Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, April 25, 2020

Spring Cloud Gateway - Mutual Authentication


Spring Cloud Gateway is described by the vendor as:
This project provides a library for building an API Gateway on top of Spring MVC. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.
The SCG default implementation for outbound connections is to use HTTP.   At the time of this blog post, documentation does not exist which shows an example of how to enable outbound HTTPS with mutual authentication.  This solution was made to fill that gap.

How to enable mutual authentication for a Spring Cloud Gateway instance: 

Monday, February 3, 2014

Oracle CLOBs with JDBC getString

In newer releases of Oracle, the preparedStatement.getString() is "overloaded" to allow you to pull back information directly from a CLOB field without using the special clob object.  Its generally good up to around 32KB;  In order to go larger, use the Java code below.

 String url   = “jdbc:oracle:thin:@localhost:1521:orcl”;  
 String user   = “scott”;  
 String password = “tiger”;

 Properties props = new Properties();  
 props.put(“user”, user );  
 props.put(“password”, password);  
 props.put(“SetBigStringTryClob”, “true”);

 DriverManager.registerDriver(new OracleDriver());  
 Connection conn = DriverManager.getConnection(url, props);  

Generally speaking, this should not be used too frequently.  In most instances, you'll want to stream the object properly, however, if the size of your strings are dancing on the edge of VARCHAR2 limits, you can get away with this workaround to simplify things.

Friday, January 31, 2014

Using AWS Role Credentials, Part III

The last remaining step in using AWS role credentials was to launch an EC2 instance using the role created in step 2, and deploy the test application built in step 1.  Launching the instance via the console is done in the usual manner, with the addition of one very important thing;  On step 3, be sure to apply the IAM role to your instance:


After the instance was launched, the test application was zipped and deployed to EC2 via:

 psftp ec2-user@ec2-w-y-x-z.compute-1.amazonaws.com -i mykeys.ppk  

Before running the application, the instance metadata was queried on the EC2 instance to validate that the role was applied and that temporary credentials were being generated:

 curl -L 169.254.169.254/latest/meta-data/iam/security-credentials/EC2-READ-S3  

which resulted in (partial snapshot):




Finally the test application was unzipped and run successfully:



As time allows I need to research the mechanism which generates the temporary credentials, and see how that affects code where objects are cached for an extended period of time (will the client always refresh the credentials before expiration via sdk, or must additional steps be taken to periodically refresh the credentials manually).

Sunday, January 26, 2014

Using AWS Role Credentials, Part I

Due to available tinkering time, this process will be documented in a series of smaller blog entries...

Amazon AWS provides for a mechanism within EC2 to automatically generate API credentials tied to IAM roles.  Basically, this is just a long-winded way to say that they've implemented something to replace embedded passwords (access key, secret key or AK/SK).

The first step in this process will be to generate a simple Java-based client which connects to S3 and lists the contents of a given bucket.  This application will initially use an AwsCredentials.properties file to test locally.  In Part II, we will remove the credentials file and deploy the application to a running EC2 instance using a role with S3 access to verify success.

The initial application file is listed below:

   
 package chris;  
   
 import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;  
 import com.amazonaws.regions.Region;  
 import com.amazonaws.regions.Regions;  
 import com.amazonaws.services.s3.AmazonS3;  
 import com.amazonaws.services.s3.AmazonS3Client;  
 import com.amazonaws.services.s3.model.ListObjectsRequest;  
 import com.amazonaws.services.s3.model.ObjectListing;  
 import com.amazonaws.services.s3.model.S3ObjectSummary;  
   
 public class Application  
 {  
   public void listObjects(AmazonS3 s3Client, String bucketName)  
   {  
       ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName);  
       ObjectListing objectListing = s3Client.listObjects(listObjectsRequest);  
       for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries())  
       {  
           System.out.println(objectSummary.getKey() + " (size: " + objectSummary.getSize() + ")");  
       }  
   }  
   
   public void run()  
   {  
       Region region = Region.getRegion(Regions.US_EAST_1);  
       String bucketName = "SPARETIMENOTEBOOK";  
       
       try  
       {  
           // USE THE FOLLOWING LOCALLY WITH AWSCREDENTIALS.PROPERTIES FILE PRESENT  
           AmazonS3Client s3Client = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());  
   
           // USE THE FOLLOWING ON PRODUCTION EC2 INSTANCE  
           // AmazonS3Client s3Client = new AmazonS3Client();  
   
           s3Client.setRegion(region);  
           listObjects(s3Client, bucketName);  
       }  
       catch (Exception e)  
       {  
           e.printStackTrace();  
       }  
   }  
     
   public static void main(String[] args)  
   {  
       Application app = new Application();  
       app.run();  
   }  
 }  

