homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defence Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
      • Summit Presentations
      • Posters & Cheat Sheets
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. Pen Test Poster: "White Board" - Bash - Check Service Every Second
370x370_Matthew-Toussain.jpg
Matthew Toussain

Pen Test Poster: "White Board" - Bash - Check Service Every Second

February 21, 2017

Board-Elements_Check-Service-Every-Second

If you've had the opportunity to take SANS 560, Network Penetration Testing and Ethical Hacking, chances are you were exposed to the Pentester's Pledge. The pledge, for those who aren't familiar is:

"I , do hereby pledge to use psexec to exploit Windows target machines after I have gained admin credentials and SMB access to the target environment. I shall forsake other service-side exploits thereafter. Otherwise, I unnecessarily risk crashing target systems".

As penetration testers, we have been endowed with the unalienable right to own all the systems (within our scope and rules of engagement of course). Cereal Killer, a whimsical character in the 1995 Hackers film, sums it up best during one of his ecclesiastical moments of clarity: "Listen, we got a higher purpose here, alright? A wake up call for the Nintendo Generation. We demand free access to data, well, it comes with some responsibility."

This responsibility is simple and it is not unique to our industry. Consider the Hippocratic Oath, which belies the medical principle of primum non nocere (do no harm). Like doctors, information security practitioners should perform with the lightest of touches. A heavy handed approach to security assessments, can lead to dire consequences side effects of pentest may include drowsy computers, frantic IT department parents, and in some cases death. Death! Yes, death, that eternal bit bucket where Google projects go to die in their hundreds. That means instead of breaking down doors with exploits, consider using the keys, after you've stolen them first of course!

In the end, though, light touches may not always be enough. When it comes to preventing a headache from escalating into a full blown migraine, vigilance is key. The sooner we can identify an unfortunate outage; the more quickly we can work with our clients to minimize any potential damage. Now, let's examine a few methods to bake rapid response actions into the penetration tester's toolkit.

503_error

Methods Covered in this Section:

Check service heartbeat:

nc -vv -z -w3 192.168.86.151

Check service every second bash loop:

while (true); do nc -vv -z -w3 10.0.0.1 80 >/dev/null && echo -e "Service is up"; sleep 1; done

Service UP/DOWN bash loop via "or": 

while (true); do nc -vv -z -w3 10.0.0.1 80 2>/dev/null && echo -e SERVICE UP || echo -e SERVICE DOWN; sleep 1; done

Checking the Pulse

If the end goal is to have bash notify us the moment a service goes down, the first step is to figure out how to tell if it is up vs down. One of the easiest ways for us to check its status is to simply connect to it with a "nc". Assuming that we're planning on exploiting a target located at  192.168.86.15 on port 445,  we could run the following to see that the service is still up:

Check service heartbeat:

nc -vv -z -w3 192.168.86.151 445

If the service is up we would see something like:

check_1

Command Breakdown

nc -vv -z -w3 192.168.86.151 445
1. nc - netcat is a tool that makes tcp connections given IP and PORT
 2. -vv - Print output in double verbose mode
 3. -z - execute in zero I/O mode. Without the -z option our nc connection to the victim machine on 445 would wait for input from the user, using the -z simply terminates the connection once it is established without sending any data.
 4. -w3 - Set connect timeout to 3s
 5. 192.168.86.151 145 - Destination IP PORT

While the above command could be run repeatedly (manually) to check the status of the service before, during, and after each exploitation attempt it would be easier to wrap the whole thing in one big bash while loop.
while (true); do...

Doing or checking something over and over again, endlessly sounds like a gloomy task for a person, but it suits computers just fine. Scripting languages like bash exist to help us solve a problem once and never worry about it again. The key to accomplishing this is often repetition. In computer logic, a loop allows us to do something over and over until a certain condition has been met. But what happens if we give the loop a condition that never proves true? In bash we can achieve infinite repetition like this:

check_2
1 is always less than 2 (-le) so the script will forever print "Hello World"

To make this more straightforward we can use something called a boolean operator. In this case, the word true will do. We can also run the entire thing on one line using the command separator: ;

check_3


Other operators we could use to build an infinite loop include: while : and while (true). Effectively, our template for running "things" is:

while true; do [thing]; [thing]; [thing]; done

Putting this all together gives us a powerful bash one-liner like this:

Check service every second bash loop:

while (true); do nc -vv -z -w3 10.0.0.1 80 >/dev/null && echo -e "Service is up"; sleep 1; done
check_4

As you can see the nc connection attempt responds with "Connection refused" as soon as the service, in this case a webserver, goes down.

Command Breakdown

while (true); do nc -vv -z -w3 10.0.0.1 80 >/dev/null && echo -e "Service is up"; sleep 1; done
1. while (true) - Begin the infinite loop
2. do nc -vv -z -w3 10.0.0.1 80 - Check service status
3. >/dev/null && echo -e - Suppress connection output and echo success to stdout
4. sleep 1 - Pause for 1 second before moving on
5. done - Finish the loop, and start back at the beginning

Success && || (and/or) Failure

For cleaner output we could suppress the output of the connection test and echo status messages based off of whether the last command was successful. Adding on the || (OR) operator allows us to make the service respond in a customizable fashion when the connection is refused:

Service UP/DOWN bash loop via OR:

while (true); do nc -vv -z -w3 10.0.0.1 80 2>/dev/null && echo -e SERVICE UP || echo -e SERVICE DOWN; sleep 1; done
check_5


Command Breakdown

while (true); do nc -vv -z -w3 localhost 80 2>/dev/null && echo -e SERVICE UP || echo -e SERVICE DOWN; sleep 1; done
1. while (true)...SERVICE UP - See previous command breakdown
2. do nc -vv -z -w3 10.0.0.1 80 - Check service status
3. || - The && operator means: "run the following if the previous executed successfully" || executes if it did not (connection refused)


Bonus - Leveraging the Environment

What if checking a service's status is not as simple as port UP/DOWN? Emily Cole (@unixgeekem) has some additional advice on the subject. Specifically, leverage the environment to gather additional telemetry on what may be going on. Techniques like "tail -f" against server logs or direct monitoring of syslogs and SEIM data can provide extra situational awareness. Occasionally, you may already have this access through past exploitation, but in the case of highly sensitive or production systems consider working with the host organization to have this access included in the rules of engagement up front. This might feel like giving away the keys, but remember: primum non nocere.

Matthew Toussain
https://twitter.com/0sm0s1z

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Tags:
  • Penetration Testing and Red Teaming

Related Content

Blog
Penetration Testing and Red Teaming, Cybersecurity and IT Essentials
January 4, 2023
Cloud Scanning for Vulnerability Discovery
In this article we'll look at the step-by-step process of scanning a cloud provider's network for target enumeration.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
Blog
Untitled_design-43.png
Digital Forensics and Incident Response, Cybersecurity and IT Essentials, Industrial Control Systems Security, Purple Team, Open-Source Intelligence (OSINT), Penetration Testing and Red Teaming, Cyber Defense, Cloud Security, Security Management, Legal, and Audit
December 8, 2021
Good News: SANS Virtual Summits Will Remain FREE for the Community in 2022
They’re virtual. They’re global. They’re free.
370x370-person-placeholder.png
Emily Blades
read more
Blog
Penetration Testing and Red Teaming
January 17, 2018
SANS Poster - White Board of Awesome Command Line Kung Fu (PDF Download)
Imagine you are sitting at your desk and come across a great command line tip that will assist you in your career as an information security professional, so you jot the tip down on a note, post-it, or scrap sheet of paper and tape it to your white board... now imagine you do this all the time...
SANS Pen Test
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn