{"id":129963,"date":"2022-11-22T20:08:47","date_gmt":"2022-11-22T20:08:47","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=914974"},"modified":"2022-11-22T20:08:47","modified_gmt":"2022-11-22T20:08:47","slug":"bash-port-scanning-ssh-as-a-python-script-tryhackme","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/11\/22\/bash-port-scanning-ssh-as-a-python-script-tryhackme\/","title":{"rendered":"Bash Port Scanning (SSH) as a Python Script [TryHackMe]"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;914974&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/bash-port-scanning-ssh-as-a-python-script-tryhackme\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6GQYPGmEFQI%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<h2>Background<\/h2>\n<p>I\u2019ve been working on the Alice in Wonderland series of free hacking CTF (Capture the Flag) challenges on TryHackMe. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f6a9.png\" alt=\"\ud83d\udea9\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/tryhackme-capture-the-flag-ctf-walkthrough-lookingglass\/\" data-type=\"post\" data-id=\"914098\" target=\"_blank\" rel=\"noreferrer noopener\">Capture the Flag &#8211; Alice in Wonderland &#8211; TryHackMe Walkthrough<\/a><\/p>\n<p>While working on the second box in the series, <a href=\"https:\/\/tryhackme.com\/room\/lookingglass\" target=\"_blank\" rel=\"noreferrer noopener\">Looking Glass<\/a>, I stumbled upon a <a href=\"https:\/\/tay1or.li\/post\/thm-lookingglass\/\" target=\"_blank\" rel=\"noreferrer noopener\">bash script<\/a> written by <em>Tay1or<\/em>, another user on TryHackMe. <\/p>\n<p>The opening challenge involves finding the correct port which hides an encrypted poem, <a href=\"https:\/\/www.poetryfoundation.org\/poems\/42916\/jabberwocky\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Jabberwocky<\/em><\/a> by Lewis Caroll. <\/p>\n<p>Using a script here is a more efficient solution because it is quite time-consuming to manually attempt connecting to different ssh ports over and over until the correct port can be found. <\/p>\n<p>The box also resets the mystery port after each login, so unless you solve the box on your first attempt, the script will come in handy multiple times.<\/p>\n<h2>Bash Script<\/h2>\n<p>Here is <strong>Tay1or<\/strong>\u2019s bash script with a few slight modifications in bold to make it run on my machine:<\/p>\n<pre class=\"wp-block-preformatted\"><code>#!\/usr\/bin\/bash low=<strong>9000<\/strong>\nhigh=<strong>13000<\/strong> while true\ndo mid=$(echo \"($high+$low)\/2\" | bc) echo -n \"Low: $low, High: $high, Trying port: $mid &#8211; \" msg=$(ssh -o <strong>\"HostKeyAlgorithms=+ssh-rsa\"<\/strong> -p $mid $targetIP | tr -d '\\r') echo \"$msg\" if [[ \"$msg\" == \"Lower\" ]] then low=$mid elif [[ \"$msg\" == \"Higher\" ]] then high=$mid fi\ndone<\/code>\n<\/pre>\n<p>I\u2019m still new to bash scripting, but because I already understand the context of the problem being faced, I can more or less guess what the script is doing. <\/p>\n<p>At the top, under the shebang line, it first sets low and high values for the ports to be searched. Then we see a <code>while true<\/code> loop. <\/p>\n<p>The first command in the loop calculates the midpoint between the low and the high port values in the given range. <\/p>\n<p>The <code>echo<\/code> command prints the low\/high\/and midpoint port that is currently being tested. <\/p>\n<p>Then we have <code>if\/elif<\/code> commands to respond appropriately to the output of the <code>$msg<\/code> to set the mid to either the lower or higher range variables. By resetting the range after each attempted connection, the search will take a minimal amount of time by eliminating the largest number of ports possible on each attempt. <\/p>\n<p>When the output msg is neither \u201cHigher\u201d or \u201cLower\u201d it will end the loop because we will have hit our secret encrypted message on the correct port.<\/p>\n<h2>Conversion into a Python script<\/h2>\n<p>I started wondering how it might be possible to translate the bash script to a Python script and decided to try my hand at converting the functionality of the code.<\/p>\n<p>I\u2019m more comfortable scripting in Python, and I think it will probably come in handy later in future challenges to be able to quickly write up a script during CTF challenges to save time.\u00a0<\/p>\n<p>The inputs of the code are the <code>targetIP<\/code> and high and low values of the target SSH port range. <\/p>\n<p>Outputs are the response from the <code>targetIP<\/code> on each attempted connection until the secret port is found. Once the secret port is found, the program will reiterate that you have found the port.<\/p>\n<p>I posted the final version of the python script <a href=\"https:\/\/github.com\/Benjamin-James-Reitz\/THM-Looking-Glass-Python-Script\/blob\/main\/script-new.py\" target=\"_blank\" rel=\"noreferrer noopener\">here on GitHub<\/a>. For your convenience, I&#8217;ll include it here too:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">#!\/usr\/bin\/env python3\n# These sites were used as references: https:\/\/stackabuse.com\/executing-shell-commands-wi>\n# https:\/\/stackoverflow.com\/questions\/4760215\/running-shell-command-and-capturing-the-> #set up initial conditions for the target port search\nimport subprocess\nlow_port=9000\nhigh_port=13790\ntargetIP = \"10.10.252.52\"\nprint(targetIP)\n#initialize loop_key variable:\nloop_key=\"higher\" while loop_key==\"Higher\" or \"Lower\": print('low = ' + str(low_port) + ', high = ' + str(high_port))\n#a good place to use floor division to cut off the extra digit mid_port=(high_port+low_port)\/\/2 print('Trying port ' + str(mid_port)) #attempt to connect to the mid port result = subprocess.run(['ssh', 'root@' + str(targetIP), '-oHostKeyAlgorithms=+ssh-rsa', '-p', str(mid_port)], stdout=subprocess.PIPE) # prep the decoded output variable msg = result.stdout decoded_msg = msg.decode('utf-8') # print result of attempted ssh connection print(decoded_msg) if \"Higher\" in decoded_msg: #print(\"yes I see the words Higher\") high_port=mid_port print(high_port) loop_key=\"Higher\" elif \"Lower\" in decoded_msg: low_port=mid_port print(low_port) loop_key=\"Lower\" else: print(\"You found the secret port - \" + str(mid_port)) exit()<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Background I\u2019ve been working on the Alice in Wonderland series of free hacking CTF (Capture the Flag) challenges on TryHackMe. Recommended Tutorial: Capture the Flag &#8211; Alice in Wonderland &#8211; TryHackMe Walkthrough While working on the second box in the series, Looking Glass, I stumbled upon a bash script written by [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-129963","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129963","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=129963"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129963\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=129963"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=129963"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=129963"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}