Technology and Security

Tag: Java

building apache tomcat from source

Building Apache Tomcat from Source

Building Apache Tomcat from source is easy, and is the first step to building your own Tomcat mods. Comprehensive instructions are provided by Apache in the BUILDING.txt file. This article will augment those steps with screenshots and a few helper scripts to make the job a bit easier. If you haven’t already done so, provision a plain Linux virtual machine. Directions for this process can be found in this article.

What is Apache Tomcat?

If you are reading this article and do not already know the answer to this question, you are probably in the wrong place. Apache Tomcat is a web container. It is a free open source implementation of the Jakarta Servlet, Jakarta Server Pages, Jakarta Expression Language, Jakarta WebSocket, Jakarta Annotations and Jakarta Authentication specifications. In a nutshell, Tomcat provides an HTTP web server environment for hosting Java code.

Virtual Machine Setup

As mentioned earlier, directions for creating an Ubuntu virtual machine can be found here. We will use that same process to create a standard Linux workstation with the following specifications:

  • OS: Ubuntu 22 LTS (although any modern version will be fine)
    • Minimal installation
  • RAM: 4GB
  • Drive: 20GB
Linux VM Specifications
Linux VM Specifications
Linux Minimal Installation
Linux Minimal Installation

Next we install the tools needed to compile Tomcat by cloning a helper repository maintained by AttainIT Technologies.

$ cd ~
$ sudo apt install git -y
$ git clone https://github.com/AttainIT-Technologies/vm-bootstrap-ubuntu.git
$ cd tomcat-dev
vm-bootstrap-ubuntu repo
vm-bootstrap-ubuntu repo
Clone GitHub Repo
Clone GitHub Repo

Finally we run the bootstrap script which will install java and ant, as well as download the source and setup the Tomcat build directory. The setup script is small and can be viewed here.

$ ./bootstrap
Workstation Setup
Workstation Setup

At this point we have completed our workstation setup and are ready to build Apache Tomcat from source.

Building Apache Tomcat from Source

Now that we have our workstation, we can build the source. Since we cloned the default branch, we have the main branch of Tomcat (most recent updates). Depending on your needs, you could replace this code with one of the other branches for Tomcat v8.x or 9.x releases.

tomcat repo
tomcat repo

Compile the source by running the following commands:

$ cd $TOMCAT_SRC
$ ant
Relocate to Tomcat Source
Relocate to Tomcat Source

The build is a bit like jumping into a time machine, as it still uses Apache Ant for its build tool. Depending on your workstation’s horsepower, the build could take up to several minutes to complete.

Building Tomcat from Source
Building Tomcat from Source

Once complete, you can change into the output directory and see the results.

Apache Tomcat Build Results
Apache Tomcat Build Results

Looking at the build directory should look very familiar, as it is a standard Tomcat distribution as you would normally download directly from Apache.

Apache Tomcat Distribution
Apache Tomcat Distribution

Since our source code has been compiled into executable binaries, lets continue on and launch our web container.

Running Apache Tomcat

Before launching our server, we should first check our version:

$ ./version.sh
Tomcat Version
Tomcat Version

Buried in the results above you can see that we have built Apache Tomcat version 10.1.0-M18-dev. Launch the server by running startup:

$ ./startup.sh
Launch Apache Tomcat
Launch Apache Tomcat

Finally, open the console in a browser:

https://localhost:8080
Web Console
Web Console

Congratulations, you have built the latest milestone release of Apache Tomcat.

Inspecting the Apache Tomcat Source

The bootstrap script also installs a recent copy of Microsoft Visual Studio Code. Use that IDE to inspect the Tomcat source code by running the following commands:

$ cd $TOMCAT_SRC
$ code .
Launch Visual Studio Code
Launch Visual Studio Code
Apache Tomcat Source Code
Apache Tomcat Source Code
AttainIT Loves Apache
Send email from Spring Boot using Microsoft 365

Send Email using Spring Boot

This article is documents how to send email using Spring Boot over Microsoft 365 (formerly Office 365). Spring provides an easy to use interface called JavaMailSender that wraps the native JavaMail API. This example demonstrates sending both plain and HTML messages, as well as adding attachments.

Microsoft 365

Microsoft 365 subscriptions come with Outlook email access via browser or by native Office client applications. The Microsoft email solution (Outlook and Exchange) is ubiquitous for business users; It also offers the ability to connect from external clients for both sending and receiving messages. We will leverage this capability to send messages from a custom Java application.

JavaMailSender

Spring Boot provides this extended interface for JavaMail that supports MIME messages and completely handles session management. Messages containing attachments typically use this interface in conjunction with the MimeMessageHelper class.

Spring Boot Properties

Spring Boot pulls the mail settings from your default application.properties file (or YAML depending on your local setup). First set the properties to reference a Microsoft 365 (formerly Office 365) SMTP email host and enable security. Our GitHub repository should not contain sensitive property values, so externalize those variables.

// application.properties

spring.mail.host=smtp.office365.com
spring.mail.port=587
spring.mail.properties.mail.smtp.port=587
spring.mail.properties.mail.transport.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.properties.mail.smtp.timeout=15000
spring.mail.properties.mail.smtp.connectiontimeout=15000
spring.mail.properties.mail.smtp.socketFactory.fallback=true
spring.mail.properties.mail.mail.debug=true

spring.config.import=sensitive.properties

Next add a spring.config.import statement to import sensitive.properties file, then provide the alternate file.

// sensitive.properties

spring.mail.username=my-user@mydomain.com
spring.mail.password=my-secure-password
prototype.o365.email.from=webmaster@mydomain.com
prototype.o365.email.to=destination-user@your-domain.com

Finally, to prevent sensitive.properties from finding its way to GitHub, be sure to update the .gitignore file to exclude it.

# .gitignore

### SENSITIVE PROPERTIES ###
sensitive*.properties

Send Email using Spring Boot

The final step is to craft and send your email. Use a SimpleMailMessage to send a plaintext email:

SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(emailTo);
msg.setFrom(emailFrom);
msg.setSubject("plain email at " + new Date().toString());
msg.setText("Hello World\n" + new Date().toString());

try
{
    javaMailSender.send(msg);
}
catch(MailException e)
{
    log.error("error sending plaintext email", e);
}

Use a MIME message to send HTML email content or include attachments:

MimeMessage msg = javaMailSender.createMimeMessage();
try
{
    MimeMessageHelper helper = 
        new MimeMessageHelper(msg, true);

    helper.setTo(emailTo);
    helper.setFrom(emailFrom);
    helper.setSubject("html email at " + new Date().toString());
    helper.setText("<h1>check attachment for the logo</h1>", true);

    helper.addAttachment("logo.png", 
        new ClassPathResource("logo.png"));
}
catch(MessagingException e)
{
    log.error("error preparing email", e);
}

try
{
    javaMailSender.send(msg);
}
catch(MailException e)
{
    log.error("error sending mime email", e);
}

Source Code

This article’s full source code is available on GitHub.

Sprint Boot Authentication with AzureAD Part 2

Spring Boot Authentication with Microsoft 365

In this second article of our series, we will start building a prototype that uses Spring Boot authentication to connect with Microsoft 365 Azure Active Directory (Azure AD). If you haven’t already completed part one of this series, please review that article now and create your Azure AD configuration.

Getting Started with Spring Initializr

In order to get the spring boot authentication prototype assembled quickly, first create an initial project structure using the Spring Initializr utility.

Spring Initializr, provided by the Pivotal, is a web application that will generate a Spring Boot project structure for you. Along with the structure, it provides a basic application class as well as either a Maven or a Gradle build script (we will use Gradle). The four primary Spring dependencies to import for our project include:

  • Azure Active Directory
  • OAUTH2 Client
  • Spring Web
  • Thymeleaf
Spring Initializr Settings
Spring Initializr Settings

Thymeleaf is a server-side Java templating engine for web applications. It has been around the block a few times, and does not have as much overhead as Angular so will keep our prototype example focused on authentication and easier to read.

Spring Initializr Project Structure

After making the dependency selections, click the “GENERATE” button to download the project file. As you can see from the snapshot below, Initializr has completed a fair amount of grunt work for our prototype.

Spring Boot Prototype Project Structure
Spring Boot Prototype Project Structure

Upgrading Versions in the Build Script

Spring Initializr choices can be a bit restrictive. At the time of this writing, the website only supports using version 2.5.8 while importing the Azure AD dependency. Selecting another version will give you the following error:

Spring Initializr Version Error for Azure AD
Spring Initializr Version Error for Azure AD

However, this is easily remedied by upgrading the versions in your build script after generating and downloading the project files.

Upgrade Spring Boot and Azure AD Versions
Upgrade Spring Boot and Azure AD Versions

We have upgraded both Spring Boot and Azure AD versions in the build.gradle script. Note that we have also upgraded the version of log4j to compensate for recent high profile vulnerabilities. Once Pivotal has upgraded the default log4j versions in Spring Boot, this log4j upgrade should no longer be necessary.

Sensitive Property Values

In part one of this series, we configured an Azure AD profile. During this step we created three values required for our prototype. These values should be treated as passwords. They should not be shared nor published to GitHub. Create the following file src/main/resources/sensitive.properties:

azure.activedirectory.tenant-id=your-azure-ad-tenant-id
azure.activedirectory.client-id=your-azure-ad--application-id
azure.activedirectory.client-secret=your-azure-ad-client-secret

Spring Boot Authentication Prototype

Our prototype is now stubbed out and ready for implementation. Part 3 of this series will focus on the code changes necessary to authenticate with Microsoft 365.

Spring Boot Authenticate With AzureAD

Spring Boot Authentication with Microsoft 365

In this first article of a multipart series, we will configure Microsoft 365 Azure Active Directory (Azure AD) to support building a web application that uses Spring Boot authentication. The official Microsoft documentation highlights key concepts for this process but rushes through several steps. In later articles we will build an example oauth2 authenticated application which uses this Azure AD configuration.

Spring Boot Authentication Overview

A number of steps are needed to build an oauth2 Spring Boot user authentication example using Azure AD. However, before we can begin coding we need an active Microsoft 365 Business subscription which is configured to support our web application. Once Microsoft 365 is configured, we can use properties obtained from the portal to bootstrap our Spring Boot starters for oauth2 and Azure AD.

What is Microsoft 365

Formerly known as Office 365, this monthly subscription from Microsoft is ubiquitous in the business world. Most customers purchase it for the core office applications and email, but it also includes an often overlooked feature. Most business subscription plans also include a license for a basic version of Azure AD, Microsoft’s LDAP Directory solution.

Prerequisites

For the purposes of this article, we’ll assume you have a typical small business setup. That means you already have a Microsoft 365 subscription, several user accounts, and have administrator access to the Microsoft portal.

Manage Azure AD

There are two primary ways to get to Azure AD via a web browser. You can either start at the top of the Microsoft portal and navigate your way through the maze, or just go directly to https://portal.azure.com. Once there, click on the button to view “Manage Azure Active Directory”

Manage Azure Active Directory
Manage Azure Active Directory

Register an Application in Azure AD

The first step in this configuration is to create a new application profile. Select “App Registrations” from the main menu in Azure AD and complete the form by adding a name, keeping the default options, and clicking the “Register” button.

Azure AD Register App
Azure AD Register App

The new application will be displayed with a number of system generated identifiers, as seen below.

Azure AD Application
Azure AD Application

These identifiers are sensitive, so treat them like passwords and keep them private. Two of these parameters will be needed for the Spring Boot authentication example application. Use the clipboard tooltip icon and make copies of the “Application (client) ID” and “Directory (tenant) ID” values and store them in a safe location for later.

Adding a Client Secret

Click the “New Client Secret” option from the “Certificates & Secrets” menu of your registered application.

Azure AD Add Client Secrets
Add Client Secrets

Add a “description” and select an “Expires” option from the form. Set the expiration length based on your company’s security policies and posture. Generally the shorter the expiry the better. But note that this value also greatly depends on your level of IT support staffing to determine how frequently the secret can be rotated and downstream applications updated.

Azure AD Client Secret Form
Add Client Secret Form

The generated client secret will contain several sensitive values that should be treated like passwords.

Azure AD Client Secret
Client Secret

Make a copy of the “Value” and store it in a safe location for later. You may also want to add the expiry date to an ops calendar so the rotation is not overlooked in the future.

Configure Platform Authentication

From the app registration, select the “Authentication” menu and then click “Add a platform“.

Azure AD Add Authentication Platform
Add Authentication Platform

Choose the “Web” option from the resulting “Configure platforms” form. Note that depending on your Microsoft 365 subscription level, you may see more platform options.

Azure AD Select Authentication Platform
Select Authentication Platform

Add a redirect URI to support local workstation development. You will need to choose a value that will not collide with any other routing within your system; The recommended default is seen below.

Azure AD Configure Authentication Platform
Configure Authentication Platform

The default “Redirect URI” can be copied below, and leave all other default values in place before clicking the “Configure” button.

http://localhost:8080/login/oauth2/code/

Create Application Roles

Now that we have the oauth2 routing configured for the application, we need to create application roles. An application’s roles will vary greatly depending on its purpose. For our example, we will only create an administrator (super user) role. In a real application, you most likely will have several roles supporting various types of functionality.

Select the “App roles” menu from the app registration, then click “Create app role“.

Azure AD Add Application Role
Add Application Role

Provide the form values then click “Apply“.

Azure AD Add Administrator Role
Add Administrator Role

There is some discretion on how you name the roles. For this example, set the value (used in the code) in all caps and the other values in proper case.

Assign Users and Groups

Select “Enterprise applications” from the Azure AD portal menu. Next select your application from the list of “All applications“. Finally, select “Users and groups” and click “Add user/group“.

Azure AD Assign Users
Assign Users

Select a user in your organization, then add a role and click “Assign“. If you created several roles earlier, lather rinse repeat on this process.

Azure AD Add Assignment
Add Assignment

Note that your Microsoft 365 subscription level will determine what assignments you can make; Basic subscriptions will only allow you to assign users directly (no group assignments).

Spring Boot User Authentication Example

This completes the basic setup for Azure AD. In the next article, we will use the Spring Boot Initialzr to start a new Java project using Gradle.

log4j vulnerabilities in spring boot

Spring Boot Updates for Log4J Vulnerabilities

Hackers continue to scan and exploit systems containing Log4J vulnerabilities at an unprecedented rate. On 10 December, the Spring Blog published detailed instructions for remediating Spring Boot applications using Maven or Gradle build scripts; Where this solution pattern is still accurate, the documented version is now out-of-date. Remember that even though the library may not be explicitly imported, it still might be present as a transitive dependency.

Latest Release for Log4J Vulnerabilities

The most secure version of Log4J is now version 2.17.1 (documented in our previous article). To force Spring Boot to import the most recent release of Log4J, include the following in your build scripts:

Maven

<properties>
    <log4j2.version>2.17.1</log4j2.version>
</properties>

Gradle

ext['log4j2.version'] = '2.17.1'

Log4J Vulnerability Update (2.17.1)

Several weeks out from the initial zero-day event, the IT world continues to work through the remediation and blowback from the Apache Log4J vulnerability. First published as CVE-2021-44228 (Log4Shell) on 9 December 2021, subsequent CVEs continue to be issued as quick turnaround patches fail to completely resolve the problem. The most recent version is now 2.17.1 (released 28 December) which repairs a newly discovered remote code execution (RCE) vulnerability in 2.17.0, tracked as CVE-2021-44832.

This family of vulnerabilities affects millions of computers, clouds, networks, and IoT devices ranging from the size of postage stamps to automobile chargers. It derives from the use of a ubiquitous piece of software, Log4J, which is mostly unknown to those outside of the IT industry. This open source code is used to generate files containing records of events that occur in software written in (or somehow leveraging) the Java programming language.

Hackers, in the form of independents or state actors, continue to scan the internet for vulnerabilities as IT teams race to resolve the problem. Once a vulnerable device is found, bad actors attempt to trigger a log message that includes a malicious payload which Log4J will process as a valid instruction. These exploits can open a reverse shell which allows the hacker to remotely control the targeted device.

As concerning as the exploit is itself, even more concerning is the pervasive use of Log4J leading this vulnerability to be described by the U.S. Cybersecurity & Infrastructure Security Agency (CISA) Director as one of the most serious she has seen in her career.

As of today, the remediation path involves upgrading impacted software to use the latest Log4J release, version 2.17.1 (note that versions of Log4J 1.x remain unaffected). The 2.17.1 release is available on the Apache site and has not yet migrated into the central repositories such as Maven Central.

CISA has published a response page which lists the history as well as recommended remediation paths for this exploit. Large vendors continue to release updates, including Amazon, IBM, and Google, but a significant concern also remains with smaller IT shops that do not have the workforce to quickly identify and push out updates.

If you have not already remediated systems that you are responsible for, it is long overdue that you do…

Powered by WordPress & Theme by Anders Norén