Mirror of metasploit
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

core.rb 97KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322
  1. # -*- coding: binary -*-
  2. #
  3. # Rex
  4. #
  5. require 'rex/ui/text/output/buffer/stdout'
  6. #
  7. # Project
  8. #
  9. require 'msf/ui/console/command_dispatcher/encoder'
  10. require 'msf/ui/console/command_dispatcher/exploit'
  11. require 'msf/ui/console/command_dispatcher/nop'
  12. require 'msf/ui/console/command_dispatcher/payload'
  13. require 'msf/ui/console/command_dispatcher/auxiliary'
  14. require 'msf/ui/console/command_dispatcher/post'
  15. module Msf
  16. module Ui
  17. module Console
  18. module CommandDispatcher
  19. ###
  20. #
  21. # Command dispatcher for core framework commands, such as module loading,
  22. # session interaction, and other general things.
  23. #
  24. ###
  25. class Core
  26. include Msf::Ui::Console::CommandDispatcher
  27. # Session command options
  28. @@sessions_opts = Rex::Parser::Arguments.new(
  29. "-c" => [ true, "Run a command on the session given with -i, or all"],
  30. "-h" => [ false, "Help banner" ],
  31. "-i" => [ true, "Interact with the supplied session ID" ],
  32. "-l" => [ false, "List all active sessions" ],
  33. "-v" => [ false, "List verbose fields" ],
  34. "-q" => [ false, "Quiet mode" ],
  35. "-d" => [ true, "Detach an interactive session" ],
  36. "-k" => [ true, "Terminate session" ],
  37. "-K" => [ false, "Terminate all sessions" ],
  38. "-s" => [ true, "Run a script on the session given with -i, or all"],
  39. "-r" => [ false, "Reset the ring buffer for the session given with -i, or all"],
  40. "-u" => [ true, "Upgrade a win32 shell to a meterpreter session" ])
  41. @@jobs_opts = Rex::Parser::Arguments.new(
  42. "-h" => [ false, "Help banner." ],
  43. "-k" => [ true, "Terminate the specified job name." ],
  44. "-K" => [ false, "Terminate all running jobs." ],
  45. "-i" => [ true, "Lists detailed information about a running job."],
  46. "-l" => [ false, "List all running jobs." ],
  47. "-v" => [ false, "Print more detailed info. Use with -i and -l" ])
  48. @@threads_opts = Rex::Parser::Arguments.new(
  49. "-h" => [ false, "Help banner." ],
  50. "-k" => [ true, "Terminate the specified thread ID." ],
  51. "-K" => [ false, "Terminate all non-critical threads." ],
  52. "-i" => [ true, "Lists detailed information about a thread." ],
  53. "-l" => [ false, "List all background threads." ],
  54. "-v" => [ false, "Print more detailed info. Use with -i and -l" ])
  55. @@connect_opts = Rex::Parser::Arguments.new(
  56. "-h" => [ false, "Help banner." ],
  57. "-p" => [ true, "List of proxies to use." ],
  58. "-C" => [ false, "Try to use CRLF for EOL sequence." ],
  59. "-c" => [ true, "Specify which Comm to use." ],
  60. "-i" => [ true, "Send the contents of a file." ],
  61. "-P" => [ true, "Specify source port." ],
  62. "-S" => [ true, "Specify source address." ],
  63. "-s" => [ false, "Connect with SSL." ],
  64. "-u" => [ false, "Switch to a UDP socket." ],
  65. "-w" => [ true, "Specify connect timeout." ],
  66. "-z" => [ false, "Just try to connect, then return." ])
  67. @@grep_opts = Rex::Parser::Arguments.new(
  68. "-h" => [ false, "Help banner." ],
  69. "-i" => [ false, "Ignore case." ],
  70. "-m" => [ true, "Stop after arg matches." ],
  71. "-v" => [ false, "Invert match." ],
  72. "-A" => [ true, "Show arg lines of output After a match." ],
  73. "-B" => [ true, "Show arg lines of output Before a match." ],
  74. "-s" => [ true, "Skip arg lines of output before attempting match."],
  75. "-k" => [ true, "Keep (include) arg lines at start of output." ],
  76. "-c" => [ false, "Only print a count of matching lines." ])
  77. @@search_opts = Rex::Parser::Arguments.new(
  78. "-h" => [ false, "Help banner." ])
  79. @@go_pro_opts = Rex::Parser::Arguments.new(
  80. "-h" => [ false, "Help banner." ])
  81. # The list of data store elements that cannot be set when in defanged
  82. # mode.
  83. DefangedProhibitedDataStoreElements = [ "MsfModulePaths" ]
  84. # Constant for disclosure date formatting in search functions
  85. DISCLOSURE_DATE_FORMAT = "%Y-%m-%d"
  86. # Returns the list of commands supported by this command dispatcher
  87. def commands
  88. {
  89. "?" => "Help menu",
  90. "back" => "Move back from the current context",
  91. "banner" => "Display an awesome metasploit banner",
  92. "cd" => "Change the current working directory",
  93. "connect" => "Communicate with a host",
  94. "color" => "Toggle color",
  95. "exit" => "Exit the console",
  96. "edit" => "Edit the current module with $VISUAL or $EDITOR",
  97. "go_pro" => "Launch Metasploit web GUI",
  98. "grep" => "Grep the output of another command",
  99. "help" => "Help menu",
  100. "info" => "Displays information about one or more module",
  101. "irb" => "Drop into irb scripting mode",
  102. "jobs" => "Displays and manages jobs",
  103. "kill" => "Kill a job",
  104. "load" => "Load a framework plugin",
  105. "loadpath" => "Searches for and loads modules from a path",
  106. "popm" => "Pops the latest module off the stack and makes it active",
  107. "pushm" => "Pushes the active or list of modules onto the module stack",
  108. "previous" => "Sets the previously loaded module as the current module",
  109. "quit" => "Exit the console",
  110. "resource" => "Run the commands stored in a file",
  111. "makerc" => "Save commands entered since start to a file",
  112. "reload_all" => "Reloads all modules from all defined module paths",
  113. "route" => "Route traffic through a session",
  114. "save" => "Saves the active datastores",
  115. "search" => "Searches module names and descriptions",
  116. "sessions" => "Dump session listings and display information about sessions",
  117. "set" => "Sets a variable to a value",
  118. "setg" => "Sets a global variable to a value",
  119. "show" => "Displays modules of a given type, or all modules",
  120. "sleep" => "Do nothing for the specified number of seconds",
  121. "threads" => "View and manipulate background threads",
  122. "unload" => "Unload a framework plugin",
  123. "unset" => "Unsets one or more variables",
  124. "unsetg" => "Unsets one or more global variables",
  125. "use" => "Selects a module by name",
  126. "version" => "Show the framework and console library version numbers",
  127. "spool" => "Write console output into a file as well the screen"
  128. }
  129. end
  130. #
  131. # Initializes the datastore cache
  132. #
  133. def initialize(driver)
  134. super
  135. @dscache = {}
  136. @cache_payloads = nil
  137. @previous_module = nil
  138. @module_name_stack = []
  139. end
  140. #
  141. # Returns the name of the command dispatcher.
  142. #
  143. def name
  144. "Core"
  145. end
  146. # Indicates the base dir where Metasploit Framework is installed.
  147. def msfbase_dir
  148. base = __FILE__
  149. while File.symlink?(base)
  150. base = File.expand_path(File.readlink(base), File.dirname(base))
  151. end
  152. File.expand_path(
  153. File.join(File.dirname(base), "..","..","..","..","..")
  154. )
  155. end
  156. def cmd_color_help
  157. print_line "Usage: color <'true'|'false'|'auto'>"
  158. print_line
  159. print_line "Enable or disable color output."
  160. print_line
  161. end
  162. def cmd_color(*args)
  163. case args[0]
  164. when "auto"
  165. driver.output.auto_color
  166. when "true"
  167. driver.output.enable_color
  168. when "false"
  169. driver.output.disable_color
  170. else
  171. cmd_color_help
  172. return
  173. end
  174. driver.update_prompt
  175. end
  176. def cmd_reload_all_help
  177. print_line "Usage: reload_all"
  178. print_line
  179. print_line "Reload all modules from all configured module paths. This may take awhile."
  180. print_line "See also: loadpath"
  181. print_line
  182. end
  183. #
  184. # Reload all module paths that we are aware of
  185. #
  186. def cmd_reload_all(*args)
  187. if args.length > 0
  188. cmd_reload_all_help
  189. return
  190. end
  191. print_status("Reloading modules from all module paths...")
  192. framework.modules.reload_modules
  193. cmd_banner()
  194. end
  195. def cmd_resource_help
  196. print_line "Usage: resource path1 [path2 ...]"
  197. print_line
  198. print_line "Run the commands stored in the supplied files. Resource files may also contain"
  199. print_line "ruby code between <ruby></ruby> tags."
  200. print_line
  201. print_line "See also: makerc"
  202. print_line
  203. end
  204. def cmd_resource(*args)
  205. if args.empty?
  206. cmd_resource_help
  207. return false
  208. end
  209. args.each do |res|
  210. good_res = nil
  211. if (File.file? res and File.readable? res)
  212. good_res = res
  213. elsif
  214. # let's check to see if it's in the scripts/resource dir (like when tab completed)
  215. [
  216. ::Msf::Config.script_directory + File::SEPARATOR + "resource",
  217. ::Msf::Config.user_script_directory + File::SEPARATOR + "resource"
  218. ].each do |dir|
  219. res_path = dir + File::SEPARATOR + res
  220. if (File.file?(res_path) and File.readable?(res_path))
  221. good_res = res_path
  222. break
  223. end
  224. end
  225. end
  226. if good_res
  227. driver.load_resource(good_res)
  228. else
  229. print_error("#{res} is not a valid resource file")
  230. next
  231. end
  232. end
  233. end
  234. #
  235. # Tab completion for the resource command
  236. #
  237. # @param str [String] the string currently being typed before tab was hit
  238. # @param words [Array<String>] the previously completed words on the command line. words is always
  239. # at least 1 when tab completion has reached this stage since the command itself has been completed
  240. def cmd_resource_tabs(str, words)
  241. tabs = []
  242. #return tabs if words.length > 1
  243. if ( str and str =~ /^#{Regexp.escape(File::SEPARATOR)}/ )
  244. # then you are probably specifying a full path so let's just use normal file completion
  245. return tab_complete_filenames(str,words)
  246. elsif (not words[1] or not words[1].match(/^\//))
  247. # then let's start tab completion in the scripts/resource directories
  248. begin
  249. [
  250. ::Msf::Config.script_directory + File::SEPARATOR + "resource",
  251. ::Msf::Config.user_script_directory + File::SEPARATOR + "resource",
  252. "."
  253. ].each do |dir|
  254. next if not ::File.exist? dir
  255. tabs += ::Dir.new(dir).find_all { |e|
  256. path = dir + File::SEPARATOR + e
  257. ::File.file?(path) and File.readable?(path)
  258. }
  259. end
  260. rescue Exception
  261. end
  262. else
  263. tabs += tab_complete_filenames(str,words)
  264. end
  265. return tabs
  266. end
  267. def cmd_makerc_help
  268. print_line "Usage: makerc <output rc file>"
  269. print_line
  270. print_line "Save the commands executed since startup to the specified file."
  271. print_line
  272. end
  273. #
  274. # Saves commands executed since the ui started to the specified msfrc file
  275. #
  276. def cmd_makerc(*args)
  277. if args.empty?
  278. cmd_makerc_help
  279. return false
  280. end
  281. driver.save_recent_history(args[0])
  282. end
  283. def cmd_back_help
  284. print_line "Usage: back"
  285. print_line
  286. print_line "Return to the global dispatcher context"
  287. print_line
  288. end
  289. #
  290. # Pop the current dispatcher stack context, assuming it isn't pointed at
  291. # the core or database backend stack context.
  292. #
  293. def cmd_back(*args)
  294. if (driver.dispatcher_stack.size > 1 and
  295. driver.current_dispatcher.name != 'Core' and
  296. driver.current_dispatcher.name != 'Database Backend')
  297. # Reset the active module if we have one
  298. if (active_module)
  299. # Do NOT reset the UI anymore
  300. # active_module.reset_ui
  301. # Save the module's datastore so that we can load it later
  302. # if the module is used again
  303. @dscache[active_module.fullname] = active_module.datastore.dup
  304. self.active_module = nil
  305. end
  306. # Destack the current dispatcher
  307. driver.destack_dispatcher
  308. # Restore the prompt
  309. prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  310. prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  311. driver.update_prompt("#{prompt} ", prompt_char, true)
  312. end
  313. end
  314. def cmd_cd_help
  315. print_line "Usage: cd <directory>"
  316. print_line
  317. print_line "Change the current working directory"
  318. print_line
  319. end
  320. #
  321. # Change the current working directory
  322. #
  323. def cmd_cd(*args)
  324. if(args.length == 0)
  325. print_error("No path specified")
  326. return
  327. end
  328. begin
  329. Dir.chdir(args.join(" ").strip)
  330. rescue ::Exception
  331. print_error("The specified path does not exist")
  332. end
  333. end
  334. def cmd_banner_help
  335. print_line "Usage: banner"
  336. print_line
  337. print_line "Print a stunning ascii art banner along with version information and module counts"
  338. print_line
  339. end
  340. #
  341. # Display one of the fabulous banners.
  342. #
  343. def cmd_banner(*args)
  344. banner = "%cya" + Banner.to_s + "%clr\n\n"
  345. # These messages should /not/ show up when you're on a git checkout;
  346. # you're a developer, so you already know all this.
  347. if (is_apt || binary_install)
  348. content = [
  349. "Trouble managing data? List, sort, group, tag and search your pentest data\nin Metasploit Pro -- learn more on http://rapid7.com/metasploit",
  350. "Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with\nMetasploit Pro -- learn more on http://rapid7.com/metasploit",
  351. "Payload caught by AV? Fly under the radar with Dynamic Payloads in\nMetasploit Pro -- learn more on http://rapid7.com/metasploit",
  352. "Easy phishing: Set up email templates, landing pages and listeners\nin Metasploit Pro -- learn more on http://rapid7.com/metasploit",
  353. "Taking notes in notepad? Have Metasploit Pro track & report\nyour progress and findings -- learn more on http://rapid7.com/metasploit",
  354. "Tired of typing 'set RHOSTS'? Click & pwn with Metasploit Pro\nLearn more on http://rapid7.com/metasploit",
  355. "Love leveraging credentials? Check out bruteforcing\nin Metasploit Pro -- learn more on http://rapid7.com/metasploit",
  356. "Save 45% of your time on large engagements with Metasploit Pro\nLearn more on http://rapid7.com/metasploit",
  357. "Validate lots of vulnerabilities to demonstrate exposure\nwith Metasploit Pro -- Learn more on http://rapid7.com/metasploit"
  358. ]
  359. banner << content.sample # Ruby 1.9-ism!
  360. banner << "\n\n"
  361. end
  362. avdwarn = nil
  363. banner_trailers = {
  364. :version => "%yelmetasploit v#{Msf::Framework::Version} [core:#{Msf::Framework::VersionCore} api:#{Msf::Framework::VersionAPI}]%clr",
  365. :exp_aux_pos => "#{framework.stats.num_exploits} exploits - #{framework.stats.num_auxiliary} auxiliary - #{framework.stats.num_post} post",
  366. :pay_enc_nop => "#{framework.stats.num_payloads} payloads - #{framework.stats.num_encoders} encoders - #{framework.stats.num_nops} nops",
  367. :free_trial => "Free Metasploit Pro trial: http://r-7.co/trymsp",
  368. :padding => 48
  369. }
  370. banner << (" =[ %-#{banner_trailers[:padding]+8}s]\n" % banner_trailers[:version])
  371. banner << ("+ -- --=[ %-#{banner_trailers[:padding]}s]\n" % banner_trailers[:exp_aux_pos])
  372. banner << ("+ -- --=[ %-#{banner_trailers[:padding]}s]\n" % banner_trailers[:pay_enc_nop])
  373. # TODO: People who are already on a Pro install shouldn't see this.
  374. # It's hard for Framework to tell the difference though since
  375. # license details are only in Pro -- we can't see them from here.
  376. banner << ("+ -- --=[ %-#{banner_trailers[:padding]}s]\n" % banner_trailers[:free_trial])
  377. if ::Msf::Framework::EICARCorrupted
  378. avdwarn = []
  379. avdwarn << "Warning: This copy of the Metasploit Framework has been corrupted by an installed anti-virus program."
  380. avdwarn << " We recommend that you disable your anti-virus or exclude your Metasploit installation path,"
  381. avdwarn << " then restore the removed files from quarantine or reinstall the framework. For more info: "
  382. avdwarn << " https://community.rapid7.com/docs/DOC-1273"
  383. avdwarn << ""
  384. end
  385. # Display the banner
  386. print_line(banner)
  387. if(avdwarn)
  388. avdwarn.map{|line| print_error(line) }
  389. end
  390. end
  391. def cmd_connect_help
  392. print_line "Usage: connect [options] <host> <port>"
  393. print_line
  394. print_line "Communicate with a host, similar to interacting via netcat, taking advantage of"
  395. print_line "any configured session pivoting."
  396. print @@connect_opts.usage
  397. end
  398. #
  399. # Talk to a host
  400. #
  401. def cmd_connect(*args)
  402. if args.length < 2 or args.include?("-h")
  403. cmd_connect_help
  404. return false
  405. end
  406. crlf = false
  407. commval = nil
  408. fileval = nil
  409. proxies = nil
  410. srcaddr = nil
  411. srcport = nil
  412. ssl = false
  413. udp = false
  414. cto = nil
  415. justconn = false
  416. aidx = 0
  417. @@connect_opts.parse(args) do |opt, idx, val|
  418. case opt
  419. when "-C"
  420. crlf = true
  421. aidx = idx + 1
  422. when "-c"
  423. commval = val
  424. aidx = idx + 2
  425. when "-i"
  426. fileval = val
  427. aidx = idx + 2
  428. when "-P"
  429. srcport = val
  430. aidx = idx + 2
  431. when "-p"
  432. proxies = val
  433. aidx = idx + 2
  434. when "-S"
  435. srcaddr = val
  436. aidx = idx + 2
  437. when "-s"
  438. ssl = true
  439. aidx = idx + 1
  440. when "-w"
  441. cto = val.to_i
  442. aidx = idx + 2
  443. when "-u"
  444. udp = true
  445. aidx = idx + 1
  446. when "-z"
  447. justconn = true
  448. aidx = idx + 1
  449. end
  450. end
  451. commval = "Local" if commval =~ /local/i
  452. if fileval
  453. begin
  454. raise "Not a file" if File.ftype(fileval) != "file"
  455. infile = ::File.open(fileval)
  456. rescue
  457. print_error("Can't read from '#{fileval}': #{$!}")
  458. return false
  459. end
  460. end
  461. args = args[aidx .. -1]
  462. if args.length < 2
  463. print_error("You must specify a host and port")
  464. return false
  465. end
  466. host = args[0]
  467. port = args[1]
  468. comm = nil
  469. if commval
  470. begin
  471. if Rex::Socket::Comm.const_defined?(commval)
  472. comm = Rex::Socket::Comm.const_get(commval)
  473. end
  474. rescue NameError
  475. end
  476. if not comm
  477. session = framework.sessions.get(commval)
  478. if session.kind_of?(Msf::Session::Comm)
  479. comm = session
  480. end
  481. end
  482. if not comm
  483. print_error("Invalid comm '#{commval}' selected")
  484. return false
  485. end
  486. end
  487. begin
  488. klass = udp ? ::Rex::Socket::Udp : ::Rex::Socket::Tcp
  489. sock = klass.create({
  490. 'Comm' => comm,
  491. 'Proxies' => proxies,
  492. 'SSL' => ssl,
  493. 'PeerHost' => host,
  494. 'PeerPort' => port,
  495. 'LocalHost' => srcaddr,
  496. 'LocalPort' => srcport,
  497. 'Timeout' => cto,
  498. 'Context' => {
  499. 'Msf' => framework
  500. }
  501. })
  502. rescue
  503. print_error("Unable to connect: #{$!}")
  504. return false
  505. end
  506. print_status("Connected to #{host}:#{port}")
  507. if justconn
  508. sock.close
  509. infile.close if infile
  510. return true
  511. end
  512. cin = infile || driver.input
  513. cout = driver.output
  514. begin
  515. # Console -> Network
  516. c2n = framework.threads.spawn("ConnectConsole2Network", false, cin, sock) do |input, output|
  517. while true
  518. begin
  519. res = input.gets
  520. break if not res
  521. if crlf and (res =~ /^\n$/ or res =~ /[^\r]\n$/)
  522. res.gsub!(/\n$/, "\r\n")
  523. end
  524. output.write res
  525. rescue ::EOFError, ::IOError
  526. break
  527. end
  528. end
  529. end
  530. # Network -> Console
  531. n2c = framework.threads.spawn("ConnectNetwork2Console", false, sock, cout, c2n) do |input, output, cthr|
  532. while true
  533. begin
  534. res = input.read(65535)
  535. break if not res
  536. output.print res
  537. rescue ::EOFError, ::IOError
  538. break
  539. end
  540. end
  541. Thread.kill(cthr)
  542. end
  543. c2n.join
  544. rescue ::Interrupt
  545. c2n.kill
  546. n2c.kill
  547. end
  548. sock.close rescue nil
  549. infile.close if infile
  550. true
  551. end
  552. def local_editor
  553. Rex::Compat.getenv('VISUAL') || Rex::Compat.getenv('EDITOR') || '/usr/bin/vim'
  554. end
  555. def cmd_edit_help
  556. msg = "Edit the currently active module"
  557. msg = "#{msg} #{local_editor ? "with #{local_editor}" : "($VISUAL or $EDITOR must be set first)"}."
  558. print_line "Usage: edit"
  559. print_line
  560. print_line msg
  561. print_line "When done editing, you must reload the module with 'reload' or 'rexploit'."
  562. print_line
  563. end
  564. #
  565. # Edit the currently active module
  566. #
  567. def cmd_edit
  568. unless local_editor
  569. print_error "$VISUAL or $EDITOR must be set first. Try 'export EDITOR=/usr/bin/vim'"
  570. return
  571. end
  572. if active_module
  573. path = active_module.file_path
  574. print_status "Launching #{local_editor} #{path}"
  575. system(local_editor,path)
  576. else
  577. print_error "Nothing to edit -- try using a module first."
  578. end
  579. end
  580. #
  581. # Instructs the driver to stop executing.
  582. #
  583. def cmd_exit(*args)
  584. forced = false
  585. forced = true if (args[0] and args[0] =~ /-y/i)
  586. if(framework.sessions.length > 0 and not forced)
  587. print_status("You have active sessions open, to exit anyway type \"exit -y\"")
  588. return
  589. elsif(driver.confirm_exit and not forced)
  590. print("Are you sure you want to exit Metasploit? [y/N]: ")
  591. response = gets.downcase.chomp
  592. if(response == "y" || response == "yes")
  593. driver.stop
  594. else
  595. return
  596. end
  597. end
  598. driver.stop
  599. end
  600. alias cmd_quit cmd_exit
  601. def cmd_sleep_help
  602. print_line "Usage: sleep <seconds>"
  603. print_line
  604. print_line "Do nothing the specified number of seconds. This is useful in rc scripts."
  605. print_line
  606. end
  607. #
  608. # Causes process to pause for the specified number of seconds
  609. #
  610. def cmd_sleep(*args)
  611. return if not (args and args.length == 1)
  612. Rex::ThreadSafe.sleep(args[0].to_f)
  613. end
  614. def cmd_info_help
  615. print_line "Usage: info <module name> [mod2 mod3 ...]"
  616. print_line
  617. print_line "Queries the supplied module or modules for information. If no module is given,"
  618. print_line "show info for the currently active module."
  619. print_line
  620. end
  621. #
  622. # Displays information about one or more module.
  623. #
  624. def cmd_info(*args)
  625. if (args.length == 0)
  626. if (active_module)
  627. print(Serializer::ReadableText.dump_module(active_module))
  628. return true
  629. else
  630. cmd_info_help
  631. return false
  632. end
  633. elsif args.include? "-h"
  634. cmd_info_help
  635. return false
  636. end
  637. args.each { |name|
  638. mod = framework.modules.create(name)
  639. if (mod == nil)
  640. print_error("Invalid module: #{name}")
  641. else
  642. print(Serializer::ReadableText.dump_module(mod))
  643. end
  644. }
  645. end
  646. #
  647. # Tab completion for the info command (same as use)
  648. #
  649. # @param str [String] the string currently being typed before tab was hit
  650. # @param words [Array<String>] the previously completed words on the command line. words is always
  651. # at least 1 when tab completion has reached this stage since the command itself has been completed
  652. def cmd_info_tabs(str, words)
  653. cmd_use_tabs(str, words)
  654. end
  655. def cmd_irb_help
  656. print_line "Usage: irb"
  657. print_line
  658. print_line "Drop into an interactive Ruby environment"
  659. print_line
  660. end
  661. #
  662. # Goes into IRB scripting mode
  663. #
  664. def cmd_irb(*args)
  665. defanged?
  666. print_status("Starting IRB shell...\n")
  667. begin
  668. Rex::Ui::Text::IrbShell.new(binding).run
  669. rescue
  670. print_error("Error during IRB: #{$!}\n\n#{$@.join("\n")}")
  671. end
  672. # Reset tab completion
  673. if (driver.input.supports_readline)
  674. driver.input.reset_tab_completion
  675. end
  676. end
  677. def cmd_jobs_help
  678. print_line "Usage: jobs [options]"
  679. print_line
  680. print_line "Active job manipulation and interaction."
  681. print @@jobs_opts.usage()
  682. end
  683. #
  684. # Displays and manages running jobs for the active instance of the
  685. # framework.
  686. #
  687. def cmd_jobs(*args)
  688. # Make the default behavior listing all jobs if there were no options
  689. # or the only option is the verbose flag
  690. if (args.length == 0 or args == ["-v"])
  691. args.unshift("-l")
  692. end
  693. verbose = false
  694. dump_list = false
  695. dump_info = false
  696. job_id = nil
  697. # Parse the command options
  698. @@jobs_opts.parse(args) { |opt, idx, val|
  699. case opt
  700. when "-v"
  701. verbose = true
  702. when "-l"
  703. dump_list = true
  704. # Terminate the supplied job name
  705. when "-k"
  706. if (not framework.jobs.has_key?(val))
  707. print_error("No such job")
  708. else
  709. print_line("Stopping job: #{val}...")
  710. framework.jobs.stop_job(val)
  711. end
  712. when "-K"
  713. print_line("Stopping all jobs...")
  714. framework.jobs.each_key do |i|
  715. framework.jobs.stop_job(i)
  716. end
  717. when "-i"
  718. # Defer printing anything until the end of option parsing
  719. # so we can check for the verbose flag.
  720. dump_info = true
  721. job_id = val
  722. when "-h"
  723. cmd_jobs_help
  724. return false
  725. end
  726. }
  727. if (dump_list)
  728. print("\n" + Serializer::ReadableText.dump_jobs(framework, verbose) + "\n")
  729. end
  730. if (dump_info)
  731. if (job_id and framework.jobs[job_id.to_s])
  732. job = framework.jobs[job_id.to_s]
  733. mod = job.ctx[0]
  734. output = "\n"
  735. output += "Name: #{mod.name}"
  736. output += ", started at #{job.start_time}" if job.start_time
  737. print_line(output)
  738. if (mod.options.has_options?)
  739. show_options(mod)
  740. end
  741. if (verbose)
  742. mod_opt = Serializer::ReadableText.dump_advanced_options(mod,' ')
  743. print_line("\nModule advanced options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
  744. end
  745. else
  746. print_line("Invalid Job ID")
  747. end
  748. end
  749. end
  750. #
  751. # Tab completion for the jobs command
  752. #
  753. # @param str [String] the string currently being typed before tab was hit
  754. # @param words [Array<String>] the previously completed words on the command line. words is always
  755. # at least 1 when tab completion has reached this stage since the command itself has been completed
  756. def cmd_jobs_tabs(str, words)
  757. if words.length == 1
  758. return @@jobs_opts.fmt.keys
  759. end
  760. if @@jobs_opts.fmt[words[1]][0] and (words.length == 2)
  761. return framework.jobs.keys
  762. end
  763. []
  764. end
  765. def cmd_kill_help
  766. print_line "Usage: kill <job1> [job2 ...]"
  767. print_line
  768. print_line "Equivalent to 'jobs -k job1 -k job2 ...'"
  769. print @@jobs_opts.usage()
  770. end
  771. def cmd_kill(*args)
  772. cmd_jobs("-k", *args)
  773. end
  774. #
  775. # Tab completion for the kill command
  776. #
  777. # @param str [String] the string currently being typed before tab was hit
  778. # @param words [Array<String>] the previously completed words on the command line. words is always
  779. # at least 1 when tab completion has reached this stage since the command itself has been completed
  780. def cmd_kill_tabs(str, words)
  781. return [] if words.length > 1
  782. framework.jobs.keys
  783. end
  784. def cmd_threads_help
  785. print_line "Usage: threads [options]"
  786. print_line
  787. print_line "Background thread management."
  788. print_line @@threads_opts.usage()
  789. end
  790. #
  791. # Displays and manages running background threads
  792. #
  793. def cmd_threads(*args)
  794. # Make the default behavior listing all jobs if there were no options
  795. # or the only option is the verbose flag
  796. if (args.length == 0 or args == ["-v"])
  797. args.unshift("-l")
  798. end
  799. verbose = false
  800. dump_list = false
  801. dump_info = false
  802. thread_id = nil
  803. # Parse the command options
  804. @@threads_opts.parse(args) { |opt, idx, val|
  805. case opt
  806. when "-v"
  807. verbose = true
  808. when "-l"
  809. dump_list = true
  810. # Terminate the supplied thread id
  811. when "-k"
  812. val = val.to_i
  813. if not framework.threads[val]
  814. print_error("No such thread")
  815. else
  816. print_line("Terminating thread: #{val}...")
  817. framework.threads.kill(val)
  818. end
  819. when "-K"
  820. print_line("Killing all non-critical threads...")
  821. framework.threads.each_index do |i|
  822. t = framework.threads[i]
  823. next if not t
  824. next if t[:tm_crit]
  825. framework.threads.kill(i)
  826. end
  827. when "-i"
  828. # Defer printing anything until the end of option parsing
  829. # so we can check for the verbose flag.
  830. dump_info = true
  831. thread_id = val.to_i
  832. when "-h"
  833. cmd_threads_help
  834. return false
  835. end
  836. }
  837. if (dump_list)
  838. tbl = Table.new(
  839. Table::Style::Default,
  840. 'Header' => "Background Threads",
  841. 'Prefix' => "\n",
  842. 'Postfix' => "\n",
  843. 'Columns' =>
  844. [
  845. 'ID',
  846. 'Status',
  847. 'Critical',
  848. 'Name',
  849. 'Started'
  850. ]
  851. )
  852. framework.threads.each_index do |i|
  853. t = framework.threads[i]
  854. next if not t
  855. tbl << [ i.to_s, t.status || "dead", t[:tm_crit] ? "True" : "False", t[:tm_name].to_s, t[:tm_time].to_s ]
  856. end
  857. print(tbl.to_s)
  858. end
  859. if (dump_info)
  860. thread = framework.threads[thread_id]
  861. if (thread)
  862. output = "\n"
  863. output += " ID: #{thread_id}\n"
  864. output += "Name: #{thread[:tm_name]}\n"
  865. output += "Info: #{thread.status || "dead"}\n"
  866. output += "Crit: #{thread[:tm_crit] ? "True" : "False"}\n"
  867. output += "Time: #{thread[:tm_time].to_s}\n"
  868. if (verbose)
  869. output += "\n"
  870. output += "Thread Source\n"
  871. output += "=============\n"
  872. thread[:tm_call].each do |c|
  873. output += " #{c.to_s}\n"
  874. end
  875. output += "\n"
  876. end
  877. print(output +"\n")
  878. else
  879. print_line("Invalid Thread ID")
  880. end
  881. end
  882. end
  883. #
  884. # Tab completion for the threads command
  885. #
  886. # @param str [String] the string currently being typed before tab was hit
  887. # @param words [Array<String>] the previously completed words on the command line. words is always
  888. # at least 1 when tab completion has reached this stage since the command itself has been completed
  889. def cmd_threads_tabs(str, words)
  890. if words.length == 1
  891. return @@threads_opts.fmt.keys
  892. end
  893. if @@threads_opts.fmt[words[1]][0] and (words.length == 2)
  894. return framework.threads.each_index.map{ |idx| idx.to_s }
  895. end
  896. []
  897. end
  898. def cmd_load_help
  899. print_line "Usage: load <path> [var=val var=val ...]"
  900. print_line
  901. print_line "Loads a plugin from the supplied path. If path is not absolute, first looks"
  902. print_line "in the user's plugin directory (#{Msf::Config.user_plugin_directory}) then"
  903. print_line "in the framework root plugin directory (#{Msf::Config.plugin_directory})."
  904. print_line "The optional var=val options are custom parameters that can be passed to plugins."
  905. print_line
  906. end
  907. #
  908. # Loads a plugin from the supplied path. If no absolute path is supplied,
  909. # the framework root plugin directory is used.
  910. #
  911. def cmd_load(*args)
  912. defanged?
  913. if (args.length == 0)
  914. cmd_load_help
  915. return false
  916. end
  917. # Default to the supplied argument path.
  918. path = args.shift
  919. opts = {
  920. 'LocalInput' => driver.input,
  921. 'LocalOutput' => driver.output,
  922. 'ConsoleDriver' => driver
  923. }
  924. # Parse any extra options that should be passed to the plugin
  925. args.each { |opt|
  926. k, v = opt.split(/\=/)
  927. opts[k] = v if (k and v)
  928. }
  929. # If no absolute path was supplied, check the base and user plugin directories
  930. if (path !~ /#{File::SEPARATOR}/)
  931. plugin_file_name = path
  932. # If the plugin isn't in the user directory (~/.msf3/plugins/), use the base
  933. path = Msf::Config.user_plugin_directory + File::SEPARATOR + plugin_file_name
  934. if not File.exists?( path + ".rb" )
  935. # If the following "path" doesn't exist it will be caught when we attempt to load
  936. path = Msf::Config.plugin_directory + File::SEPARATOR + plugin_file_name
  937. end
  938. end
  939. # Load that plugin!
  940. begin
  941. if (inst = framework.plugins.load(path, opts))
  942. print_status("Successfully loaded plugin: #{inst.name}")
  943. end
  944. rescue ::Exception => e
  945. elog("Error loading plugin #{path}: #{e}\n\n#{e.backtrace.join("\n")}", src = 'core', level = 0, from = caller)
  946. print_error("Failed to load plugin from #{path}: #{e}")
  947. end
  948. end
  949. #
  950. # Tab completion for the load command
  951. #
  952. # @param str [String] the string currently being typed before tab was hit
  953. # @param words [Array<String>] the previously completed words on the command line. words is always
  954. # at least 1 when tab completion has reached this stage since the command itself has been completed
  955. def cmd_load_tabs(str, words)
  956. tabs = []
  957. if (not words[1] or not words[1].match(/^\//))
  958. # then let's start tab completion in the scripts/resource directories
  959. begin
  960. [
  961. Msf::Config.user_plugin_directory,
  962. Msf::Config.plugin_directory
  963. ].each do |dir|
  964. next if not ::File.exist? dir
  965. tabs += ::Dir.new(dir).find_all { |e|
  966. path = dir + File::SEPARATOR + e
  967. ::File.file?(path) and File.readable?(path)
  968. }
  969. end
  970. rescue Exception
  971. end
  972. else
  973. tabs += tab_complete_filenames(str,words)
  974. end
  975. return tabs.map{|e| e.sub(/.rb/, '')}
  976. end
  977. def cmd_route_help
  978. print_line "Usage: route [add/remove/get/flush/print] subnet netmask [comm/sid]"
  979. print_line
  980. print_line "Route traffic destined to a given subnet through a supplied session."
  981. print_line "The default comm is Local."
  982. print_line
  983. end
  984. #
  985. # This method handles the route command which allows a user to specify
  986. # which session a given subnet should route through.
  987. #
  988. def cmd_route(*args)
  989. if (args.length == 0)
  990. cmd_route_help
  991. return false
  992. end
  993. arg = args.shift
  994. case arg
  995. when "add", "remove", "del"
  996. if (args.length < 3)
  997. print_error("Missing arguments to route #{arg}.")
  998. return false
  999. end
  1000. # Satisfy check to see that formatting is correct
  1001. unless Rex::Socket::RangeWalker.new(args[0]).length == 1
  1002. print_error "Invalid IP Address"
  1003. return false
  1004. end
  1005. unless Rex::Socket::RangeWalker.new(args[1]).length == 1
  1006. print_error "Invalid Subnet mask"
  1007. return false
  1008. end
  1009. gw = nil
  1010. # Satisfy case problems
  1011. args[2] = "Local" if (args[2] =~ /local/i)
  1012. begin
  1013. # If the supplied gateway is a global Comm, use it.
  1014. if (Rex::Socket::Comm.const_defined?(args[2]))
  1015. gw = Rex::Socket::Comm.const_get(args[2])
  1016. end
  1017. rescue NameError
  1018. end
  1019. # If we still don't have a gateway, check if it's a session.
  1020. if ((gw == nil) and
  1021. (session = framework.sessions.get(args[2])) and
  1022. (session.kind_of?(Msf::Session::Comm)))
  1023. gw = session
  1024. elsif (gw == nil)
  1025. print_error("Invalid gateway specified.")
  1026. return false
  1027. end
  1028. if arg == "remove" or arg == "del"
  1029. worked = Rex::Socket::SwitchBoard.remove_route(args[0], args[1], gw)
  1030. if worked
  1031. print_status("Route removed")
  1032. else
  1033. print_error("Route not found")
  1034. end
  1035. else
  1036. worked = Rex::Socket::SwitchBoard.add_route(args[0], args[1], gw)
  1037. if worked
  1038. print_status("Route added")
  1039. else
  1040. print_error("Route already exists")
  1041. end
  1042. end
  1043. when "get"
  1044. if (args.length == 0)
  1045. print_error("You must supply an IP address.")
  1046. return false
  1047. end
  1048. comm = Rex::Socket::SwitchBoard.best_comm(args[0])
  1049. if ((comm) and
  1050. (comm.kind_of?(Msf::Session)))
  1051. print_line("#{args[0]} routes through: Session #{comm.sid}")
  1052. else
  1053. print_line("#{args[0]} routes through: Local")
  1054. end
  1055. when "flush"
  1056. Rex::Socket::SwitchBoard.flush_routes
  1057. when "print"
  1058. tbl = Table.new(
  1059. Table::Style::Default,
  1060. 'Header' => "Active Routing Table",
  1061. 'Prefix' => "\n",
  1062. 'Postfix' => "\n",
  1063. 'Columns' =>
  1064. [
  1065. 'Subnet',
  1066. 'Netmask',
  1067. 'Gateway',
  1068. ],
  1069. 'ColProps' =>
  1070. {
  1071. 'Subnet' => { 'MaxWidth' => 17 },
  1072. 'Netmask' => { 'MaxWidth' => 17 },
  1073. })
  1074. Rex::Socket::SwitchBoard.each { |route|
  1075. if (route.comm.kind_of?(Msf::Session))
  1076. gw = "Session #{route.comm.sid}"
  1077. else
  1078. gw = route.comm.name.split(/::/)[-1]
  1079. end
  1080. tbl << [ route.subnet, route.netmask, gw ]
  1081. }
  1082. print(tbl.to_s)
  1083. else
  1084. cmd_route_help
  1085. end
  1086. end
  1087. #
  1088. # Tab completion for the route command
  1089. #
  1090. # @param str [String] the string currently being typed before tab was hit
  1091. # @param words [Array<String>] the previously completed words on the command line. words is always
  1092. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1093. def cmd_route_tabs(str, words)
  1094. if words.length == 1
  1095. return %w{add remove get flush print}
  1096. end
  1097. ret = []
  1098. case words[1]
  1099. when "remove", "del"
  1100. Rex::Socket::SwitchBoard.each { |route|
  1101. case words.length
  1102. when 2
  1103. ret << route.subnet
  1104. when 3
  1105. if route.subnet == words[2]
  1106. ret << route.netmask
  1107. end
  1108. when 4
  1109. if route.subnet == words[2]
  1110. ret << route.comm.sid.to_s if route.comm.kind_of? Msf::Session
  1111. end
  1112. end
  1113. }
  1114. ret
  1115. when "add"
  1116. # We can't really complete the subnet and netmask args without
  1117. # diving pretty deep into all sessions, so just be content with
  1118. # completing sids for the last arg
  1119. if words.length == 4
  1120. ret = framework.sessions.keys.map { |k| k.to_s }
  1121. end
  1122. # The "get" command takes one arg, but we can't complete it either...
  1123. end
  1124. ret
  1125. end
  1126. def cmd_save_help
  1127. print_line "Usage: save"
  1128. print_line
  1129. print_line "Save the active datastore contents to disk for automatic use across restarts of the console"
  1130. print_line
  1131. print_line "The configuration is stored in #{Msf::Config.config_file}"
  1132. print_line
  1133. end
  1134. #
  1135. # Saves the active datastore contents to disk for automatic use across
  1136. # restarts of the console.
  1137. #
  1138. def cmd_save(*args)
  1139. defanged?
  1140. # Save the console config
  1141. driver.save_config
  1142. # Save the framework's datastore
  1143. begin
  1144. framework.save_config
  1145. if (active_module)
  1146. active_module.save_config
  1147. end
  1148. rescue
  1149. log_error("Save failed: #{$!}")
  1150. return false
  1151. end
  1152. print_line("Saved configuration to: #{Msf::Config.config_file}")
  1153. end
  1154. def cmd_loadpath_help
  1155. print_line "Usage: loadpath </path/to/modules>"
  1156. print_line
  1157. print_line "Loads modules from the given directory which should contain subdirectories for"
  1158. print_line "module types, e.g. /path/to/modules/exploits"
  1159. print_line
  1160. end
  1161. #
  1162. # Adds one or more search paths.
  1163. #
  1164. def cmd_loadpath(*args)
  1165. defanged?
  1166. if (args.length == 0 or args.include? "-h")
  1167. cmd_loadpath_help
  1168. return true
  1169. end
  1170. totals = {}
  1171. overall = 0
  1172. curr_path = nil
  1173. begin
  1174. # Walk the list of supplied search paths attempting to add each one
  1175. # along the way
  1176. args.each { |path|
  1177. curr_path = path
  1178. # Load modules, but do not consult the cache
  1179. if (counts = framework.modules.add_module_path(path))
  1180. counts.each_pair { |type, count|
  1181. totals[type] = (totals[type]) ? (totals[type] + count) : count
  1182. overall += count
  1183. }
  1184. end
  1185. }
  1186. rescue NameError, RuntimeError
  1187. log_error("Failed to add search path #{curr_path}: #{$!}")
  1188. return true
  1189. end
  1190. added = "Loaded #{overall} modules:\n"
  1191. totals.each_pair { |type, count|
  1192. added << " #{count} #{type}#{count != 1 ? 's' : ''}\n"
  1193. }
  1194. print(added)
  1195. end
  1196. #
  1197. # Tab completion for the loadpath command
  1198. #
  1199. # @param str [String] the string currently being typed before tab was hit
  1200. # @param words [Array<String>] the previously completed words on the command line. words is always
  1201. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1202. def cmd_loadpath_tabs(str, words)
  1203. return [] if words.length > 1
  1204. # This custom completion might better than Readline's... We'll leave it for now.
  1205. #tab_complete_filenames(str,words)
  1206. paths = []
  1207. if (File.directory?(str))
  1208. paths = Dir.entries(str)
  1209. paths = paths.map { |f|
  1210. if File.directory? File.join(str,f)
  1211. File.join(str,f)
  1212. end
  1213. }
  1214. paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
  1215. else
  1216. d = Dir.glob(str + "*").map { |f| f if File.directory?(f) }
  1217. d.delete_if { |f| f.nil? or f == '.' or f == '..' }
  1218. # If there's only one possibility, descend to the next level
  1219. if (1 == d.length)
  1220. paths = Dir.entries(d[0])
  1221. paths = paths.map { |f|
  1222. if File.directory? File.join(d[0],f)
  1223. File.join(d[0],f)
  1224. end
  1225. }
  1226. paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
  1227. else
  1228. paths = d
  1229. end
  1230. end
  1231. paths.sort!
  1232. return paths
  1233. end
  1234. def cmd_search_help
  1235. print_line "Usage: search [keywords]"
  1236. print_line
  1237. print_line "Keywords:"
  1238. {
  1239. 'app' => 'Modules that are client or server attacks',
  1240. 'author' => 'Modules written by this author',
  1241. 'bid' => 'Modules with a matching Bugtraq ID',
  1242. 'cve' => 'Modules with a matching CVE ID',
  1243. 'edb' => 'Modules with a matching Exploit-DB ID',
  1244. 'name' => 'Modules with a matching descriptive name',
  1245. 'osvdb' => 'Modules with a matching OSVDB ID',
  1246. 'platform' => 'Modules affecting this platform',
  1247. 'ref' => 'Modules with a matching ref',
  1248. 'type' => 'Modules of a specific type (exploit, auxiliary, or post)',
  1249. }.each_pair do |keyword, description|
  1250. print_line " #{keyword.ljust 10}: #{description}"
  1251. end
  1252. print_line
  1253. print_line "Examples:"
  1254. print_line " search cve:2009 type:exploit app:client"
  1255. print_line
  1256. end
  1257. #
  1258. # Searches modules for specific keywords
  1259. #
  1260. def cmd_search(*args)
  1261. match = ''
  1262. @@search_opts.parse(args) { |opt, idx, val|
  1263. case opt
  1264. when "-t"
  1265. print_error("Deprecated option. Use type:#{val} instead")
  1266. cmd_search_help
  1267. return
  1268. when "-h"
  1269. cmd_search_help
  1270. return
  1271. else
  1272. match += val + " "
  1273. end
  1274. }
  1275. if framework.db and framework.db.migrated and framework.db.modules_cached
  1276. search_modules_sql(match)
  1277. return
  1278. end
  1279. print_warning("Database not connected or cache not built, using slow search")
  1280. tbl = generate_module_table("Matching Modules")
  1281. [
  1282. framework.exploits,
  1283. framework.auxiliary,
  1284. framework.post,
  1285. framework.payloads,
  1286. framework.nops,
  1287. framework.encoders
  1288. ].each do |mset|
  1289. mset.each do |m|
  1290. o = mset.create(m[0]) rescue nil
  1291. # Expected if modules are loaded without the right pre-requirements
  1292. next if not o
  1293. if not o.search_filter(match)
  1294. tbl << [ o.fullname, o.disclosure_date.nil? ? "" : o.disclosure_date.strftime(DISCLOSURE_DATE_FORMAT), o.rank_to_s, o.name ]
  1295. end
  1296. end
  1297. end
  1298. print_line(tbl.to_s)
  1299. end
  1300. # Prints table of modules matching the search_string.
  1301. #
  1302. # @param (see Msf::DBManager#search_modules)
  1303. # @return [void]
  1304. def search_modules_sql(search_string)
  1305. tbl = generate_module_table("Matching Modules")
  1306. framework.db.search_modules(search_string).each do |o|
  1307. tbl << [ o.fullname, o.disclosure_date.nil? ? "" : o.disclosure_date.strftime(DISCLOSURE_DATE_FORMAT), RankingName[o.rank].to_s, o.name ]
  1308. end
  1309. print_line(tbl.to_s)
  1310. end
  1311. #
  1312. # Tab completion for the search command
  1313. #
  1314. # @param str [String] the string currently being typed before tab was hit
  1315. # @param words [Array<String>] the previously completed words on the command line. words is always
  1316. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1317. def cmd_search_tabs(str, words)
  1318. if words.length == 1
  1319. return @@search_opts.fmt.keys
  1320. end
  1321. case (words[-1])
  1322. when "-r"
  1323. return RankingName.sort.map{|r| r[1]}
  1324. when "-t"
  1325. return %w{auxiliary encoder exploit nop payload post}
  1326. end
  1327. []
  1328. end
  1329. def cmd_spool_help
  1330. print_line "Usage: spool <off>|<filename>"
  1331. print_line
  1332. print_line "Example:"
  1333. print_line " spool /tmp/console.log"
  1334. print_line
  1335. end
  1336. def cmd_spool(*args)
  1337. if args.include?('-h') or args.empty?
  1338. cmd_spool_help
  1339. return
  1340. end
  1341. color = driver.output.config[:color]
  1342. if args[0] == "off"
  1343. driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new)
  1344. msg = "Spooling is now disabled"
  1345. else
  1346. driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(args[0]))
  1347. msg = "Spooling to file #{args[0]}..."
  1348. end
  1349. # Restore color and prompt
  1350. driver.output.config[:color] = color
  1351. prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  1352. if active_module
  1353. # intentionally += and not << because we don't want to modify
  1354. # datastore or the constant DefaultPrompt
  1355. prompt += " #{active_module.type}(%bld%red#{active_module.shortname}%clr)"
  1356. end
  1357. prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  1358. driver.update_prompt("#{prompt} ", prompt_char, true)
  1359. print_status(msg)
  1360. return
  1361. end
  1362. def cmd_sessions_help
  1363. print_line "Usage: sessions [options]"
  1364. print_line
  1365. print_line "Active session manipulation and interaction."
  1366. print(@@sessions_opts.usage())
  1367. end
  1368. #
  1369. # Provides an interface to the sessions currently active in the framework.
  1370. #
  1371. def cmd_sessions(*args)
  1372. begin
  1373. method = nil
  1374. quiet = false
  1375. verbose = false
  1376. sid = nil
  1377. cmds = []
  1378. script = nil
  1379. reset_ring = false
  1380. # any arguments that don't correspond to an option or option arg will
  1381. # be put in here
  1382. extra = []
  1383. # Parse the command options
  1384. @@sessions_opts.parse(args) { |opt, idx, val|
  1385. case opt
  1386. when "-q"
  1387. quiet = true
  1388. # Run a command on all sessions, or the session given with -i
  1389. when "-c"
  1390. method = 'cmd'
  1391. if (val)
  1392. cmds << val
  1393. end
  1394. when "-v"
  1395. verbose = true
  1396. # Do something with the supplied session identifier instead of
  1397. # all sessions.
  1398. when "-i"
  1399. sid = val
  1400. # Display the list of active sessions
  1401. when "-l"
  1402. method = 'list'
  1403. when "-k"
  1404. method = 'kill'
  1405. sid = val if val
  1406. if not sid
  1407. print_error("Specify a session to kill")
  1408. return false
  1409. end
  1410. when "-K"
  1411. method = 'killall'
  1412. when "-d"
  1413. method = 'detach'
  1414. sid = val
  1415. # Run a script on all meterpreter sessions
  1416. when "-s"
  1417. if not script
  1418. method = 'scriptall'
  1419. script = val
  1420. end
  1421. # Upload and exec to the specific command session
  1422. when "-u"
  1423. method = 'upexec'
  1424. sid = val
  1425. # Reset the ring buffer read pointer
  1426. when "-r"
  1427. reset_ring = true
  1428. method = 'reset_ring'
  1429. # Display help banner
  1430. when "-h"
  1431. cmd_sessions_help
  1432. return false
  1433. else
  1434. extra << val
  1435. end
  1436. }
  1437. if sid and not framework.sessions.get(sid)
  1438. print_error("Invalid session id")
  1439. return false
  1440. end
  1441. if method.nil? and sid
  1442. method = 'interact'
  1443. end
  1444. # Now, perform the actual method
  1445. case method
  1446. when 'cmd'
  1447. if (cmds.length < 1)
  1448. print_error("No command specified!")
  1449. return false
  1450. end
  1451. cmds.each do |cmd|
  1452. if sid
  1453. sessions = [ sid ]
  1454. else
  1455. sessions = framework.sessions.keys.sort
  1456. end
  1457. sessions.each do |s|
  1458. session = framework.sessions.get(s)
  1459. print_status("Running '#{cmd}' on #{session.type} session #{s} (#{session.session_host})")
  1460. if (session.type == "meterpreter")
  1461. # If session.sys is nil, dont even try..
  1462. if not (session.sys)
  1463. print_error("Session #{s} does not have stdapi loaded, skipping...")
  1464. next
  1465. end
  1466. c, c_args = cmd.split(' ', 2)
  1467. begin
  1468. process = session.sys.process.execute(c, c_args,
  1469. {
  1470. 'Channelized' => true,
  1471. 'Hidden' => true
  1472. })
  1473. rescue ::Rex::Post::Meterpreter::RequestError
  1474. print_error("Failed: #{$!.class} #{$!}")
  1475. end
  1476. if process and process.channel and (data = process.channel.read)
  1477. print_line(data)
  1478. end
  1479. elsif session.type == "shell"
  1480. if (output = session.shell_command(cmd))
  1481. print_line(output)
  1482. end
  1483. end
  1484. # If the session isn't a meterpreter or shell type, it
  1485. # could be a VNC session (which can't run commands) or
  1486. # something custom (which we don't know how to run
  1487. # commands on), so don't bother.
  1488. end
  1489. end
  1490. when 'kill'
  1491. if ((session = framework.sessions.get(sid)))
  1492. print_status("Killing session #{sid}")
  1493. session.kill
  1494. else
  1495. print_error("Invalid session identifier: #{sid}")
  1496. end
  1497. when 'killall'
  1498. print_status("Killing all sessions...")
  1499. framework.sessions.each_sorted do |s|
  1500. if ((session = framework.sessions.get(s)))
  1501. session.kill
  1502. end
  1503. end
  1504. when 'detach'
  1505. if ((session = framework.sessions.get(sid)))
  1506. print_status("Detaching session #{sid}")
  1507. if (session.interactive?)
  1508. session.detach()
  1509. end
  1510. else
  1511. print_error("Invalid session identifier: #{sid}")
  1512. end
  1513. when 'interact'
  1514. if ((session = framework.sessions.get(sid)))
  1515. if (session.interactive?)
  1516. print_status("Starting interaction with #{session.name}...\n") if (quiet == false)
  1517. self.active_session = session
  1518. session.interact(driver.input.dup, driver.output)
  1519. self.active_session = nil
  1520. if (driver.input.supports_readline)
  1521. driver.input.reset_tab_completion
  1522. end
  1523. else
  1524. print_error("Session #{sid} is non-interactive.")
  1525. end
  1526. else
  1527. print_error("Invalid session identifier: #{sid}")
  1528. end
  1529. when 'scriptall'
  1530. if (script.nil?)
  1531. print_error("No script specified!")
  1532. return false
  1533. end
  1534. script_paths = {}
  1535. script_paths['meterpreter'] = Msf::Sessions::Meterpreter.find_script_path(script)
  1536. script_paths['shell'] = Msf::Sessions::CommandShell.find_script_path(script)
  1537. if sid
  1538. print_status("Running script #{script} on session #{sid}...")
  1539. sessions = [ sid ]
  1540. else
  1541. print_status("Running script #{script} on all sessions...")
  1542. sessions = framework.sessions.keys.sort
  1543. end
  1544. sessions.each do |s|
  1545. if ((session = framework.sessions.get(s)))
  1546. if (script_paths[session.type])
  1547. print_status("Session #{s} (#{session.session_host}):")
  1548. begin
  1549. session.execute_file(script_paths[session.type], extra)
  1550. rescue ::Exception => e
  1551. log_error("Error executing script: #{e.class} #{e}")
  1552. end
  1553. end
  1554. end
  1555. end
  1556. when 'upexec'
  1557. if ((session = framework.sessions.get(sid)))
  1558. if (session.interactive?)
  1559. if (session.type == "shell") # XXX: check for windows?
  1560. session.init_ui(driver.input, driver.output)
  1561. session.execute_script('spawn_meterpreter', nil)
  1562. session.reset_ui
  1563. else
  1564. print_error("Session #{sid} is not a command shell session.")
  1565. end
  1566. else
  1567. print_error("Session #{sid} is non-interactive.")
  1568. end
  1569. else
  1570. print_error("Invalid session identifier: #{sid}")
  1571. end
  1572. when 'reset_ring'
  1573. sessions = sid ? [ sid ] : framework.sessions.keys
  1574. sessions.each do |sidx|
  1575. s = framework.sessions[sidx]
  1576. next if not (s and s.respond_to?(:ring_seq))
  1577. s.reset_ring_sequence
  1578. print_status("Reset the ring buffer pointer for Session #{sidx}")
  1579. end
  1580. when 'list',nil
  1581. print_line
  1582. print(Serializer::ReadableText.dump_sessions(framework, :verbose => verbose))
  1583. print_line
  1584. end
  1585. rescue IOError, EOFError, Rex::StreamClosedError
  1586. print_status("Session stream closed.")
  1587. rescue ::Interrupt
  1588. raise $!
  1589. rescue ::Exception
  1590. log_error("Session manipulation failed: #{$!} #{$!.backtrace.inspect}")
  1591. end
  1592. # Reset the active session
  1593. self.active_session = nil
  1594. return true
  1595. end
  1596. #
  1597. # Tab completion for the sessions command
  1598. #
  1599. # @param str [String] the string currently being typed before tab was hit
  1600. # @param words [Array<String>] the previously completed words on the command line. words is always
  1601. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1602. def cmd_sessions_tabs(str, words)
  1603. if words.length == 1
  1604. return @@sessions_opts.fmt.keys
  1605. end
  1606. case words[-1]
  1607. when "-i", "-k", "-d", "-u"
  1608. return framework.sessions.keys.map { |k| k.to_s }
  1609. when "-c"
  1610. # Can't really complete commands hehe
  1611. when "-s"
  1612. # XXX: Complete scripts
  1613. end
  1614. []
  1615. end
  1616. def cmd_set_help
  1617. print_line "Usage: set [option] [value]"
  1618. print_line
  1619. print_line "Set the given option to value. If value is omitted, print the current value."
  1620. print_line "If both are omitted, print options that are currently set."
  1621. print_line
  1622. print_line "If run from a module context, this will set the value in the module's"
  1623. print_line "datastore. Use -g to operate on the global datastore"
  1624. print_line
  1625. end
  1626. #
  1627. # Sets a name to a value in a context aware environment.
  1628. #
  1629. def cmd_set(*args)
  1630. # Figure out if these are global variables
  1631. global = false
  1632. if (args[0] == '-g')
  1633. args.shift
  1634. global = true
  1635. end
  1636. # Decide if this is an append operation
  1637. append = false
  1638. if (args[0] == '-a')
  1639. args.shift
  1640. append = true
  1641. end
  1642. # Determine which data store we're operating on
  1643. if (active_module and global == false)
  1644. datastore = active_module.datastore
  1645. else
  1646. global = true
  1647. datastore = self.framework.datastore
  1648. end
  1649. # Dump the contents of the active datastore if no args were supplied
  1650. if (args.length == 0)
  1651. # If we aren't dumping the global data store, then go ahead and
  1652. # dump it first
  1653. if (!global)
  1654. print("\n" +
  1655. Msf::Serializer::ReadableText.dump_datastore(
  1656. "Global", framework.datastore))
  1657. end
  1658. # Dump the active datastore
  1659. print("\n" +
  1660. Msf::Serializer::ReadableText.dump_datastore(
  1661. (global) ? "Global" : "Module: #{active_module.refname}",
  1662. datastore) + "\n")
  1663. return true
  1664. elsif (args.length == 1)
  1665. if (not datastore[args[0]].nil?)
  1666. print_line("#{args[0]} => #{datastore[args[0]]}")
  1667. return true
  1668. else
  1669. print_error("Unknown variable")
  1670. cmd_set_help
  1671. return false
  1672. end
  1673. end
  1674. # Set the supplied name to the supplied value
  1675. name = args[0]
  1676. value = args[1, args.length-1].join(' ')
  1677. if (name.upcase == "TARGET")
  1678. # Different targets can have different architectures and platforms
  1679. # so we need to rebuild the payload list whenever the target
  1680. # changes.
  1681. @cache_payloads = nil
  1682. end
  1683. # Security check -- make sure the data store element they are setting
  1684. # is not prohibited
  1685. if global and DefangedProhibitedDataStoreElements.include?(name)
  1686. defanged?
  1687. end
  1688. # If the driver indicates that the value is not valid, bust out.
  1689. if (driver.on_variable_set(global, name, value) == false)
  1690. print_error("The value specified for #{name} is not valid.")
  1691. return true
  1692. end
  1693. if append
  1694. datastore[name] = datastore[name] + value
  1695. else
  1696. datastore[name] = value
  1697. end
  1698. print_line("#{name} => #{datastore[name]}")
  1699. end
  1700. #
  1701. # Tab completion for the set command
  1702. #
  1703. # @param str [String] the string currently being typed before tab was hit
  1704. # @param words [Array<String>] the previously completed words on the command line. words is always
  1705. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1706. def cmd_set_tabs(str, words)
  1707. # A value has already been specified
  1708. return [] if words.length > 2
  1709. # A value needs to be specified
  1710. if words.length == 2
  1711. return tab_complete_option(str, words)
  1712. end
  1713. res = cmd_unset_tabs(str, words) || [ ]
  1714. # There needs to be a better way to register global options, but for
  1715. # now all we have is an ad-hoc list of opts that the shell treats
  1716. # specially.
  1717. res += %w{
  1718. ConsoleLogging
  1719. LogLevel
  1720. MinimumRank
  1721. SessionLogging
  1722. TimestampOutput
  1723. Prompt
  1724. PromptChar
  1725. PromptTimeFormat
  1726. }
  1727. mod = active_module
  1728. if (not mod)
  1729. return res
  1730. end
  1731. mod.options.sorted.each { |e|
  1732. name, opt = e
  1733. res << name
  1734. }
  1735. # Exploits provide these three default options
  1736. if (mod.exploit?)
  1737. res << 'PAYLOAD'
  1738. res << 'NOP'
  1739. res << 'TARGET'
  1740. end
  1741. if (mod.exploit? or mod.payload?)
  1742. res << 'ENCODER'
  1743. end
  1744. if (mod.auxiliary?)
  1745. res << "ACTION"
  1746. end
  1747. if (mod.exploit? and mod.datastore['PAYLOAD'])
  1748. p = framework.payloads.create(mod.datastore['PAYLOAD'])
  1749. if (p)
  1750. p.options.sorted.each { |e|
  1751. name, opt = e
  1752. res << name
  1753. }
  1754. end
  1755. end
  1756. unless str.blank?
  1757. res = res.select { |term| term.upcase.start_with?(str.upcase) }
  1758. res = res.map { |term|
  1759. if str == str.upcase
  1760. str + term[str.length..-1].upcase
  1761. elsif str == str.downcase
  1762. str + term[str.length..-1].downcase
  1763. else
  1764. str + term[str.length..-1]
  1765. end
  1766. }
  1767. end
  1768. return res
  1769. end
  1770. def cmd_setg_help
  1771. print_line "Usage: setg [option] [value]"
  1772. print_line
  1773. print_line "Exactly like set -g, set a value in the global datastore."
  1774. print_line
  1775. end
  1776. #
  1777. # Sets the supplied variables in the global datastore.
  1778. #
  1779. def cmd_setg(*args)
  1780. args.unshift('-g')
  1781. cmd_set(*args)
  1782. end
  1783. #
  1784. # Tab completion for the setg command
  1785. #
  1786. # @param str [String] the string currently being typed before tab was hit
  1787. # @param words [Array<String>] the previously completed words on the command line. words is always
  1788. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1789. def cmd_setg_tabs(str, words)
  1790. cmd_set_tabs(str, words)
  1791. end
  1792. def cmd_show_help
  1793. global_opts = %w{all encoders nops exploits payloads auxiliary plugins options}
  1794. print_status("Valid parameters for the \"show\" command are: #{global_opts.join(", ")}")
  1795. module_opts = %w{ advanced evasion targets actions }
  1796. print_status("Additional module-specific parameters are: #{module_opts.join(", ")}")
  1797. end
  1798. #
  1799. # Displays the list of modules based on their type, or all modules if
  1800. # no type is provided.
  1801. #
  1802. def cmd_show(*args)
  1803. mod = self.active_module
  1804. args << "all" if (args.length == 0)
  1805. args.each { |type|
  1806. case type
  1807. when '-h'
  1808. cmd_show_help
  1809. when 'all'
  1810. show_encoders
  1811. show_nops
  1812. show_exploits
  1813. show_payloads
  1814. show_auxiliary
  1815. show_post
  1816. show_plugins
  1817. when 'encoders'
  1818. show_encoders
  1819. when 'nops'
  1820. show_nops
  1821. when 'exploits'
  1822. show_exploits
  1823. when 'payloads'
  1824. show_payloads
  1825. when 'auxiliary'
  1826. show_auxiliary
  1827. when 'post'
  1828. show_post
  1829. when 'options'
  1830. if (mod)
  1831. show_options(mod)
  1832. else
  1833. show_global_options
  1834. end
  1835. when 'advanced'
  1836. if (mod)
  1837. show_advanced_options(mod)
  1838. else
  1839. print_error("No module selected.")
  1840. end
  1841. when 'evasion'
  1842. if (mod)
  1843. show_evasion_options(mod)
  1844. else
  1845. print_error("No module selected.")
  1846. end
  1847. when 'sessions'
  1848. if (active_module and active_module.respond_to?(:compatible_sessions))
  1849. sessions = active_module.compatible_sessions
  1850. else
  1851. sessions = framework.sessions.keys.sort
  1852. end
  1853. print_line
  1854. print(Serializer::ReadableText.dump_sessions(framework, :session_ids => sessions))
  1855. print_line
  1856. when "plugins"
  1857. show_plugins
  1858. when "targets"
  1859. if (mod and mod.exploit?)
  1860. show_targets(mod)
  1861. else
  1862. print_error("No exploit module selected.")
  1863. end
  1864. when "actions"
  1865. if (mod and (mod.auxiliary? or mod.post?))
  1866. show_actions(mod)
  1867. else
  1868. print_error("No auxiliary module selected.")
  1869. end
  1870. else
  1871. print_error("Invalid parameter \"#{type}\", use \"show -h\" for more information")
  1872. end
  1873. }
  1874. end
  1875. #
  1876. # Tab completion for the show command
  1877. #
  1878. # @param str [String] the string currently being typed before tab was hit
  1879. # @param words [Array<String>] the previously completed words on the command line. words is always
  1880. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1881. def cmd_show_tabs(str, words)
  1882. return [] if words.length > 1
  1883. res = %w{all encoders nops exploits payloads auxiliary post plugins options}
  1884. if (active_module)
  1885. res.concat(%w{ advanced evasion targets actions })
  1886. if (active_module.respond_to? :compatible_sessions)
  1887. res << "sessions"
  1888. end
  1889. end
  1890. return res
  1891. end
  1892. def cmd_unload_help
  1893. print_line "Usage: unload <plugin name>"
  1894. print_line
  1895. print_line "Unloads a plugin by its symbolic name. Use 'show plugins' to see a list of"
  1896. print_line "currently loaded plugins."
  1897. print_line
  1898. end
  1899. #
  1900. # Unloads a plugin by its name.
  1901. #
  1902. def cmd_unload(*args)
  1903. if (args.length == 0)
  1904. cmd_unload_help
  1905. return false
  1906. end
  1907. # Walk the plugins array
  1908. framework.plugins.each { |plugin|
  1909. # Unload the plugin if it matches the name we're searching for
  1910. if (plugin.name == args[0])
  1911. print("Unloading plugin #{args[0]}...")
  1912. framework.plugins.unload(plugin)
  1913. print_line("unloaded.")
  1914. break
  1915. end
  1916. }
  1917. end
  1918. #
  1919. # Tab completion for the unload command
  1920. #
  1921. # @param str [String] the string currently being typed before tab was hit
  1922. # @param words [Array<String>] the previously completed words on the command line. words is always
  1923. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1924. def cmd_unload_tabs(str, words)
  1925. return [] if words.length > 1
  1926. tabs = []
  1927. framework.plugins.each { |k| tabs.push(k.name) }
  1928. return tabs
  1929. end
  1930. def cmd_unset_help
  1931. print_line "Usage: unset [-g] var1 var2 var3 ..."
  1932. print_line
  1933. print_line "The unset command is used to unset one or more variables."
  1934. print_line "To flush all entires, specify 'all' as the variable name."
  1935. print_line "With -g, operates on global datastore variables."
  1936. print_line
  1937. end
  1938. #
  1939. # Unsets a value if it's been set.
  1940. #
  1941. def cmd_unset(*args)
  1942. # Figure out if these are global variables
  1943. global = false
  1944. if (args[0] == '-g')
  1945. args.shift
  1946. global = true
  1947. end
  1948. # Determine which data store we're operating on
  1949. if (active_module and global == false)
  1950. datastore = active_module.datastore
  1951. else
  1952. datastore = framework.datastore
  1953. end
  1954. # No arguments? No cookie.
  1955. if (args.length == 0)
  1956. cmd_unset_help
  1957. return false
  1958. end
  1959. # If all was specified, then flush all of the entries
  1960. if args[0] == 'all'
  1961. print_line("Flushing datastore...")
  1962. # Re-import default options into the module's datastore
  1963. if (active_module and global == false)
  1964. active_module.import_defaults
  1965. # Or simply clear the global datastore
  1966. else
  1967. datastore.clear
  1968. end
  1969. return true
  1970. end
  1971. while ((val = args.shift))
  1972. if (driver.on_variable_unset(global, val) == false)
  1973. print_error("The variable #{val} cannot be unset at this time.")
  1974. next
  1975. end
  1976. print_line("Unsetting #{val}...")
  1977. datastore.delete(val)
  1978. end
  1979. end
  1980. #
  1981. # Tab completion for the unset command
  1982. #
  1983. # @param str [String] the string currently being typed before tab was hit
  1984. # @param words [Array<String>] the previously completed words on the command line. words is always
  1985. # at least 1 when tab completion has reached this stage since the command itself has been completed
  1986. def cmd_unset_tabs(str, words)
  1987. datastore = active_module ? active_module.datastore : self.framework.datastore
  1988. datastore.keys
  1989. end
  1990. def cmd_unsetg_help
  1991. print_line "Usage: unsetg var1 [var2 ...]"
  1992. print_line
  1993. print_line "Exactly like unset -g, unset global variables, or all"
  1994. print_line
  1995. end
  1996. #
  1997. # Unsets variables in the global data store.
  1998. #
  1999. def cmd_unsetg(*args)
  2000. args.unshift('-g')
  2001. cmd_unset(*args)
  2002. end
  2003. #
  2004. # Tab completion for the unsetg command
  2005. #
  2006. # @param str [String] the string currently being typed before tab was hit
  2007. # @param words [Array<String>] the previously completed words on the command line. words is always
  2008. # at least 1 when tab completion has reached this stage since the command itself has been completed
  2009. def cmd_unsetg_tabs(str, words)
  2010. self.framework.datastore.keys
  2011. end
  2012. alias cmd_unsetg_help cmd_unset_help
  2013. def cmd_use_help
  2014. print_line "Usage: use module_name"
  2015. print_line
  2016. print_line "The use command is used to interact with a module of a given name."
  2017. print_line
  2018. end
  2019. #
  2020. # Uses a module.
  2021. #
  2022. def cmd_use(*args)
  2023. if (args.length == 0)
  2024. cmd_use_help
  2025. return false
  2026. end
  2027. # Try to create an instance of the supplied module name
  2028. mod_name = args[0]
  2029. begin
  2030. if ((mod = framework.modules.create(mod_name)) == nil)
  2031. print_error("Failed to load module: #{mod_name}")
  2032. return false
  2033. end
  2034. rescue Rex::AmbiguousArgumentError => info
  2035. print_error(info.to_s)
  2036. rescue NameError => info
  2037. log_error("The supplied module name is ambiguous: #{$!}.")
  2038. end
  2039. return false if (mod == nil)
  2040. # Enstack the command dispatcher for this module type
  2041. dispatcher = nil
  2042. case mod.type
  2043. when MODULE_ENCODER
  2044. dispatcher = Msf::Ui::Console::CommandDispatcher::Encoder
  2045. when MODULE_EXPLOIT
  2046. dispatcher = Msf::Ui::Console::CommandDispatcher::Exploit
  2047. when MODULE_NOP
  2048. dispatcher = Msf::Ui::Console::CommandDispatcher::Nop
  2049. when MODULE_PAYLOAD
  2050. dispatcher = Msf::Ui::Console::CommandDispatcher::Payload
  2051. when MODULE_AUX
  2052. dispatcher = Msf::Ui::Console::CommandDispatcher::Auxiliary
  2053. when MODULE_POST
  2054. dispatcher = Msf::Ui::Console::CommandDispatcher::Post
  2055. else
  2056. print_error("Unsupported module type: #{mod.type}")
  2057. return false
  2058. end
  2059. # If there's currently an active module, enqueque it and go back
  2060. if (active_module)
  2061. @previous_module = active_module
  2062. cmd_back()
  2063. end
  2064. if (dispatcher != nil)
  2065. driver.enstack_dispatcher(dispatcher)
  2066. end
  2067. # Update the active module
  2068. self.active_module = mod
  2069. # If a datastore cache exists for this module, then load it up
  2070. if @dscache[active_module.fullname]
  2071. active_module.datastore.update(@dscache[active_module.fullname])
  2072. end
  2073. @cache_payloads = nil
  2074. mod.init_ui(driver.input, driver.output)
  2075. # Update the command prompt
  2076. prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  2077. prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  2078. driver.update_prompt("#{prompt} #{mod.type}(%bld%red#{mod.shortname}%clr) ", prompt_char, true)
  2079. end
  2080. #
  2081. # Command to take to the previously active module
  2082. #
  2083. def cmd_previous()
  2084. if @previous_module
  2085. self.cmd_use(@previous_module.fullname)
  2086. else
  2087. print_error("There isn't a previous module at the moment")
  2088. end
  2089. end
  2090. #
  2091. # Help for the 'previous' command
  2092. #
  2093. def cmd_previous_help
  2094. print_line "Usage: previous"
  2095. print_line
  2096. print_line "Set the previously loaded module as the current module"
  2097. print_line
  2098. end
  2099. #
  2100. # Command to enqueque a module on the module stack
  2101. #
  2102. def cmd_pushm(*args)
  2103. # could check if each argument is a valid module, but for now let them hang themselves
  2104. if args.count > 0
  2105. args.each do |arg|
  2106. @module_name_stack.push(arg)
  2107. # Note new modules are appended to the array and are only module (full)names
  2108. end
  2109. else #then just push the active module
  2110. if active_module
  2111. #print_status "Pushing the active module"
  2112. @module_name_stack.push(active_module.fullname)
  2113. else
  2114. print_error("There isn't an active module and you didn't specify a module to push")
  2115. return self.cmd_pushm_help
  2116. end
  2117. end
  2118. end
  2119. #
  2120. # Tab completion for the pushm command
  2121. #
  2122. # @param str [String] the string currently being typed before tab was hit
  2123. # @param words [Array<String>] the previously completed words on the command line. words is always
  2124. # at least 1 when tab completion has reached this stage since the command itself has been completed
  2125. def cmd_pushm_tabs(str, words)
  2126. tab_complete_module(str, words)
  2127. end
  2128. #
  2129. # Help for the 'pushm' command
  2130. #
  2131. def cmd_pushm_help
  2132. print_line "Usage: pushm [module1 [,module2, module3...]]"
  2133. print_line
  2134. print_line "push current active module or specified modules onto the module stack"
  2135. print_line
  2136. end
  2137. #
  2138. # Command to dequeque a module from the module stack
  2139. #
  2140. def cmd_popm(*args)
  2141. if (args.count > 1 or not args[0].respond_to?("to_i"))
  2142. return self.cmd_popm_help
  2143. elsif args.count == 1
  2144. # then pop 'n' items off the stack, but don't change the active module
  2145. if args[0].to_i >= @module_name_stack.count
  2146. # in case they pass in a number >= the length of @module_name_stack
  2147. @module_name_stack = []
  2148. print_status("The module stack is empty")
  2149. else
  2150. @module_name_stack.pop[args[0]]
  2151. end
  2152. else #then just pop the array and make that the active module
  2153. pop = @module_name_stack.pop
  2154. if pop
  2155. return self.cmd_use(pop)
  2156. else
  2157. print_error("There isn't anything to pop, the module stack is empty")
  2158. end
  2159. end
  2160. end
  2161. #
  2162. # Help for the 'popm' command
  2163. #
  2164. def cmd_popm_help
  2165. print_line "Usage: popm [n]"
  2166. print_line
  2167. print_line "pop the latest module off of the module stack and make it the active module"
  2168. print_line "or pop n modules off the stack, but don't change the active module"
  2169. print_line
  2170. end
  2171. #
  2172. # Tab completion for the use command
  2173. #
  2174. # @param str [String] the string currently being typed before tab was hit
  2175. # @param words [Array<String>] the previously completed words on the command line. words is always
  2176. # at least 1 when tab completion has reached this stage since the command itself has been completd
  2177. def cmd_use_tabs(str, words)
  2178. return [] if words.length > 1
  2179. tab_complete_module(str, words)
  2180. end
  2181. #
  2182. # Returns the revision of the framework and console library
  2183. #
  2184. def cmd_version(*args)
  2185. svn_console_version = "$Revision: 15168 $"
  2186. svn_metasploit_version = Msf::Framework::Revision.match(/ (.+?) \$/)[1] rescue nil
  2187. if svn_metasploit_version
  2188. print_line("Framework: #{Msf::Framework::Version}.#{svn_metasploit_version}")
  2189. else
  2190. print_line("Framework: #{Msf::Framework::Version}")
  2191. end
  2192. print_line("Console : #{Msf::Framework::Version}.#{svn_console_version.match(/ (.+?) \$/)[1]}")
  2193. return true
  2194. end
  2195. def cmd_grep_help
  2196. print_line "Usage: grep [options] pattern cmd"
  2197. print_line
  2198. print_line "Grep the results of a console command (similar to Linux grep command)"
  2199. print(@@grep_opts.usage())
  2200. end
  2201. #
  2202. # Greps the output of another console command, usage is similar the shell grep command
  2203. # grep [options] pattern other_cmd [other command's args], similar to the shell's grep [options] pattern file
  2204. # however it also includes -k to keep lines and -s to skip lines. grep -k 5 is useful for keeping table headers
  2205. #
  2206. # @param args [Array<String>] Args to the grep command minimally including a pattern & a command to search
  2207. # @return [String,nil] Results matching the regular expression given
  2208. def cmd_grep(*args)
  2209. return cmd_grep_help if args.length < 2
  2210. match_mods = {:insensitive => false}
  2211. output_mods = {:count => false, :invert => false}
  2212. @@grep_opts.parse(args.dup) do |opt, idx, val|
  2213. case opt
  2214. when "-h"
  2215. return cmd_grep_help
  2216. when "-m"
  2217. # limit to arg matches
  2218. match_mods[:max] = val.to_i
  2219. # delete opt and val from args list
  2220. args.shift(2)
  2221. when "-A"
  2222. # also return arg lines after a match
  2223. output_mods[:after] = val.to_i
  2224. # delete opt and val from args list
  2225. args.shift(2)
  2226. when "-B"
  2227. # also return arg lines before a match
  2228. output_mods[:before] = val.to_i
  2229. # delete opt and val from args list
  2230. args.shift(2)
  2231. when "-v"
  2232. # invert match
  2233. match_mods[:invert] = true
  2234. # delete opt from args list
  2235. args.shift
  2236. when "-i"
  2237. # case insensitive
  2238. match_mods[:insensitive] = true
  2239. args.shift
  2240. when "-c"
  2241. # just count matches
  2242. output_mods[:count] = true
  2243. args.shift
  2244. when "-k"
  2245. # keep arg number of lines at the top of the output, useful for commands with table headers in output
  2246. output_mods[:keep] = val.to_i
  2247. args.shift(2)
  2248. when "-s"
  2249. # skip arg number of lines at the top of the output, useful for avoiding undesirable matches
  2250. output_mods[:skip] = val.to_i
  2251. args.shift(2)
  2252. end
  2253. end
  2254. # after deleting parsed options, the only args left should be the pattern, the cmd to run, and cmd args
  2255. pattern = args.shift
  2256. if match_mods[:insensitive]
  2257. rx = Regexp.new(pattern, true)
  2258. else
  2259. rx = Regexp.new(pattern)
  2260. end
  2261. cmd = args.join(" ")
  2262. # get a ref to the current console driver
  2263. orig_driver = self.driver
  2264. # redirect output after saving the old ones and getting a new output buffer to use for redirect
  2265. orig_driver_output = orig_driver.output
  2266. orig_driver_input = orig_driver.input
  2267. # we use a rex buffer but add a write method to the instance, which is
  2268. # required in order to be valid $stdout
  2269. temp_output = Rex::Ui::Text::Output::Buffer.new
  2270. temp_output.extend Rex::Ui::Text::Output::Buffer::Stdout
  2271. orig_driver.init_ui(orig_driver_input,temp_output)
  2272. # run the desired command to be grepped
  2273. orig_driver.run_single(cmd)
  2274. # restore original output
  2275. orig_driver.init_ui(orig_driver_input,orig_driver_output)
  2276. # restore the prompt so we don't get "msf > >".
  2277. prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  2278. prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  2279. mod = active_module
  2280. if mod # if there is an active module, give them the fanciness they have come to expect
  2281. driver.update_prompt("#{prompt} #{mod.type}(%bld%red#{mod.shortname}%clr) ", prompt_char, true)
  2282. else
  2283. driver.update_prompt("#{prompt} ", prompt_char, true)
  2284. end
  2285. # dump the command's output so we can grep it
  2286. cmd_output = temp_output.dump_buffer
  2287. # Bail if the command failed
  2288. if cmd_output =~ /Unknown command:/
  2289. print_error("Unknown command: #{args[0]}.")
  2290. return false
  2291. end
  2292. # put lines into an array so we can access them more easily and split('\n') doesn't work on the output obj.
  2293. all_lines = cmd_output.lines.select {|line| line}
  2294. # control matching based on remaining match_mods (:insensitive was already handled)
  2295. if match_mods[:invert]
  2296. statement = 'not line =~ rx'
  2297. else
  2298. statement = 'line =~ rx'
  2299. end
  2300. our_lines = []
  2301. count = 0
  2302. all_lines.each_with_index do |line, line_num|
  2303. next if (output_mods[:skip] and line_num < output_mods[:skip])
  2304. our_lines << line if (output_mods[:keep] and line_num < output_mods[:keep])
  2305. # we don't wan't to keep processing if we have a :max and we've reached it already (not counting skips/keeps)
  2306. break if match_mods[:max] and count >= match_mods[:max]
  2307. if eval statement
  2308. count += 1
  2309. # we might get a -A/after and a -B/before at the same time
  2310. our_lines += retrieve_grep_lines(all_lines,line_num,output_mods[:before], output_mods[:after])
  2311. end
  2312. end
  2313. # now control output based on remaining output_mods such as :count
  2314. return print_status(count.to_s) if output_mods[:count]
  2315. our_lines.each {|line| print line}
  2316. end
  2317. #
  2318. # Tab completion for the grep command
  2319. #
  2320. # @param str [String] the string currently being typed before tab was hit
  2321. # @param words [Array<String>] the previously completed words on the command line. words is always
  2322. # at least 1 when tab completion has reached this stage since the command itself has been completed
  2323. def cmd_grep_tabs(str, words)
  2324. tabs = @@grep_opts.fmt.keys || [] # default to use grep's options
  2325. # if not an opt, use normal tab comp.
  2326. # @todo uncomment out next line when tab_completion normalization is complete RM7649 or
  2327. # replace with new code that permits "nested" tab completion
  2328. # tabs = driver.get_all_commands if (str and str =~ /\w/)
  2329. tabs
  2330. end
  2331. #
  2332. # Tab complete module names
  2333. #
  2334. def tab_complete_module(str, words)
  2335. res = []
  2336. framework.modules.module_types.each do |mtyp|
  2337. mset = framework.modules.module_names(mtyp)
  2338. mset.each do |mref|
  2339. res << mtyp + '/' + mref
  2340. end
  2341. end
  2342. return res.sort
  2343. end
  2344. #
  2345. # Provide tab completion for option values
  2346. #
  2347. def tab_complete_option(str, words)
  2348. opt = words[1]
  2349. res = []
  2350. mod = active_module
  2351. # With no active module, we have nothing to compare
  2352. if (not mod)
  2353. return res
  2354. end
  2355. # Well-known option names specific to exploits
  2356. if (mod.exploit?)
  2357. return option_values_payloads() if opt.upcase == 'PAYLOAD'
  2358. return option_values_targets() if opt.upcase == 'TARGET'
  2359. return option_values_nops() if opt.upcase == 'NOPS'
  2360. return option_values_encoders() if opt.upcase == 'StageEncoder'
  2361. end
  2362. # Well-known option names specific to auxiliaries
  2363. if (mod.auxiliary?)
  2364. return option_values_actions() if opt.upcase == 'ACTION'
  2365. end
  2366. # The ENCODER option works for payloads and exploits
  2367. if ((mod.exploit? or mod.payload?) and opt.upcase == 'ENCODER')
  2368. return option_values_encoders()
  2369. end
  2370. # Well-known option names specific to post-exploitation
  2371. if (mod.post? or mod.exploit?)
  2372. return option_values_sessions() if opt.upcase == 'SESSION'
  2373. end
  2374. # Is this option used by the active module?
  2375. if (mod.options.include?(opt))
  2376. res.concat(option_values_dispatch(mod.options[opt], str, words))
  2377. elsif (mod.options.include?(opt.upcase))
  2378. res.concat(option_values_dispatch(mod.options[opt.upcase], str, words))
  2379. end
  2380. # How about the selected payload?
  2381. if (mod.exploit? and mod.datastore['PAYLOAD'])
  2382. p = framework.payloads.create(mod.datastore['PAYLOAD'])
  2383. if (p and p.options.include?(opt))
  2384. res.concat(option_values_dispatch(p.options[opt], str, words))
  2385. elsif (p and p.options.include?(opt.upcase))
  2386. res.concat(option_values_dispatch(p.options[opt.upcase], str, words))
  2387. end
  2388. end
  2389. return res
  2390. end
  2391. #
  2392. # Provide possible option values based on type
  2393. #
  2394. def option_values_dispatch(o, str, words)
  2395. res = []
  2396. res << o.default.to_s if o.default
  2397. case o.class.to_s
  2398. when 'Msf::OptAddress'
  2399. case o.name.upcase
  2400. when 'RHOST'
  2401. option_values_target_addrs().each do |addr|
  2402. res << addr
  2403. end
  2404. when 'LHOST'
  2405. rh = self.active_module.datastore["RHOST"]
  2406. if rh and not rh.empty?
  2407. res << Rex::Socket.source_address(rh)
  2408. else
  2409. res << Rex::Socket.source_address()
  2410. end
  2411. else
  2412. end
  2413. when 'Msf::OptAddressRange'
  2414. case str
  2415. when /^file:(.*)/
  2416. files = tab_complete_filenames($1, words)
  2417. res += files.map { |f| "file:" + f } if files
  2418. when /\/$/
  2419. res << str+'32'
  2420. res << str+'24'
  2421. res << str+'16'
  2422. when /\-$/
  2423. res << str+str[0, str.length - 1]
  2424. else
  2425. option_values_target_addrs().each do |addr|
  2426. res << addr+'/32'
  2427. res << addr+'/24'
  2428. res << addr+'/16'
  2429. end
  2430. end
  2431. when 'Msf::OptPort'
  2432. case o.name.upcase
  2433. when 'RPORT'
  2434. option_values_target_ports().each do |port|
  2435. res << port
  2436. end
  2437. end
  2438. if (res.empty?)
  2439. res << (rand(65534)+1).to_s
  2440. end
  2441. when 'Msf::OptEnum'
  2442. o.enums.each do |val|
  2443. res << val
  2444. end
  2445. when 'Msf::OptPath'
  2446. files = tab_complete_filenames(str, words)
  2447. res += files if files
  2448. when 'Msf::OptBool'
  2449. res << 'true'
  2450. res << 'false'
  2451. when 'Msf::OptString'
  2452. if (str =~ /^file:(.*)/)
  2453. files = tab_complete_filenames($1, words)
  2454. res += files.map { |f| "file:" + f } if files
  2455. end
  2456. end
  2457. return res
  2458. end
  2459. #
  2460. # Provide valid payload options for the current exploit
  2461. #
  2462. def option_values_payloads
  2463. return @cache_payloads if @cache_payloads
  2464. @cache_payloads = active_module.compatible_payloads.map { |refname, payload|
  2465. refname
  2466. }
  2467. @cache_payloads
  2468. end
  2469. #
  2470. # Provide valid session options for the current post-exploit module
  2471. #
  2472. def option_values_sessions
  2473. active_module.compatible_sessions.map { |sid| sid.to_s }
  2474. end
  2475. #
  2476. # Provide valid target options for the current exploit
  2477. #
  2478. def option_values_targets
  2479. res = []
  2480. if (active_module.targets)
  2481. 1.upto(active_module.targets.length) { |i| res << (i-1).to_s }
  2482. end
  2483. return res
  2484. end
  2485. #
  2486. # Provide valid action options for the current auxiliary module
  2487. #
  2488. def option_values_actions
  2489. res = []
  2490. if (active_module.actions)
  2491. active_module.actions.each { |i| res << i.name }
  2492. end
  2493. return res
  2494. end
  2495. #
  2496. # Provide valid nops options for the current exploit
  2497. #
  2498. def option_values_nops
  2499. framework.nops.map { |refname, mod| refname }
  2500. end
  2501. #
  2502. # Provide valid encoders options for the current exploit or payload
  2503. #
  2504. def option_values_encoders
  2505. framework.encoders.map { |refname, mod| refname }
  2506. end
  2507. #
  2508. # Provide the target addresses
  2509. #
  2510. def option_values_target_addrs
  2511. res = [ ]
  2512. res << Rex::Socket.source_address()
  2513. return res if not framework.db.active
  2514. # List only those hosts with matching open ports?
  2515. mport = self.active_module.datastore['RPORT']
  2516. if (mport)
  2517. mport = mport.to_i
  2518. hosts = {}
  2519. framework.db.each_service(framework.db.workspace) do |service|
  2520. if (service.port == mport)
  2521. hosts[ service.host.address ] = true
  2522. end
  2523. end
  2524. hosts.keys.each do |host|
  2525. res << host
  2526. end
  2527. # List all hosts in the database
  2528. else
  2529. framework.db.each_host(framework.db.workspace) do |host|
  2530. res << host.address
  2531. end
  2532. end
  2533. return res
  2534. end
  2535. #
  2536. # Provide the target ports
  2537. #
  2538. def option_values_target_ports
  2539. res = [ ]
  2540. return res if not framework.db.active
  2541. return res if not self.active_module.datastore['RHOST']
  2542. host = framework.db.has_host?(framework.db.workspace, self.active_module.datastore['RHOST'])
  2543. return res if not host
  2544. framework.db.each_service(framework.db.workspace) do |service|
  2545. if (service.host_id == host.id)
  2546. res << service.port.to_s
  2547. end
  2548. end
  2549. return res
  2550. end
  2551. def cmd_go_pro_help
  2552. print_line "Usage: go_pro"
  2553. print_line
  2554. print_line "Launch the Metasploit web GUI"
  2555. print_line
  2556. end
  2557. def cmd_go_pro(*args)
  2558. @@go_pro_opts.parse(args) do |opt, idx, val|
  2559. case opt
  2560. when "-h"
  2561. cmd_go_pro_help
  2562. return false
  2563. end
  2564. end
  2565. unless is_apt
  2566. print_warning "This command is only available on deb package installations, such as Kali Linux."
  2567. return false
  2568. end
  2569. unless is_metasploit_debian_package_installed
  2570. print_warning "You need to install the 'metasploit' package first."
  2571. print_warning "Type 'apt-get install -y metasploit' to do this now, then exit"
  2572. print_warning "and restart msfconsole to try again."
  2573. return false
  2574. end
  2575. # If I've gotten this far, I know that this is apt-installed, the
  2576. # metasploit package is here, and I'm ready to rock.
  2577. if is_metasploit_service_running
  2578. launch_metasploit_browser
  2579. else
  2580. print_status "Starting the Metasploit services. This can take a little time."
  2581. start_metasploit_service
  2582. select(nil,nil,nil,3)
  2583. if is_metasploit_service_running
  2584. launch_metasploit_browser
  2585. else
  2586. print_error "Metasploit services aren't running. Type 'service metasploit start' and try again."
  2587. end
  2588. end
  2589. return true
  2590. end
  2591. protected
  2592. #
  2593. # Go_pro methods -- these are used to start and connect to
  2594. # Metasploit Community / Pro.
  2595. #
  2596. # Note that this presumes a default port.
  2597. def launch_metasploit_browser
  2598. cmd = "/usr/bin/xdg-open"
  2599. unless ::File.executable_real? cmd
  2600. print_warning "Can't figure out your default browser, please visit https://localhost:3790"
  2601. print_warning "to start Metasploit Community / Pro."
  2602. return false
  2603. end
  2604. svc_log = File.expand_path(File.join(msfbase_dir, ".." , "engine", "prosvc_stdout.log"))
  2605. unless ::File.readable_real? svc_log
  2606. print_error "Unable to access log file: #{svc_log}"
  2607. return false
  2608. end
  2609. really_started = false
  2610. # This method is a little lame but it's a short enough file that it
  2611. # shouldn't really matter that we open and close it a few times.
  2612. timeout = 0
  2613. until really_started
  2614. select(nil,nil,nil,3)
  2615. log_data = ::File.open(svc_log, "rb") {|f| f.read f.stat.size}
  2616. really_started = log_data =~ /Ready/ # This is webserver ready
  2617. if really_started
  2618. print_line
  2619. print_good "Metasploit Community / Pro is up and running, connecting now."
  2620. print_good "If this is your first time connecting, you will be presented with"
  2621. print_good "a self-signed certificate warning. Accept it to create a new user."
  2622. select(nil,nil,nil,7)
  2623. browser_pid = ::Process.spawn(cmd, "https://localhost:3790")
  2624. ::Process.detach(browser_pid)
  2625. elsif timeout >= 200 # 200 * 3 seconds is 10 minutes and that is tons of time.
  2626. print_line
  2627. print_warning "For some reason, Community / Pro didn't start in a timely fashion."
  2628. print_warning "You might want to restart the Metasploit services by typing"
  2629. print_warning "'service metasploit restart'. Sorry it didn't work out."
  2630. return false
  2631. else
  2632. print "."
  2633. timeout += 1
  2634. end
  2635. end
  2636. end
  2637. def start_metasploit_service
  2638. cmd = File.expand_path(File.join(msfbase_dir, '..', '..', '..', 'scripts', 'start.sh'))
  2639. return unless ::File.executable_real? cmd
  2640. %x{#{cmd}}.each_line do |line|
  2641. print_status line.chomp
  2642. end
  2643. end
  2644. def is_metasploit_service_running
  2645. cmd = "/usr/sbin/service"
  2646. system("#{cmd} metasploit status >/dev/null") # Both running returns true, otherwise, false.
  2647. end
  2648. def is_metasploit_debian_package_installed
  2649. cmd = "/usr/bin/dpkg"
  2650. return unless ::File.executable_real? cmd
  2651. installed_packages = %x{#{cmd} -l 'metasploit'}
  2652. installed_packages.each_line do |line|
  2653. if line =~ /^.i metasploit / # Yes, trailing space
  2654. return true
  2655. end
  2656. end
  2657. return false
  2658. end
  2659. # Determines if this is an apt-based install
  2660. def is_apt
  2661. File.exists?(File.expand_path(File.join(msfbase_dir, '.apt')))
  2662. end
  2663. # Determines if we're a Metasploit Pro/Community/Express
  2664. # installation or a tarball/git checkout
  2665. #
  2666. # @return [Boolean] true if we are a binary install
  2667. def binary_install
  2668. binary_paths = [
  2669. 'C:/metasploit/apps/pro/msf3',
  2670. '/opt/metasploit/apps/pro/msf3'
  2671. ]
  2672. return binary_paths.include? Msf::Config.install_root
  2673. end
  2674. #
  2675. # Module list enumeration
  2676. #
  2677. def show_encoders(regex = nil, minrank = nil, opts = nil) # :nodoc:
  2678. # If an active module has been selected and it's an exploit, get the
  2679. # list of compatible encoders and display them
  2680. if (active_module and active_module.exploit? == true)
  2681. show_module_set("Compatible Encoders", active_module.compatible_encoders, regex, minrank, opts)
  2682. else
  2683. show_module_set("Encoders", framework.encoders, regex, minrank, opts)
  2684. end
  2685. end
  2686. def show_nops(regex = nil, minrank = nil, opts = nil) # :nodoc:
  2687. show_module_set("NOP Generators", framework.nops, regex, minrank, opts)
  2688. end
  2689. def show_exploits(regex = nil, minrank = nil, opts = nil) # :nodoc:
  2690. show_module_set("Exploits", framework.exploits, regex, minrank, opts)
  2691. end
  2692. def show_payloads(regex = nil, minrank = nil, opts = nil) # :nodoc:
  2693. # If an active module has been selected and it's an exploit, get the
  2694. # list of compatible payloads and display them
  2695. if (active_module and active_module.exploit? == true)
  2696. show_module_set("Compatible Payloads", active_module.compatible_payloads, regex, minrank, opts)
  2697. else
  2698. show_module_set("Payloads", framework.payloads, regex, minrank, opts)
  2699. end
  2700. end
  2701. def show_auxiliary(regex = nil, minrank = nil, opts = nil) # :nodoc:
  2702. show_module_set("Auxiliary", framework.auxiliary, regex, minrank, opts)
  2703. end
  2704. def show_post(regex = nil, minrank = nil, opts = nil) # :nodoc:
  2705. show_module_set("Post", framework.post, regex, minrank, opts)
  2706. end
  2707. def show_options(mod) # :nodoc:
  2708. mod_opt = Serializer::ReadableText.dump_options(mod, ' ')
  2709. print("\nModule options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
  2710. # If it's an exploit and a payload is defined, create it and
  2711. # display the payload's options
  2712. if (mod.exploit? and mod.datastore['PAYLOAD'])
  2713. p = framework.payloads.create(mod.datastore['PAYLOAD'])
  2714. if (!p)
  2715. print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
  2716. return
  2717. end
  2718. p.share_datastore(mod.datastore)
  2719. if (p)
  2720. p_opt = Serializer::ReadableText.dump_options(p, ' ')
  2721. print("\nPayload options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
  2722. end
  2723. end
  2724. # Print the selected target
  2725. if (mod.exploit? and mod.target)
  2726. mod_targ = Serializer::ReadableText.dump_exploit_target(mod, ' ')
  2727. print("\nExploit target:\n\n#{mod_targ}\n") if (mod_targ and mod_targ.length > 0)
  2728. end
  2729. # Uncomment this line if u want target like msf2 format
  2730. #print("\nTarget: #{mod.target.name}\n\n")
  2731. end
  2732. def show_global_options
  2733. columns = [ 'Option', 'Current Setting', 'Description' ]
  2734. tbl = Table.new(
  2735. Table::Style::Default,
  2736. 'Header' => 'Global Options:',
  2737. 'Prefix' => "\n",
  2738. 'Postfix' => "\n",
  2739. 'Columns' => columns
  2740. )
  2741. [
  2742. [ 'ConsoleLogging', framework.datastore['ConsoleLogging'] || "false", 'Log all console input and output' ],
  2743. [ 'LogLevel', framework.datastore['LogLevel'] || "0", 'Verbosity of logs (default 0, max 5)' ],
  2744. [ 'MinimumRank', framework.datastore['MinimumRank'] || "0", 'The minimum rank of exploits that will run without explicit confirmation' ],
  2745. [ 'SessionLogging', framework.datastore['SessionLogging'] || "false", 'Log all input and output for sessions' ],
  2746. [ 'TimestampOutput', framework.datastore['TimestampOutput'] || "false", 'Prefix all console output with a timestamp' ],
  2747. [ 'Prompt', framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt.to_s.gsub(/%.../,"") , "The prompt string" ],
  2748. [ 'PromptChar', framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar.to_s.gsub(/%.../,""), "The prompt character" ],
  2749. [ 'PromptTimeFormat', framework.datastore['PromptTimeFormat'] || Time::DATE_FORMATS[:db].to_s, 'Format for timestamp escapes in prompts' ],
  2750. ].each { |r| tbl << r }
  2751. print(tbl.to_s)
  2752. end
  2753. def show_targets(mod) # :nodoc:
  2754. mod_targs = Serializer::ReadableText.dump_exploit_targets(mod, ' ')
  2755. print("\nExploit targets:\n\n#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
  2756. end
  2757. def show_actions(mod) # :nodoc:
  2758. mod_actions = Serializer::ReadableText.dump_auxiliary_actions(mod, ' ')
  2759. print("\nAuxiliary actions:\n\n#{mod_actions}\n") if (mod_actions and mod_actions.length > 0)
  2760. end
  2761. def show_advanced_options(mod) # :nodoc:
  2762. mod_opt = Serializer::ReadableText.dump_advanced_options(mod, ' ')
  2763. print("\nModule advanced options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
  2764. # If it's an exploit and a payload is defined, create it and
  2765. # display the payload's options
  2766. if (mod.exploit? and mod.datastore['PAYLOAD'])
  2767. p = framework.payloads.create(mod.datastore['PAYLOAD'])
  2768. if (!p)
  2769. print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
  2770. return
  2771. end
  2772. p.share_datastore(mod.datastore)
  2773. if (p)
  2774. p_opt = Serializer::ReadableText.dump_advanced_options(p, ' ')
  2775. print("\nPayload advanced options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
  2776. end
  2777. end
  2778. end
  2779. def show_evasion_options(mod) # :nodoc:
  2780. mod_opt = Serializer::ReadableText.dump_evasion_options(mod, ' ')
  2781. print("\nModule evasion options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
  2782. # If it's an exploit and a payload is defined, create it and
  2783. # display the payload's options
  2784. if (mod.exploit? and mod.datastore['PAYLOAD'])
  2785. p = framework.payloads.create(mod.datastore['PAYLOAD'])
  2786. if (!p)
  2787. print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
  2788. return
  2789. end
  2790. p.share_datastore(mod.datastore)
  2791. if (p)
  2792. p_opt = Serializer::ReadableText.dump_evasion_options(p, ' ')
  2793. print("\nPayload evasion options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
  2794. end
  2795. end
  2796. end
  2797. def show_plugins # :nodoc:
  2798. tbl = Table.new(
  2799. Table::Style::Default,
  2800. 'Header' => 'Plugins',
  2801. 'Prefix' => "\n",
  2802. 'Postfix' => "\n",
  2803. 'Columns' => [ 'Name', 'Description' ]
  2804. )
  2805. framework.plugins.each { |plugin|
  2806. tbl << [ plugin.name, plugin.desc ]
  2807. }
  2808. print(tbl.to_s)
  2809. end
  2810. def show_module_set(type, module_set, regex = nil, minrank = nil, opts = nil) # :nodoc:
  2811. tbl = generate_module_table(type)
  2812. module_set.sort.each { |refname, mod|
  2813. o = nil
  2814. begin
  2815. o = mod.new
  2816. rescue ::Exception
  2817. end
  2818. next if not o
  2819. # handle a search string, search deep
  2820. if(
  2821. not regex or
  2822. o.name.match(regex) or
  2823. o.description.match(regex) or
  2824. o.refname.match(regex) or
  2825. o.references.map{|x| [x.ctx_id + '-' + x.ctx_val, x.to_s]}.join(' ').match(regex) or
  2826. o.author.to_s.match(regex)
  2827. )
  2828. if (not minrank or minrank <= o.rank)
  2829. show = true
  2830. if opts
  2831. mod_opt_keys = o.options.keys.map { |x| x.downcase }
  2832. opts.each do |opt,val|
  2833. if mod_opt_keys.include?(opt.downcase) == false or (val != nil and o.datastore[opt] != val)
  2834. show = false
  2835. end
  2836. end
  2837. end
  2838. if (opts == nil or show == true)
  2839. tbl << [ refname, o.disclosure_date.nil? ? "" : o.disclosure_date.strftime(DISCLOSURE_DATE_FORMAT), o.rank_to_s, o.name ]
  2840. end
  2841. end
  2842. end
  2843. }
  2844. print(tbl.to_s)
  2845. end
  2846. def generate_module_table(type) # :nodoc:
  2847. Table.new(
  2848. Table::Style::Default,
  2849. 'Header' => type,
  2850. 'Prefix' => "\n",
  2851. 'Postfix' => "\n",
  2852. 'Columns' => [ 'Name', 'Disclosure Date', 'Rank', 'Description' ]
  2853. )
  2854. end
  2855. #
  2856. # Returns an array of lines at the provided line number plus any before and/or after lines requested
  2857. # from all_lines by supplying the +before+ and/or +after+ parameters which are always positive
  2858. #
  2859. # @param all_lines [Array<String>] An array of all lines being considered for matching
  2860. # @param line_num [Integer] The line number in all_lines which has satisifed the match
  2861. # @param after [Integer] The number of lines after the match line to include (should always be positive)
  2862. # @param before [Integer] The number of lines before the match line to include (should always be positive)
  2863. # @return [Array<String>] Array of lines including the line at line_num and any +before+ and/or +after+
  2864. def retrieve_grep_lines(all_lines,line_num, before = nil, after = nil)
  2865. after = after.to_i.abs
  2866. before = before.to_i.abs
  2867. start = line_num - before
  2868. start = 0 if start < 0
  2869. finish = line_num + after
  2870. return all_lines.slice(start..finish)
  2871. end
  2872. end
  2873. end end end end