Multiple Ways to Persistence on Windows 10 with Metasploit

In this article, you will learn the multiple ways to maintain access or create a persistent backdoor with the help of the Metasploit Framework on the host machine which you have compromised.

Table of Content

Persistence Backdoor

Pre-requisites

Methods for Generating persistence using Metasploit

  • Persistence_service
  • Mitigation method for persistence_service exploit.
  • Persistence_exe
  • Mitigation method for persistence_exe exploit.
  • Registry_persistence
  • Mitigation method for Registry_persistence exploit.
  • Persistence through Netcat.
  • Persistence through Remote Desktop Protocol.

 Conclusion

Persistence Backdoor

The word Persistence is simply known as permanent hence in this post, we are sharing the multiple methods to generate a permanent backdoor within the victim machine.

As there is a lot of hard work required to exploit any system and once the system is exploited successfully you need more time for further examine or penetrate the victim’s system but at that time if victim shut down his system or changed the credentials then all your hard work will be spoiled. That’s why maintaining access is an important phase of penetration testing. Persistence consists of techniques that adversaries use to keep access to systems across restarts, changed credentials and other interruptions that could cut off their access.

Pre-requisites

Window 10 -Victim System

Kali Linux – Attacker (Metasploit Framework)

Note: For creating a persistence backdoor, you should have a compromised machine of the victim with meterpreter session to continue all practices that are taught in this post.

Methods for Generating persistence using Metasploit

Let’s start, we already have compromised the window 10 (victim’s PC) and have meterpreter session along with the admin rights. To know how to get admin access click here. Now, we want to leave a permanent backdoor in the victim system that will provide a reverse connection for the next time.

Service Persistence

This Module will generate and upload an executable to a remote host, next will make it a persistent service. It will create a new service which will start the payload whenever the service is running. Admin or system privilege is required.

Thus, we will run the following commands on Kali Linux to run the above-listed module:

Above said module which will generate and upload an executable on the victim’s system under the /temp directory as  “lVFC.exe” and will make it a persistence service.

If the victim reboots the system, the previous meterpreter session will be closed. Only we need to set up the multi handler to run the payload by using the following commands:

Once the victim system starts, automatically we will gain the meterpreter session again.

When the PC is started automatically some of its services starts by default so persistence_service exploit creates a new service that will start the payload whenever the service is running. In the below image you can see the executable file IVFC.exe is running under username System and we can verify its path.

C:/Windows/Temp/IVFC.exe

Mitigation method for persistence_service exploit

First of all, identify the unfamiliar files which are running and then stop the running executable format file i.e. IVFC.exe and delete it from the temp directory.

Persistence_exe

This is the second method to maintain access to the victim’s PC. Under this scenario, we already have meterpreter session of the victim’s PC and it has user access.

This module will upload an executable to the victim’s system and make it persistent. It can be installed as a user, system or service. We will use this module by using the session 1(already compromised system’session) and set the rexpath (remote executable path), through this payload file will create on victim’s PC but due to persistence script, it will save under temp directory with default.exe name(change the name under rexname option ) and will set it to autorun under the registry path mentioned in below image.

 To run this module, type the following commands:

After, successful execution of the above module, now we have to set up the multi handle by using the following command:

Once the victim reboots its PC and the login into it, automatically we will get the meterpreter session.

In the below image you can see the function of persistence_exe, which will create the autorun service under the registry editor path:

due to which service will start running as soon as the victim’s PC starts. Its default file creates under the temp directory.

Mitigation Method for Persistence_exe

First, remove the entry from the registry editor under the path:

And then delete the executable payload file under the temp directory and reboot the system.

Registry Persistence

A registry is the core part of the window and contains a surplus of raw data. Attackers love to choose windows registry locations to hook their codes so that files or codes cannot be detected by scans for suspicious activities.

This module will install a payload that is executed during boot. It will be executed either at user logon or system startup via the registry value in “CurrentVersion\Run” (depending on privilege and selected method). The payload will be installed completely in the registry.

Since we already have compromised the victim’s Pc and have the meterpreter session along with the user privileges. Use the following command to execute the registry persistence.

Once the exploit executed, it will create a registry key under HKCU\software\wl4cN9w and installed key as highlighted in the image.

If the victim reboots the system, meterpreter session will dead get the session again just set up the multi handler payload and execute it.

Once the victim’s machine will start and as the victim will log in into the system, automatically we will get the meterpreter session again due to the autorun script under the registry which is installed by the attacker. Successfully registry _persistence is executed.

Through the below image you can verify the path of registry key created by registry_persistence exploit.

Persistence through Netcat

Netcat or nc is a utility tool that uses TCP and UDP connections to read and write in a network. It can be used for both attack and security. In the case of attack, it can be driven by scripts which makes it quite dependable back-end and if we talk about security, it helps us to debug the network along with investing it. To read more about netcat please refer https://www.hackingarticles.in/comprehensive-guide-on-netcat/.

Now we are going to make a persistence Netcat backdoor on the compromised system. As we already have meterpreter session, upload netcat.exe into system32 file of victim’s pc by using the following command:

The next step is to set the netcat to listen on the random port i.e.4445, open the port on startup and make the connection.

Use the following command:

On successful netcat connection, we get the shell of the victim’s PC.

We will add the new rule in the firewall named as ‘netcat’ in which inbound connection will allow for port 4445 by using the interactive cmd prompt running a command called netsh. Type the following command:

To check the operational mode and port status run the command:

When the victim reboots the system again, we will get the netcat shell. On Kali Linux(attacker system) run the following command to connect our netcat backdoor via port 4445.

Persistence through RDP

After having the meterpreter session of the already compromised targeted system. We will utilize Carlos Perez’s getgui script which enables Remote Desktop and creates a user account to login to it.

Username: Nisha

Password: 123

Run the following command:

With the help of the following module, it is possible to apply the ‘sticky keys’ hack to a session with appropriate rights. The hack provides a means to get a SYSTEM shell using UI-level interaction at an RDP login screen or via a UAC confirmation dialog.

As you can see here that we sticky is added successfully, now to launch the exploit at an RDP or UAC by press shift key 5 times.

Now we will check the connection using rdesktop and review the certificate and type Yes. By using the following command

Congrats !!! finally we get the Gui mode of the victim’s system.

 Conclusion

Persistence does not require any authentication to connect with the victim’s system. To complete the penetration testing, always remember to clean up the processes and the backdoor services on the victim’s host.

Author: Nisha Sharma is trained in Certified Ethical hacking and Bug Bounty Hunter. Connect with her here

Forensics Investigation of Ping Command

Introduction:

When we say “ping,” we often are just limiting its definition to checking whether a host is alive or not. In my opinion, while this purpose is correct, its technical details are often ignored. Many network administrators are unable to answer what ping is in details; or how it works. So in this research-based article, I am going to present some points that I didn’t know before starting to read about the topic.

Tools used: Wireshark, command prompt/terminal, https://www.rapidtables.com/convert/number/hex-to-ascii.html

In this article, practicals are based on a Windows 10 x64 system to ping a Debian Linux x64 bit architecture. While this shouldn’t matter in many cases, it matters for a certain part where we calculate TTL and an anomaly case as well. More of that later though. While reading about this topic I learnt tons of new stuff that for me, as a penetration tester, would definitely be useful to understand in-depth how those exploits are working.

Let’s get to the good stuff now.

Table of Content:

  • OSI Model
  • Ethernet, IP and ICMP protocols
  • Ping command and ping packet
  • Wireshark and basic filters
  • How is a datagram sent to destination host (understanding layers involved using Wireshark)
  • Understanding data size in ping
  • MTU in IEEE 802.3i
  • Fragmentation in ping
  • Anomaly in ping

OSI Model:

OSI stands for Open System Interconnection is a reference model that describes how information from a software application in one computer moves through a physical medium to the software application in another computer.

It has seven layers and each layer performs a special network task. They are as follows:

Each layer has a specific task to do and we’re not going into depth with each and every one of them. Let’s save that for another day. Let’s focus on layers 1, 2 and 3 for now.

Layer 1, 2 and layer 3 combined are responsible for the effective transmission of ICMP packets.

Ethernet, IP and ICMP Protocols

While “pinging” a system, layers 1, 2 and 3 are in action. Each layer defines its own “format of protocol options” known as a header. It precedes the actual data to be sent and has information such as the source IP, destination IP, checksum, type of protocol etc. And when it is attached with the actual data to be sent, it forms a protocol data unit which is renamed as per the layer.

Default protocol data units (PDU) in these layers are:

  • Layer 1: bits
  • Layer 2: frame
  • Layer 3: packet
  • Layer 4: datagram

We’ll be using these terms quite often and it is important to be clear what these terms mean. While the data is travelling through these layers, it is converted virtually into its own PDU.

Ethernet

IEEE 802.3 is a set of standards and protocols that define Ethernet-based networks. Ethernet technologies are primarily used in LANs. There are a number of versions in IEEE 802.3 such as the 802.3a, 802.3i etc. When we ping, there is some data sent to the destination host and in a specific format.

Ethernet header:

IP (Internet Protocol)

It is the principal communications protocol for relaying datagrams across network boundaries. IP has the task of delivering packets from the source to the host solely based on the IP address in the packet headers. IP defines packet structures that encapsulate the data and headers.

ICMP (Internet Control Message Protocol)

Since IP does not have an inbuilt mechanism for error control and sending control messages, ICMP is here to provide that functionality. It is a supporting protocol used by network devices like routers for sending error messages.

Ping

Ping is a computer networking utility used to test the reachability of a host on IP network. Ping operates by sending ICMP Echo request packets and waits for ICMP Echo replies. This reports error, TTL, packet loss etc. One ping request is a combination of Ethernet, IP and ICMP headers and data.

Useful ping options in windows and Linux are:

Windows:

Options Functionalities
-t To see statistics and continue – type Control-Break; To stop – type Control-C.

Ping the specified host until stopped.

-a Resolve addresses to hostnames.
-n count The number of echo requests to send.
-l size Send buffer size.
-f Set Don’t Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use the routing header to test reverse route also (IPv6-only). Per RFC 5095 the use of this routing header has been deprecated. Some systems may drop echo requests if this header is used.
-S srcaddr Source address to use.
-c Compartment Routing compartment identifier.
-p

 

Ping a Hyper-V Network Virtualization provider address.
-4 Force using IPv4.
-6 Force using IPv6.

Linux:

Options Functionalities
-a use audible ping
-A use adaptive ping
-B sticky source address
-c <count> stop after <count> replies
-D print timestamps
-d use SO_DEBUG socket option
-f flood ping
-h print help and exit
-I <interface> either interface name or address
-i <interval> seconds between sending each packet
-L suppress loopback of multicast packets
-l <preload> send <preload> number of packages while waiting replies
-m <mark> tag the packets going out
-M <pmtud opt> define mtu discovery, can be one of <do|dont|want>
-n no dns name resolution

 

-O report outstanding replies
-p <pattern> contents of padding byte
-q quiet output
-Q <tclass> use quality of service <tclass> bits
-s <size> use <size> as number of data bytes to be sent
-S <size> use <size> as SO_SNDBUF socket option value
-t <ttl> define time to live
-U print user-to-user latency
-v verbose output
-V print version and exit
-w <deadline> reply wait <deadline> in seconds
-W <timeout> time to wait for response

IPv4 options:

Options Functionalities
-4 use IPv4
-b allow pinging broadcast
-R record route
-T <timestamp> define timestamp, can be one of <tsonly|tsandaddr|tsprespec>

IPv6 options:

Options Functionalities
-6                 use IPv6
    -F <flowlabel>     define flow label, default is random
  -N <nodeinfo opt> use icmp6 node info query, try <help> as argument

Ping sends out IP packets with ICMP_Echo_Request to the destination and waits for its reply (IP packet with ICMP_Echo_Reply).

The ICMP packet is encapsulated in an IPv4 packet. The general composition of the IP datagram is as follows:

When a ping command is sent to the host, the datagram is encapsulating Ethernet header, IP header, ICMP header and payload too. The minimum size of an IPv4 header is 20 bytes and the maximum size is 60 bytes.

The default size of payload data in ping in windows is 32 bytes. Let’s add 20 bytes of IP header in it and 8 bytes of ICMP header. 32+20+8, it comes out to be 60 bytes.

But, when we analyse ping in Wireshark, the size of the frame written in the log is 74 bytes. This is because while pinging, we would need the destination and source MAC address as well, which is available in the Ethernet header.

So, 14 + 20 + 8 + 32 = 74 bytes.

So, ping sends an encapsulated IP packet which is a combination of:

Ethernet header + IP header + ICMP header + ICMP payload

But, keep on reading for very interesting cases that made me write this article.

Wireshark and Basic Filters

Wireshark is a freely available network monitoring tool that is able to log all the traffic incoming and outgoing from a single NIC card. I won’t be telling how to set up Wireshark and start logging, please use this tutorial for it.
In the above case, when we ping a Linux system from a windows system, we see something like:

Let’s go step by step and see what just happened.

  1. I’ve pinged IP address 192.168.217.128 from my source IP 192.168.238.1 and captured just one packet to see clearly the action.
  2. On the top, there is a Wireshark filter applied for the IP address that goes like addr == 192.168.217.128
  3. Some other useful Wireshark filters are:
    http or dns

  1. Next, you can see the total length of the datagram sent, that is, 74 bytes, as already explained above.
  2. Then you can see, in yellow, Ethernet frame. Here, you’ll find the Ethernet header.
  3. After that is the IPv4 packet. IP is used to deliver packets from source to destination based on the IP addresses.
  4. Finally, we see the ICMP header and payload data.
  5. All these layers are involved in a simple ping over IEEE 802.3. In the next section, we’ll learn how to analyse a packet data using Wireshark to get an in-depth view of packet forensics.

How is a datagram sent to the destination?

When a datagram is sent from source to destination, in our case, when we ping, the format of the datagram is as follows:

We’ll ping a destination with default options:

Let’s start analysing the traffic in Wireshark now.

I just captured a single datagram in Wireshark when I pinged a destination host and analysed it layer by layer.

Talking about Layer 2 here, we can see that Ethernet type 2 is being used.

As we talked in point 2, Ethernet frame sent with ping includes the source and destination MAC along with the type of protocol being used.

0000   00 0c 29 d7 b1 35 00 50 56 c0 00 08      08 00

           Destination MAC         Source MAC          EtherType

                (6 bytes)                      (6 bytes)             (2 bytes)

The most important field here is the EtherType field as on analysing these bytes we can find the protocol that was used in the communication. This is really essential for forensics point of view and some of the most important hex values are:

Ethernet Types Hex Value                       
ARP 08 06
IPv4 08 00
IPv6 86 dd
IEEE 802.1Q 81 00

Moving on to layer 3, we see an IP packet, since obviously ping is using IP protocol to check if a host is alive or not. Here is the observation of the hex dump of IP packet:

0000   ….45           00              00 3c da 40 00 00 80        01 2c ad c0 a8 d9 01

        Header    Type              Total                        TTL     Protocol        Source IP

        Length     of service     Length

        (1 byte)    (1 byte)       (2 bytes)                 (1 byte)  (1 byte)          (4 bytes)

0010   c0 a8 d9 80

           Destination IP

              (4 bytes)

From the analysis of this IP packet, we observe that IP header is then added to the Ethernet frame to make a packet that has the above-mentioned options specified. By analysing this data we can observe a lot of different things. Some of which are:

TTL:

OS Hex Value TTL Decimal Value TTL
Windows 80 128
Linux 40 64
Mac 39 57

Type Of Protocol:

Protocol Hex Value Decimal Value
ICMP 1 1
TCP 6 6
EGP 8 8
UDP 11 11

One really interesting thing to note is the Header Length. We see that header length is written as 45 in hex which comes out to be 69 which is not possible. On further breaking down this byte, we see that the first nibble (half byte) tells the version of the protocol.

4 = hex value = 4 (version of protocol), that is IPv4

5 = hex value = IHL (Internet Header Length) = next for bits

And so on (total length = 00 3c = 60 bytes)

A datagram is completed and transported when ICMP header is added in Layer 3. We know that IP lacks error control mechanism, so ping uses ICMP to serve that purpose. ICMP protocol is specified in IP header as we saw above and hence, it is important to analyse ICMP header to better understand the underlying mechanism of ping.

0000     08            00              4d 53 00 01 00 08 61 62 63 64 65 66 67 68

           Type        Code           Checksum                         Data

           (1 byte)    (1 byte)       (2 bytes)                         (32 bytes)

0010   69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 61

0020   62 63 64 65 66 67 68 69

Type: It is the type of request of ICMP request sent. According to IANA, there are 45 assigned requests.

We can see, 08 as the Type of request which symbolises Echo request. When one system pings another system, it sends a Type 8 request and if the host is alive, the host sends back Type 0 (Echo Reply) request.

Code: It is simply the hex value of the type of ICMP request message. It ranges from 0 to 15 for each of the types. This reference is taken from Wikipedia:

Checksum: “The checksum is the 16-bit one’s complement of the one’s complement sum of the ICMP message starting with the ICMP Type. For computing the checksum, the checksum field should be zero. If the total length is odd, the received data is padded with one octet of zeros for computing the checksum. This checksum may be replaced in the future.” – RFC 792

So, to calculate the checksum, we have to split the ICMP header and payload data into multiple pairs of 2 bytes each, calculate the one’s complement of first two bytes, add with the next one and repeat it till all the bytes are exhausted.

Here, checksum status is shown as good and correct, so we need not look any further.

Data: Contains other essential data like timestamp, sequence number, magic number etc.

Data size in ping

According to RFC 791, an IP can handle a datagram of maximum size 65,535 bytes. However, by default, the data in ping is 32 bytes and the whole datagram is by default 60 bytes in case of windows. Adding 14 extra bytes of Ethernet header, it comes out to be 74 bytes which we see in Wireshark. Focus on the colour codes here:

Red= ICMP payload data size

Green= Total length of the IPv4 packet

Maroon= Total length of the datagram

Let’s talk about Linux now. The default IP packet size in Linux’s case is 56 bytes. Adding extra 28 bytes of IP and ICMP header makes it 84 bytes. Adding more 14 Ethernet frame header bytes makes it 98 bytes.

However, we can add data as per our wish, as long as it remains under 65,535 bytes using the ping –l option in Windows. This also has some limitations. Let’s talk about them in the next section.

MTU in IEEE 802.3i

MTU stands for Maximum Transmission Unit and it is the size of the largest Protocol Data Unit that can be communicated in a single network-layer operation. IEEE 802.3 standards restrict the minimum to 48 bytes and the maximum to 1500 bytes. So, if I am to transfer more than 1500 bytes of data in a single datagram, it would be fragmented into multiple packets.

To understand MTU, we’ll take up four cases:

Data payload size=200 bytes, 1472 bytes, 2000 bytes, 65500 bytes

Payload size 200 bytes:

We see that the size of IPv4 datagram comes out to be 242 bytes. This is a result of 200 payload bytes + 8 bytes ICMP header + 20 bytes of IP header + 14 bytes of Ethernet header. The noticeable thing here is that still a single datagram is sent and no fragmentation is done. Let’s push the limit to MTU now.

Now let’s push the limits of ping packet to the MTU, that is, 1500 bytes in case of an IEEE 802.3.

Notice some things here. We have not set the data size as 1500 which is the MTU rather 1472 due to the fact that protocol has some bytes for the headers in reserve.

20 bytes of IP and 8 bytes of ICMP headers are automatically added in every transaction as we’ve seen. So, 1500-28=1472 is the maximum payload data size that we can specify in a ping command.

These 1500 bytes are then collated with ethernet header and finally, a datagram of 1514 bytes is transferred.

So, what will happen when this data size is increased from 1472? Let’s check out.

Fragmentation in ping

IP fragmentation or ping fragmentation is a process in which a packet exceeding the size of MTU is broken into multiple pieces and transacted to the destination host. RFC 791 has the procedure for IP fragmentation, transmission and reassembly of packets.

Let’s increase the size of the data payload to 2000 bytes and let’s see what happens.

Now, we can see that fragmentation is done and the datagram is split into two fragments of size 1480 and 520 bytes. Why?

The first fragment is 1500 bytes in total length but the data is only 1480 because 20 bytes are always in reserve for IP protocol header, and the second fragment is 520 bytes in payload data size.

First fragment= 1480 (data size) + 20 (IP header)

Second fragment= 520 (data size) + 20 (IP header) + 8 (ICMP header)

It is important to note that ICMP header is not added in the first fragment and it will only be added when the whole datagram is complete. It is because ICMP is responsible for error control and it calculates the checksum. For checksum to be calculated, whole data should be transmitted first and hence, ICMP header is not added in the initial fragments but only in the last fragment.

Now we push these limits to the maximum size.

Here, the datagram is split into multiple 44 fragments of 1480 bytes each and the last packet is 408 (minus 28= 380 bytes) bytes in size.

You must not get confused here. 65500 is the maximum size of a payload that we can specify in ping.

However, each of the 44 frames is of size 1500 bytes and the last frame is 388+20+8 bytes, which comes out to be 66416 bytes. Hence, the cumulative size of a packet datagram can be at max 66416 bytes.

Add on extra 14 bytes of Ethernet header, it comes out to be: 67,046 bytes.

Anomaly in Ping

Let’s focus on a case when the payload size is specified as 0. Let’s see what the protocols do with 0 bytes of data.

As expected, the request goes with 42 bytes (20 + 8 + 14) with 0 bytes of data but wait, why does the reply come back as 60 bytes?

On analysing the hex dump, we see that a Linux system is replying with 18 null bytes of data.

If we specify ping –s 0 in Linux machine, maybe we get some answer.

Okay, so in the terminal, we see “pinging with 0 (28) bytes of data” which means 28 bytes of IP plus ICMP header and 0-byte data. BUT, Wireshark shows us something size of 60 bytes and has again added an extra 18 bytes.

Turns out that these 18 bytes are Ethernet padding bytes and that’s why this anomaly has arisen. IEEE 802.3 adds extra bytes if data is less than 18 bytes in case of Linux known as padding bytes or pad bytes.

Let’s specify a data in the range: 1<x<18 for example, 10 bytes. Let’s see what happens.

In Wireshark, we see the size is still 60 bytes. And 10 bytes have been written by the hex values from 0 to 9, while rest of them are still null bytes.

It is safe to say the same anomaly will exist when we specify data in the multiples of 1480 since the last fragment will have 0 bytes of data to be sent and padding would be added.

This was an interesting anomaly and made us understood some details of the IEEE 802.3 standards difference in Windows and Linux.

Author: Harshit Rajpal is an InfoSec researcher and left and right brain thinker. contact here

SSH Penetration Testing (Port 22)

Probing through every open port is practically the first step hackers take in order to prepare their attack. And in order to work, one is required to keep their port open but at the same time, they are threatened by the fear of hackers. Therefore, one must learn to secure their ports even if they are open. In this post, we will discuss penetration testing of SSH which is also known as Secure Shell.

Table of content

  • Introduction to SSH
  • SSH Installation
  • SSH Port Scanning
  • Methods to Connect SSH
    • Terminal Command (Linux)
    • Putty (Windows)
  • Port Redirection
  • Port Redirection Testing
  • Establish SSH connection using RSA key
  • Exploit SSH with Metasploit
    • SSH Key Persistence- Post Exploitation
    • Stealing the SSH key
    • SSH login using pubkey
  • SSH Password cracking

Introduction to SSH

The SSH protocol also stated to as Secure Shell is a technique for secure and reliable remote login from one computer to another. It offers several options for strong authentication, as it protects the connections and communications\ security and integrity with strong encryption. It is a secure alternative to the non-protected login protocols (such as telnet, rlogin) and insecure file transfer methods (such as FTP).

SSH Installation

It very easy to install and configure ssh service, we can directly install ssh service by using the openssh-server package from ubuntu repo. To install any service you must have root privilege account and then follow the given below command.

when you will execute above command it will extract the package the install the default configure on the host machine. you can check open port with the help of netstat command on the host machine.

SSH Port Scanning

If you don’t have direct access to the host machine, use nmap to remotely identify the port state that is considered to be the initial step of the penetration test. Here we’re going to use Kali Linux to perform a penetration testing.

So, to identify an open port on a remote network, we will use a version scan of the nmap that will not only identify an open port but will also perform a banner grabbing that shows the installed version of the service.

Methods to Connect SSH

Terminal Command (Linux)

Now execute the following command to access the ssh shell of the remote machine as an authorized user. Username: ignite

Password: 123

Putty (Windows)

Step1: Install putty.exe and run it, then enter the HOST IP address <192.168.1.103> and port <22>, also choose to connect type as SSH.

Step2: To establish a connection between the client and the server, a putty session will be generated that requires a login credential.

Username: ignite

Password: 123

Port Redirection

By default, ssh listen on port 22 which means if the attacker identifies port 22 is open then he can try attacks on port 22 in order to connect with the host machine. Therefore, a system admin chooses Port redirection or Port mapping by changing its default port to others in order to receive the connection request from the authorized network.

Follow the below steps for port redirection:

Step1: Edit the sshd_config from inside the /etc/sshd using the editor

Step2: Change port 22 into 2222 and save the file.

Step3: Then restart ssh

Port Redirection Testing

Thus, when we have run the scan on port 22, it has shown port state CLOSE for ssh whereas port 2222 OPEN for ssh which can be seen the given image.

Establish SSH connection using RSA key

Strong passwords don’t seem to be decent to secure the server because a brute force attack can crack them. That’s why you need an additional security method to secure the SSH server.

SSH key pairs is another necessary feature to authenticate clients to the server. It consists of a long string of characters: a public and a private key. You can place the public key on the server and private key on the client machine and unlock the server by connecting the private key of the client machine. Once the keys match up, the system permits you to automatically establish an SSH session without the need to type in a password.

Ssh-keygen is a tool for creating new authentication key pairs for SSH. Such key pairs are used for automating logins, single sign-on, and for authenticating hosts.

Thus, we will follow the steps for generating a key pair for authenticated connection.

Step1: Run the given command to generate an ssh key pair (id_rsa and id_rsa.pub) on the host machine Ubuntu.

Step2: Same should be done on the client machine which is authorized to establish the connection with the host machine (ubuntu).

Step3: Once the ssh key pair (id_rsa and id_rsa.pub) get generated then rename the id_rsa.pub into authorized_keys as show in the given image.

Step4: Share the authorized_keys with the host machine by copying it into the .ssh directory.

Step5: Edit the sshd_config from inside the /etc/sshd using the editor

Step6: Enable the “passwordauthentication no” comment

As a result of only the authorized machine which rsa key can establish a connection with the host machine without using password.

Now if you need to connect to the ssh server using your password username, the server will drop your connection request because it will authenticate the request that has authorized key.

Step7: Copy the id_rsa key from Kali Linux to the windows machine, to established connection using authorized keys on the windows machine,

Step8: Install puttygen.exe

Step 9: Run puttygen.exe and load the id_rsa and “save as key” named as Key

Step10: Use putty.exe to connect with the host machine by entering hostname 192.168.1.103 and port 22.

Step11: Navigate to SSH >auth and browse the key private key that you have saved as mention in step 9.

This will establish an ssh connection between windows client and server without using a password.

Exploit SSH with Metasploit

SSH Key Persistence- Post Exploitation

Consider a situation, that by compromising the host machine you have obtained a meterpreter session and want to leave a permanent backdoor that will provide a reverse connection for next time.

This can be achieved with the help of the Metasploit module named “SSH Key Persistence-a post exploit” when port 22 is running on the host machine.

This module will add an SSH key to a specified user (or all), to allow remote login on the victim via SSH at any time.

As can be seen in the image given, it added authorized keys to /home / ignite/.ssh and stored a private key within /root/.msf4/loot

As we ensure this by connecting the host machine via port 22 using a private key generated above. Here I have renamed the private as “key” and gave permission 600.

Bravo!! It works without any congestion and in this way, we can use ssh key as persistence backdoor.

Stealing the SSH key

Consider a situation, that by compromising the host machine you have obtained a meterpreter session and port 22 is open for ssh and you want to steal SSH public key and authorized key. This can be done with the help Metasploit module named “Multi Gather OpenSSH PKI Credentials Collection -a post exploit” as discussed below.

This module will collect the contents of all users .ssh directories on the targeted machine. Additionally, known_hosts and authorized_keys and any other files are also downloaded. This module is largely based on firefox_creds.rb.

From given below image you can see we have got all authorized keys store in /home/ignite/.ssh directory in our local machine at /root/.msf4/loot and now use those keys for login into an SSH server.

This can be done manually by downloading keys directly from inside /home/ignite/.ssh as shown in the below image.

As we ensure this by connecting the host machine via port 22 using private key downloaded above. Let’s change the permission for the rsa key and to do this follow the step given below.

It works without any congestion and in this way, we can use ssh key as persistence backdoor.

SSH login using pubkey

Considering you have id_rsa key of the host machine and want to obtain meterpreter session via Metasploit and this can be achieved with the help of the following module.

This module will test ssh logins on a range of machines using a defined private key file and report successful logins. If you have loaded a database plugin and connected to a database this module will record successful logins and hosts so you can track your access. Key files may be a single private key or several private keys in a single directory.

This will give a command session which can be further updated into the meterpreter session by executing the following command.

SSH Password cracking

We can test a brute force attack on ssh for guessing the password or to test threshold policy while performing penetration testing on SSH. It requires a dictionary for username list and password list, here we have username dictionary “user.txt” and password list named “pass.txt” to perform the brute force attack with the help of hydra

As a result you can observe that the host machine has no defence against brute force attack, and we were able to obtain ssh credential.

To protect your service against brute force attack you can use fail2ban which is an IPS. Read more from here to setup fail2ban IPS in the network.

If you will observe the given below image, then it can see here that this time the connection request drops by host machine when we try to launch a brute force attack.

Conclusion: In this post, we try to discuss the possible way to secure SSH and perform penetration testing against such a scenario.

Author: Nisha Sharma is trained in Certified Ethical hacking and Bug Bounty Hunter. Connect with her here

Hiding Shell using PrependMigrate -Metasploit

In this article, you will get to know about the strength of mfsvenom along with PrependMigrate. You will also learn how to migrate the created payload into processes currently running on the targeted machine so, the victim unable to find the malicious file. It is very important to migrate your backdoor payload because if the target is alerted and decides to take measures to kill the process then, your session will also get killed. Therefore, an attacker must do this as soon as the session opens.

Table of Content

  • Basic Terminologies
    • Metasploit Framework
    • MSFvenom
    • PrependMigrate
  • Hiding shell with PrependMigrate
    • With MSFvenom.
    • Without MSFvenom.

Basic Terminologies

Metasploit Framework

Metasploit Framework, an open-source tool for developing and executing exploit code against a remote target machine.

Steps for exploiting a system using the Framework include:

  • Choosing and configuring an exploit
  • Checking whether the intended target system is susceptible to the chosen exploit
  • Choosing and configuring a payload
  • Choosing the encoding technique
  • Executing the exploit.

This modular approach – allowing the combination of any exploit with any payload – is the major advantage of the Framework. It facilitates the tasks of attackers, exploits writers, and payload writers. 

Msfvenom

MSFvenom is a combination of Msfpayload and Msfencode, putting both of these tools into a single Framework instance. It is used to generate and encode various types of payload that are available in the Metasploit Framework. The advantages of msfvenom are:

  • One single tool
  • Standardized command-line options
  • Increased speed

PrependMigrate

PrependMigrate is an option that allows us to link our session with an ongoing process on the target system. It can also transfer a session by linking it from one process to another. It comes handy as it is difficult for the target to find the malicious process so it becomes paramount for the attacker to cover their tracks.

Configurations used in Practical

Attacker:

    OS: Kali Linux

    IP: 192.168.1.107

Target:

      OS: Windows 10

      IP: 192.168.1.104

First Method

Let’s start the game of conceal and seek. You have to conceal to save yourself and let the target try to find you.

Starting with MSFvenom we will be creating a malicious executable named raj.exe and conceal the generated executable behind a process named explorer.exe (you can choose any process running on task manager) by PrependMigrate process.

Next, we will be loading the Metasploit framework on Kali Linux by using the msfconsole keyword. Then set the following options to enable our handler:

Now, we will send the payload to the target machine and run the executable on the Target Machine. This will generate a meterpreter session which will be captured by the listener we created earlier. You can access the target system but if the target acknowledges that the system is compromised; then they can take security measures to end your session. To escape from this situation, the attacker’s first responsibility is to conceal the executable payload behind the process so the victim cannot identify it in any way possible.

Use the following ps command to check the processes that are running presently and filter with the raj.exe

 The process ID (PID) of raj.exe i.e. 4848 as shown in the process list and if the victim kills the raj.exe i.e. 4848 PID then the running process will end. Thus, ending our session with a simple command:

But you do not need to worry as PrependMigrate saves the day by letting us conceal raj.exe behind the explorer.exe and you will be at an advantage as your meterpreter session is still running. 

Second Method

The Second way of hiding shells using the PrependMigrate but without using msfvenom. Here, the objective is the same as the earlier. We will start by opening the Metasploit Framework.

Then use the following set of commands to create your payload:

After the creation of malicious executable i.e. nisha.exe, we will create listener multi/handler using the following commands:

Using the ps command along with grep command we will get the PID of nisha .exe i.e.4128

(Note: PID stands for process id, which means the identification number for currently running process in memory. PPID stands for Parent Process Id, which means the parent process is responsible for creating the child (current) process. Through parent Process, the child process will be created.)

Now we try ourselves to kill the nisha.exe process to get conceal from the victim with the following command:

But still, you have a victim’s session which means nisha.exe migrates into new process id of explorer.exe. And you can use the sysinfo command to confirm that the session is still up and running.

Conclusion

This is how one conceals themselves. The purpose of this article is to serve both the blue team and the red team as one should be aware of how to locate and eliminate the attacker as well as how to conceal yourself when you are on the other side of the line.

Author: Nisha Sharma is trained in Certified Ethical hacking and Bug Bounty Hunter. Connect with her here