AwsCredentials.properties contains only the following:

    secretKey=MY_SECRET_KEY_GOES_HERE
    accessKey=MY_ACCESS_KEY_GOES_HERE

with the obvious inclusion of the actual key values...

After compilation, the class was observed running as expected and displays the contents of the given S3 bucket.  In the next part, I will create an EC2 role and deploy the application to a running instance to verify the code runs properly without the included credentials.

Sunday, September 8, 2013

Symmetric key encryption in Java using AES

Per Wikipedia, symmetric key encryption is defined as:  Symmetric-key algorithms are a class of algorithms for cryptography that use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext.

As with most things, everything you need to know about AES in Java can be found on Google, but scattered across a number of partial code snippets.  Below is a my attempt to consolidate that information into a single example application (JDK7) which takes a sentence and runs it back and forth through the encryption process.  In reality, you would be best served by not using "password" as a password, avoiding sequential byte sequences as your keys and/or initialization vectors, and removing passwords from your code. :)

   
 package chris;  
   
 import java.io.FileInputStream;  
 import java.security.Key;  
 import java.security.KeyStore;  
 import javax.crypto.Cipher;  
 import javax.crypto.spec.IvParameterSpec;  
 import javax.crypto.spec.SecretKeySpec;  
   
 /**  
  * JAVA AES EXAMPLE APPLICATION  
  *   
  * java cipher documentation:  
  * http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJSSEProvider  
  * http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#impl  
  *   
  * @author Chris  
  */  
 public class Application  
 {  
      public void aes(boolean useHardcodedKey) throws Exception  
      {  
           System.out.println("---- AES EXAMPLE ----");  
   
           System.out.println("original string: " + CLEARTEXT);  
           System.out.println("original length: " + CLEARTEXT.length());  
   
           // SELECT ALGORITHM  
             
           String algorithm = "AES/CBC/PKCS5Padding";  
                        // or "AES/CBC/ISO10126PADDING";  
             
           SecretKeySpec secretKey = null;  
             
           if(useHardcodedKey)  
           {  
                secretKey = new SecretKeySpec(RAW_KEY, "AES");  
           }  
           else  
           {  
                FileInputStream in = new FileInputStream(AES_KEYSTORE);  
                KeyStore keystore = KeyStore.getInstance("JCEKS");  
                keystore.load(in, PASSWORD);  
                Key key = keystore.getKey("mykey", PASSWORD);  
                secretKey = new SecretKeySpec(key.getEncoded(), "AES");  
           }  
             
           // INITIALIZATION VECTOR  
          
           byte[] ivBytes = new byte[]  
                     {0x00, 0x01, 0x02, 0x03,0x04, 0x05, 0x06, 0x07,   
                      0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};  
          
           IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);  
   
           // ENCRYPT  
          
           Cipher cipherENCRYPT = Cipher.getInstance(algorithm);  
           cipherENCRYPT.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);  
           byte[] crypted = cipherENCRYPT.doFinal(CLEARTEXT.getBytes());  
   
           // DECRYPT  
          
           Cipher cipherDECRYPT = Cipher.getInstance(algorithm);  
           cipherDECRYPT.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);  
           byte[] decrypted = cipherDECRYPT.doFinal(crypted);  
          
           // VERIFY  
          
           String compare = new String(decrypted, "UTF8");  
           System.out.println("decrypted string: " + compare);  
           System.out.println("decrypted length: " + compare.length());  
      }  
        
      public static void main(String[] args)  
      {  
           Application app = new Application();  
             
           try  
           {  
                app.aes(true);  
           }  
           catch(Exception e)  
           {  
                e.printStackTrace();  
           }  
      }  
        
      private static final String CLEARTEXT = "Here is a proprietary sentence to protect.";  
        
      // HARD-CODED AES SECRET KEY  
        
      private static final byte[] RAW_KEY = new byte[]  
                {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,  
                 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};  
   
      // KEYTOOL commands for generating an AES keystore  
      //  
      // keytool -genseckey -alias mykey -keyalg AES -keysize 128   
      //     -storepass password -storetype JCEKS -keystore aes.jks  
      // keytool -list -v -keystore keystore.jks -storetype JCEKS  
   
      private static final String AES_KEYSTORE = "c:\\temp\\aes.jks";  
      private static final char[] PASSWORD = "password".toCharArray();  
 }  
   

Thanks to codeformatter for providing the easy-to-use code formatting tool for use with blogger.

Wednesday, May 29, 2013

Automating Tomcat 7 Installation on EC2, Part II

Finalizing the work started in Automating Tomcat 7 Installation on EC2 the user data script was enhanced to modify the following two files:
  • /etc/tomcat7/server.xml
    • change instances of 8080 to 80
    • change instances of 8443 to 443
  • /etc/default/tomcat7
    • change #AUTHBIND no to AUTHBIND yes
And then start the tomcat7 service.  The final user data script is as follows:

#!/bin/bash
export DEBIAN_FRONTEND=noninteractive
sudo apt-get update -q -y
sudo apt-get install tomcat7 tomcat7-docs tomcat7-examples -q -y
sudo sed -i 's/port="8080"/port="80"/' /etc/tomcat7/server.xml
sudo sed -i 's/redirectPort="8443"/redirectPort="443"/' /etc/tomcat7/server.xml
sudo sed -i 's/#AUTHBIND=no/AUTHBIND=yes/' /etc/default/tomcat7
sudo service tomcat7 stop
sudo service tomcat7 start

After starting a new micro Ubuntu 12 instance while providing the script above (as well as using a security configuration which allows/opens port 80 for http traffic), the web server came online and started serving up pages without any further interaction (ie - turnkey tomcat server).




The script could be enhanced further by downloading/deploying a Java webapp (exploded folder or .war file) as needed.

Tuesday, May 28, 2013

Automating Tomcat 7 Installation on EC2

Extending work performed in the earlier post Running Tomcat 7 on EC2, I began the process to automate the creation of a Tomcat 7 application server.  The magic is performed on the "Advanced Instance Options" page (which also has an equivalent in the EC2 API world):


The "User Data" area allows for the creation of a "one time script" which will be run immediately after the server is provisioned and started for the first time.  For this case, the following was dumped into a text file and included on the configuration wizard page:

 #!/bin/bash
export DEBIAN_FRONTEND=noninteractive
sudo apt-get update -q -y
sudo apt-get install tomcat7 -q -y
sudo apt-get install tomcat7-docs -q -y
sudo apt-get install tomcat7-examples -q -y

Note that the "as file" option was used as opposed to "as text".  There really is no technical reason for doing things this way;  However, this implementation does provide for a script file which could be placed under configuration management control (svn/git/etc) outside of this process.

After completing the instance wizard and waiting for provisioning, an Ubuntu 12 server was successfully created with Tomcat 7 and associated docs and examples already installed.  All that remained was the port configuration steps and service startup:

sudo nano /etc/tomcat7/server.xml
change instances of 8080 to 80, and save file
sudo nano /etc/default/tomcat7
change #AUTHBIND no to AUTHBIND yes, and save file
sudo service tomcat7 stop
sudo service tomcat7 start


In a future post, I'll attempt to integrate these remaining items into the user data script.

Wednesday, May 8, 2013

Running Tomcat 7 on EC2

Installing Apache Tomcat 7 on a virtual machine within the Amazon EC2 cloud turned out to be a fairly trivial task. Using the micro instance created in a previous post, I issued the following commands on the Ubuntu command line to install the service:

sudo apt-get install update
sudo apt-get install tomcat7
sudo apt-get install tomcat7-docs
sudo apt-get install tomcat7-examples

In order to bind tomcat to listen on privileged port 80, the following steps were taken:

sudo nano /etc/tomcat7/server.xml
change instances of 8080 to 80, and save file
sudo nano /etc/default/tomcat7
change #AUTHBIND no to #AUTHBIND yes, and save file
sudo service tomcat7 stop
sudo service tomcat7 start

Finally, the Amazon EC2 security group was modified to allow access to port 80.  After these steps, bringing up a browser and accessing http://amazon-dynamic-server-name/docs successfully brought up the Tomcat 7 documentation.

I'm not sure why I was surprised, but I did discover that restarting an EC2 instance resulted in the instance obtaining a new DNS name and IP address.  The next time I work on a server, I need to remember to assign an Elastic IP address to the micro instance (in order to be able to save a PUTTY connection in my profile).

Friday, May 3, 2013

Creating an Environment Script for EC2 tools

With a basic understanding of Amazon EC2 under my belt, I continued with my workstation build-out by creating an environment script for the EC2 command line tools.  Nothing to Earth shattering here; the majority of time involved was mostly just researching variables that needed to be set.

@echo off
set EC2_HOME=C:\Users\chris\Dev\apps\ec2-api-tools-1-6-7-2
set EC2_PRIVATE_KEY=C:\Users\chris\Dev\bin\identity\pk-xxxx.pem
set EC2_CERT=C:\Users\chris\Dev\bin\identity\cert-xxxx.pem
REM default to avoid using --region parameter everywhere from command line
set EC2_URL=https://ec2.us-east-1.amazonaws.com
set PATH=.\;%EC2_HOME%\bin;%PATH%
echo ** ENVIRONMENT SET FOR AMAZON EC2 1.6.7.2

Java settings are not required because I have those covered in another script.  The script was entered, saved in my local dev\bin directory, and worked without issue.

Sunday, April 28, 2013

Downloading the Amazon EC2 Tools

We at Spare Time Notebook have been sleeping on this cloud thing for far too long; not ignoring it per se, just, well, not really needing it.  With the cost of hardware dropping through the floor as of late, its hard to let go of old habits (just buy another box) and embrace the new world.

Those lazy habits end today, as I delve into Amazon's EC2 offering.  I'll be documenting my progress/lessons learned as I go, and since time is tight, will be posting my education in pieces.

Today's effort is about as basic as possible - getting the tools loaded on my development workstation (who knows, maybe someday the math will work and my local workstation will be retired, and instead live in the cloud, only to be spawned when needed).  After a query to the friendly neighborhood google, I had an official link for Setting Up the Amazon EC2 Command Line Interface Tools.  This set of directions had a link to the latest download distribution (currently 1.6.7.2):



The download is fairly small (14meg), and was unzipped into my tools directory like any other java distribution:


I'll spend some time researching the task of building an appropriate command line environment and establishing proper credentials to the Amazon infrastructure and post again after I know what I should be doing.

Sunday, February 10, 2013

Interrupting a Thread in Java 7

In order to construct a well-behaved server class in Java, a few key pieces are required.  While researching this topic, I've discovered that there are n developers in the world working with Java concurrency and there are at least (n+1) opinions on the "proper way" to do this.   I've leveraged what seems to be the most common implementation guidelines and came up with the following example.

A few general notes:
  • there is much of anything in this example that is Java 7 specific, it just happens to be the version I'm using.
  • since this site is hosted on blogger, and there are not too many good/convenient options for presenting source code, I've just posted screen snapshots of the code.  My apologies for the laziness...

CONSOLE OUTPUT:

Jumping first to the summary, here is the program execution. You can see the server start, launch the worker thread, let it run for a short time, then signal the worker to stop.  All appears in order and working well.


APPLICATION CLASS:

Nothing too exciting to discuss here...  The main driver class to launch the example.


WORKER CLASS:

Here is the worker, a subclass of Thread.  This could be done by implementing a Runnable instead, but I find the Thread extension cleaner to read - mileage may vary based on personal preferences.  The worker does not perform any real work, but just dumps the message "worker thread performs work" to the console, then suspends.



SERVER CLASS:

Here is the implementation of the server (in order to keep the snapshot a bit cleaner, the shutdown method was extracted).  There are basic methods for startup and shutdown, as well as a simulate method which simulates work by for waiting for a short time.


SERVER SHUTDOWN METHOD:

This is the key to the whole process of stopping.  When the server shuts down, the worker thread needs to be asked to stop as well.  The server then waits for the worker to stop and then continues on with its own cleanup.  This method is really where implementations will tend to differ, based on what the worker thread is doing as well as the nature of the server itself.  You can use workerThread.join() to wait forever, but if the worker thread is hung, your server will never return.  This is one of those instances where you'll just need to apply best engineering judgement based on specifics to your application.


While researching Java concurrency, I did not find many full examples online; most tended to be snippets with too little, or full open source applications with too much.  I hope this example application finds a balance of both and is of use to someone else.

Friday, May 25, 2012

Convert Oracle Weblogic 11 to a Windows Service

In most instances, development application servers are installed to be started manually.  For those occasions when a development AdminServer needs to be converted to a Windows service, the following process can be used (unfortunately, the normal use of the Windows SC.EXE application is insufficient for WL).  Thanks to the original source at Weblogic Wonders.

To convert an administrative server, create a command file (.cmd) containing the following code (modified as needed), and then run the script, preferably using admin rights.

SETLOCAL
set DOMAIN_NAME=Wonders_Domain
set USERDOMAIN_HOME=c:\bea\user_projects\domains\mydomain
set SERVER_NAME=AdminServer
set WL_HOME=c:\bea\wlserver103
set WLS_USER=weblogic
set WLS_PW=weblogic
set PRODUCTION_MODE=true
set MEM_ARGS=-Xms1024m –Xmx1024m
call “%WL_HOME%\server\bin\installSvc.cmd”
ENDLOCAL

If the script ran to completion, there should be a new entry in the Control Panel | Administrative Tools | Services application to control your application server.