Saturday, March 16, 2019

DUKPT in JAVA using jPOS


Any encryption algorithm is only as secure as its keys.The strongest algorithm is useless if the keys used to encrypt the data with the algorithm are not secure.This is like locking your door with the biggest and strongest lock, but if you hid the key under the doormat, the lock itself is useless. When we talk about encryption, we also need to keep in mind that the data has to be decrypted at the other end.Typically, the weakest link in any encryption scheme is the sharing of the keys between the encrypting and decrypting parties. DUKPT is an attempt to ensure that both the parties can encrypt and decrypt data without having to pass the encryption/decryption keys around.

One of the most common E2EE solutions used by merchants is derived unique key per transaction (DUKPT) also known as “duck putt”.  DUKPT is commonly used in the convenience store and gas station industries to encrypt sensitive authentication data (SAD) from the gas pump to the merchant or processor.



DUKPT uses the 56-bit data encryption standard (DES) encryption or triple DES (3DES) algorithms.
While DES and 3DES 56-bit and 112-bit are no longer considered secure, because DUKPT uses a unique key for every transaction, it means that every transaction has to be individually broken to gain access to the data. While using the cloud could be leveraged to perform this rapidly, it would be too costly an effort for the data retrieved.  As a result, DUKPT using DES is still technically considered a secure method of encryption although it is never recommended for use.  3DES and AES are now the more commonly implemented algorithms with AES being the preferred solution if supported by the POI. 3DES encryption is a common algorithm implemented by well known libraries like BouncyCastle and Java JCE.

DUKPT is not itself an encryption standard; rather it is a key management technique. The features of the DUKPT scheme are:
  • Enable both originating and receiving parties to be in agreement as to the key being used for a given transaction,
  •  Each transaction will have a distinct key from all other transactions, except by coincidence,
  • If a present derived key is compromised, past and future keys (and thus the transactional data encrypted under them) remain uncompromised,
  • Each device generates a different key sequence,
  • Originators and receivers of encrypted messages do not have to perform an interactive key-agreement protocol beforehand.

Derived Key Generation Process



 The following procedure is used for device initialization and encryption.
  1. First: A key is irreversibly derived from the BDK (within a TRSM). This is known as the Initial PIN Encryption Key (IPEK).
  2. Second: The IPEK is then injected into the devices, so any compromise of that key compromises only the device, not the BDK
  3. Third: This IPEK creates yet another set of keys (inside the device) irreversibly derived from it (nominally called the Future Keys)
  4. Fourth: Afterwards the IPEK is then immediately discarded. (NOTE: This step contradicts "Session Keys" section where it indicates that only 21 "Future Keys" are generated.) The IPEK must be retained by the terminal in order generate the next batch of 21 Future Keys.
  5. Fifth: Future Keys are used to encrypt transactions in the DUKPT process.
Upon detection of compromise the device itself a new IPEK is derived inside the TRSM and the Derived Key Generation Process is restarted.



Keys used in DUKPT


BDK : Base Derivation Key: 32 hexadecimal character {0-9, A-F} key, which is randomly generated
KSN : Key Serial Number: 20 hexadecimal characters comprised of three unique parts: Key Set Identifier, Device Identification,and Transaction Counter
  • KSI : Key Set Identifier: First 10 characters of KSN, which serves as a BDK identifier in payment application systems
  • DID : Device Identification: Next 5 characters of KSN, which enables 524,287 individual POS devices to be injected with a single key
  • CTR : Transaction Counter: Last 5 characters of KSN, enabling 1, 048, 575 transactions to occur from each POS device
IPEK : Initial PIN Encryption Key: Cryptographically combining the BDK and KSN will yield the IPEK, which is the key actually injected into a POS terminal. This key is then utilized to derive future “Transaction Keys” – this same sequence can be used for PAN encryption utilizing an interoperable key exchange format
If BDK is compromised then all devices and all transactions are similarly compromised.Generally the security parameters in the devices are ‘distant’ from the sensitive BDK, and if the device is compromised, other devices are not implicitly compromised.

This is mitigated by the fact that there are only two parties that know the BDK:
  • The recipient of the encrypted messages (typically a merchant acquirer)
  • The party which initializes the encryption devices (typically the manufacturer of the device).
On the receiving side there is no state information retained; only the BDK is persistent across processing operations. The BDK is usually stored inside a Tamper-Resistant security module (TRSM), or Hardware Security Module (HSM).


What is DUKPT

 

  • Derived Unique Key Per Transaction (DUKPT) is a key management scheme. It uses one time encryption keys that are derived from a secret master key that is shared by the entity (or device) that encrypts and the entity (or device) that decrypts the data.
  • This technique involves the use of Base Derivation Key (BDK) and Key Serial Number (KSN).
    On each transaction, the PIN pad generates a new encryption keys that are derived from a secret BDK and a non-secret KSN. It encrypts the PIN with this key, and then forwards both the encrypted PIN and the key serial number to the acquirer.
  • The card reader utilizes DUKPT(derived unique key per transaction) scheme and 3DES encryption.The client device uses the IPEK to come up with a table of Future Keys and then discards the IPEK. So the client device now has it's original serial number, a counter (combined are the KSN) and a list of Future Keys.To encrypt the data, the client device grabs the first Future Key from the list and uses that as the encryption key. It then sends the encrypted data and it's KSN (which contains the counter) to the server.
  • On the server end, the server knows it's own secret (the BDK) and now has the clent device's KSN. The server uses those two keys to produce the IPEK .With the IPEK the server can recreate the table of Future Keys and knowing the counter provided by the client (the last 5 characters of the KSN) it knows which key from the table to use.
  • DUKPT allows the processing of the encryption to be moved away from the devices that hold the shared secret. The encryption is done with a derived key, which is not re-used after the transaction. 

 

How DUKPT Works

 

  • DUKPT uses one time keys that are generated for every transaction and then discarded.The advantage is that if one of these keys is compromised, only one transaction will be compromised.
  • With DUKPT, the originating (say, a Pin Entry Device or PED) and the receiving (processor, gateway, etc) parties share a key. This key is not actually used for encryption. Instead, another one time key that is derived from this master key is used for encrypting and decrypting the data. It is important to note that the master key should not be recoverable from the derived one time key.
  • To decrypt data, the receiving end has to know which master key was used to generate the one time key. This means that the receiving end has to store and keep track of a master key for each device.This can be a lot of work for someone that supports a lot of devices. A better way is required to deal with this.
  • This is how it works in real-life: The receiver has a master key called the Base Derivation Key (BDK). The BDK is supposed to be secret and will never be shared with anyone. This key is used to generate keys called the Initial Pin Encryption Key (IPEK). From this a set of keys called Future Keys is generated and the IPEK discarded.
  • Each of the Future keys is embedded into a PED by the device manufacturer, with whom these are shared. This additional derivation step means that the receiver does not have to keep track of each and every key that goes into the PEDs. They can be re-generated when required.
  • The receiver shares the Future keys with the PED manufacturer, who embeds one key into each PED.If one of these keys is compromised, the PED can be rekeyed with a new Future key that is derived from the BDK, since the BDK is still safe.

 Encryption and Decryption Process In DUKPT 

 

  • When data needs to be sent from the PED to the receiver, the Future key within that device is used to generate a one time key and then this key is used with an encryption algorithm to encrypt the data. This data is then sent to the receiver along with the Key Serial Number (KSN) which consists of the Device ID and the device transaction counter.
  • Based on the KSN, the receiver then generates the IPEK and from that generates the Future Key thatwas used by the device and then the actual key that was used to encrypt the data. With this key,the receiver will be able to decrypt the data.

Origination/Encryption

On the originating (encrypting) end, the system works as follows:
  • A transaction is initiated which involves data to be encrypted. The typical case is a customer's PIN.
  • A key is retrieved from the set of “Future Keys”
  • This is used to encrypt the message, creating a cryptogram.
  • An identifier known as the “Key Serial Number” (KSN) is returned from the encrypting device, along with the cryptogram. The KSN is formed from the device’s unique identifier, and an internal transaction counter.
  • The (cryptogram, KSN) pair is forwarded on to the intended recipient, typically the merchant acquirer, where it is decrypted and processed further.
  • Internally, the device does the following:
                a. Increments the transaction count (using an internal counter)
                b. Invalidates the key just used, and
                c. If necessary generates more future keys

Receiving/Decryption

On the receiving (decrypting) end, the system works as follows:
  • The (cryptogram, KSN) pair are received.
  • The appropriate BDK (if the system has more than one) is located.
  • The receiving system first regenerates the IPEK, and then goes through a process similar to that used on the originating system to arrive at the same encrypting key that was used (the session key). The Key Serial Number (KSN) provides the information needed to do this.
  • The cryptogram is decrypted with session key.
  • Any further processing is done. For merchant acquirers, this usually means encrypting under another key to forward on to a switch (doing a “translate”), but for certain closed-loop operations may involve directly processing the data, such as verifying the PIN.

DUKPT in Java Using jPOS :

  • Each Hardware Security Module (HSM) has its own Master Key and can be called an LMK or KSK  (Key Storage Key).
  • Every key you generate will be encrypted under this LMK. In real life you will never know the clear value of the LMK, the HSM will store it on a chip card. 
  • The JPOS API has very good support and can help you generate keys, encrypt, decrypt, form PIN blocks and translate PIN blocks

Java Dependency Libraries :

  • bcprov-jdk15on-1.58.jar
  • jpos-2.1.1.jar
  • commons-cli-1.4.jar
  • jdom2-2.0.6.jar
  • javatuples-1.2.jar

Step 1 : Start jPOS Command Line Interface .


Use --cli command line option that starts the jPOS command line interface .You  can start the command line interface in two ways :

1. By running Q2 using "--cli" as argument in java code
import org.jpos.q2.Q2;

public class Q2CommandLineInterface {
  public static void main(String[] args) {
    try { 
   Q2 q2 = new Q2(new String[] { "--cli" });
      q2.start();
    }catch (Exception localException) {}
  }
}

2. By calling bin/q2 --cli .
$ bin/q2 --cli
q2>

You should see a prompt like this



Step 2 : Generate LMK file using smconsole

$ q2> smconsole -lmk <lmk file path + lmk file name> -rebuildlmk
This will create the LMK file, on provided lmk file path



/tmp/dukpt-lmk

LMK0x01=7F3E2F01893DE50B7A3BBA34EFF80D317F3E2F01893DE50B
LMK0x00=F1FB3E37F176E683913B4F86385B4A01F1FB3E37F176E683
LMK0x09=5152DA52D5BF1A26D9F826E307973BB05152DA52D5BF1A26
LMK0x08=A1B6DAAEA78575D0D691893780F4DF91A1B6DAAEA78575D0
LMK0x0e=4AD3C4299162E3F12FF2BCCE97B00E7F4AD3C4299162E3F1
LMK0x07=DF132FFB32EF23DA67F8C229AD08BC38DF132FFB32EF23DA
LMK0x0d=F480F42349A23D0D6EC4D6018A76E975F480F42349A23D0D
LMK0x06=B3C2EAAE15D629E56DEA07F12CD9018FB3C2EAAE15D629E5
LMK0x0c=F89D45F270FEFE97B5E38558BC084F62F89D45F270FEFE97
LMK0x05=1A4AABA845EAF72A9102D362525710F11A4AABA845EAF72A
LMK0x0b=DC076BA7462CC746AD830885A1925D40DC076BA7462CC746
LMK0x04=61C15DFD2C700104F1B5981F38F4371A61C15DFD2C700104
LMK0x0a=6D5B525E4FA4944001AE13B986AE7AC76D5B525E4FA49440
LMK0x03=2CB0079E328C45FD9B584F6773083BC82CB0079E328C45FD
LMK0x02=C8DF2FEF08FDA126CB5D2C52FB8C1920C8DF2FEF08FDA126

Step 3 : Import the BDK using the 'smconsole' command that would encrypt it under the LMK. 


The Encrypted BDK will  be used at the time of Decryption and You will get encrypted bdk and the check value.
$ q2> smconsole –lmk <lmk _file_name> FK 128 BDK <BDK1> <BDK2> <BDK3>

Note 1:
If you have only one BDK ,  BDK2 and BDK3 are not available then fill it with Zeros(0).
Example : Original bdk 0123456789ABCDEFFEDCBA9876543210):
$ q2> smconsole –lmk <lmk _file_name> FK 128 BDK 0123456789ABCDEFFEDCBA9876543210 00000000000000000000000000000000 00000000000000000000000000000000

Note 2:
If you have two bdk,then run below command,
Example : Original bdk 0123456789ABCDEFFEDCBA9876543210 and 0123456789ABCDEFFEDCBA9876543210
$ q2> smconsole –lmk <lmk _file_name> FK 128 BDK 0123456789ABCDEFFEDCBA9876543210 0123456789ABCDEFFEDCBA9876543210 00000000000000000000000000000000


/tmp/dukpt-bdk
 
dukpt-bdk.key=26FB71EA0C9CBBA1D51CA00CFFA36374
dukpt-bdk.checkvalue=08D7B4
dukpt-bdk.length=128
dukpt-bdk.type=BDK
dukpt-bdk.class=org.jpos.security.SecureDESKey


 Step 4 : Swiped credit card using ID Tech card reader and decrypt the card data in java jPOS.



DukptAdapter.java
package com.java2depth.dukpt;

import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jpos.core.ConfigurationException;
import org.jpos.iso.ISOUtil;
import org.jpos.security.KeySerialNumber;
import org.jpos.security.SMException;
import org.jpos.security.SecureDESKey;
import org.jpos.security.SecureKeyStore;
import org.jpos.security.SecureKeyStore.SecureKeyStoreException;
import org.jpos.security.SimpleKeyFile;

public class DukptAdapter {
 
 SSM sm;
    SecureKeyStore ks;
    
   private void initSM () throws ConfigurationException, SMException {
    sm = new SSM("/tmp/dukpt-lmk","com.sun.crypto.provider.SunJCE");
    }
    
    private void initKS () throws Exception {
     
        ks = new SimpleKeyFile ("/tmp/dukpt-bdk");
    }
 
 private  SecureDESKey getBDK(String keyName) throws SecureKeyStoreException{
     SecureDESKey bdk = (SecureDESKey) ks.getKey (keyName);
     return bdk;
 }
 
 
    private KeySerialNumber getKSN(String ksn) throws Exception{
     if(ksn!=null && ksn.length()!=20)
      throw new Exception("Invalid KSN Size");
     String baseKeyID=ksn.substring(0, 10);
     String deviceID=ksn.substring(10, 15);
     String transacionCounter=ksn.substring(15, 20);
     KeySerialNumber ksnDecrypted = new KeySerialNumber(baseKeyID,deviceID,transacionCounter);
     return ksnDecrypted;
    }
    
    private  byte[] getDerivedKey(KeySerialNumber ksn,SecureDESKey bdk) throws SecureKeyStoreException, SMException{
     byte[] derivedKey = sm.calculateDerivedKey(ksn, bdk, true);
     return derivedKey;
 }
    
    private  byte[] decrypt(byte[] dataInByte, byte[] derivedKey)throws Exception {
  Security.addProvider(new BouncyCastleProvider());
  SecretKey keySpec = new SecretKeySpec(derivedKey, "DESede");
  Cipher decrypter = Cipher.getInstance("DESede/CBC/Nopadding", "BC"); //With out Padding
  //Cipher decrypter = Cipher.getInstance("DESede/CBC/PKCS5Padding", "BC"); //With Padding(PKCS5Padding)
  decrypter.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(new byte[8]));
  return decrypter.doFinal(dataInByte);
 }
    
    
    
    public static String decryptData(String encryptedData,String keySerialNumber) throws Exception {
     DukptAdapter adapter=new DukptAdapter();
     adapter.setUp();
  SecureDESKey bdk = (SecureDESKey) adapter.getBDK("dukpt-bdk");
  KeySerialNumber ksn=adapter.getKSN(keySerialNumber);
  byte[] derivedKey = adapter.getDerivedKey(ksn, bdk);
  byte[] decryptedData=adapter.decrypt(ISOUtil.hex2byte(encryptedData), derivedKey);
  return new String(decryptedData);
 }
    
    private  byte[] encrypt(String text, byte[] derivedKey)throws Exception {
  Security.addProvider(new BouncyCastleProvider());
  SecretKey keySpec = new SecretKeySpec(derivedKey, "DESede");
  Cipher decrypter = Cipher.getInstance("DESede/CBC/Nopadding", "BC"); //With out Padding
  //Cipher decrypter = Cipher.getInstance("DESede/CBC/PKCS5Padding", "BC"); //With Padding(PKCS5Padding)
  decrypter.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[8]));
  return decrypter.doFinal(text.getBytes());
 }
    
    
    public static String encryptData(String text,String keySerialNumber) throws Exception {
     DukptAdapter adapter=new DukptAdapter();
     adapter.setUp();
  SecureDESKey bdk = (SecureDESKey) adapter.getBDK("dukpt-bdk");
  KeySerialNumber ksn=adapter.getKSN(keySerialNumber);
  byte[] derivedKey = adapter.getDerivedKey(ksn, bdk);
  byte[] encryptedData=adapter.encrypt(text, derivedKey);
  return ISOUtil.hexString(encryptedData);
 }
    
    public static String decryptUnEncryptedData(String text) throws Exception {
  return new String(ISOUtil.hex2byte(text));
 }
    
    public void setUp() throws Exception {
        initSM ();
        initKS ();
    }
    
   public static void showKeyDetails(String keySerialNumber) throws Exception {
  System.out.println("::::::::::::::::::::::::::::::::::Key Details::::::::::::::::::::::::::::::::::::::::::");
  DukptAdapter adapter=new DukptAdapter();
  SimpleConfiguration bdkConfig = new SimpleConfiguration("/tmp/dukpt-bdk");
  SimpleConfiguration lmkConfig = new SimpleConfiguration("/tmp/dukpt-lmk");
  SecureKeyStore ks = new SimpleKeyFile ("/tmp/dukpt-bdk");
  SSM sm = new SSM("/tmp/dukpt-lmk","com.sun.crypto.provider.SunJCE");
  SecureDESKey bdk = (SecureDESKey) ks.getKey ("dukpt-bdk");
  KeySerialNumber ksn=adapter.getKSN(keySerialNumber);
  System.out.println("DUKPT Key Type  :"+bdkConfig.get("dukpt-bdk.type"));
  System.out.println("BDK Key         :"+bdkConfig.get("dukpt-bdk.key"));
  System.out.println("BDK check Value :"+bdkConfig.get("dukpt-bdk.checkvalue"));
  System.out.println("BDK Key Length  :"+bdkConfig.get("dukpt-bdk.length"));
  System.out.println("BDK Class       :"+bdkConfig.get("dukpt-bdk.class"));
  System.out.println("LMK Key         :"+lmkConfig.get("LMK0x09"));
  System.out.println("KSN             :"+keySerialNumber);
  System.out.println("Initial Key     :"+ISOUtil.hexString(sm.calculateInitialKey(ksn, bdk, true)));
  System.out.println("Derived Key     :"+ISOUtil.hexString(sm.calculateDerivedKey(ksn, bdk, true)));
  System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
 }
}



IdtechAdapter.java
package com.java2depth.dukpt;

/**
 * 
 Header//Compulsory Fixed Length(20 hexString,10 bytes length)
 UnEncryptedTrack1Data//Compulsory Variable length
 UnEncryptedTrack2Data//Compulsory Variable length
 EncryptedTrack1Data//Compulsory Variable length
 EncryptedTrack2Data//Compulsory Variable length
 UnUsedEncryptedData//Optional Variable length
 DeviceSN//Compulsory Fixed Length(20 hexString,10 bytes)
 KSN//Compulsory Fixed Length (20 hexString,10 bytes)
 Footer//Compulsory Fixed Length (6 hexString,3 bytes)
 *
 */

public class IdtechAdapter {

 private static int getUnEncryptedTrack1Length(String encryptedData){
  String header=encryptedData.substring(0, 20);
  String track1LengthInhex=header.substring(10, 12);
  int track1Len=getDecimalFromHex(track1LengthInhex);
  return track1Len*2;
 }
 
 private static int getUnEncryptedTrack2Length(String encryptedData){
  String header=encryptedData.substring(0, 20);
  String track2LengthInhex=header.substring(12, 14);
  int track2Len=getDecimalFromHex(track2LengthInhex);
  return track2Len*2;
 }
 
 private static int getDecimalFromHex(String hex){
  return Integer.parseInt(hex,16);
 }
 
 private static int getEncryptedTrack1Length(String encryptedData){
  int encryptTrack1Len=0;
  String header=encryptedData.substring(0, 20);
  String track1LengthInhex=header.substring(10, 12);
  int track1Len=getDecimalFromHex(track1LengthInhex);
  int track1Flag=track1Len%8;
  if(track1Flag!=0){
    encryptTrack1Len=track1Len+(8-track1Flag);
    encryptTrack1Len=encryptTrack1Len*2;
   }else{
    encryptTrack1Len=track1Len*2;
   }
  return encryptTrack1Len;
 }

 private static int getEncryptedTrack2Length(String encryptedData){
  int encryptTrack2Len=0;
  String header=encryptedData.substring(0, 20);
  String track2LengthInhex=header.substring(12, 14);
  int track2Len=getDecimalFromHex(track2LengthInhex);
  int track2Flag=track2Len%8;
  if(track2Flag!=0){
    encryptTrack2Len=track2Len+(8-track2Flag);
    encryptTrack2Len=encryptTrack2Len*2;
   }else{
    encryptTrack2Len=track2Len*2;
   }
  return encryptTrack2Len;
 }
 
 private static String getHeader(String encryptedData){
  return encryptedData.substring(0, 20);
 }
 
 
 private static String getUnEncryptedTrack1Data(String encryptedData){
  int unEncryptTrack1Length=getUnEncryptedTrack1Length(encryptedData);
  return encryptedData.substring(20, 20+unEncryptTrack1Length);
 }
 
 public static String getUnEncryptedTrack2Data(String encryptedData){
  int unEncryptTrack1Length=getUnEncryptedTrack1Length(encryptedData);
  int unEncryptTrack2Length=getUnEncryptedTrack2Length(encryptedData);
  return encryptedData.substring(20+unEncryptTrack1Length, 20+unEncryptTrack1Length+unEncryptTrack2Length);
 }
 public static String getEncryptedTrack1Data(String encryptedData){
  int unEncryptTrack1Length=getUnEncryptedTrack1Length(encryptedData);
  int unEncryptTrack2Length=getUnEncryptedTrack2Length(encryptedData);
  int encryptTrack1Length=getEncryptedTrack1Length(encryptedData);
  return encryptedData.substring(20+unEncryptTrack1Length+unEncryptTrack2Length, 20+unEncryptTrack1Length+unEncryptTrack2Length+encryptTrack1Length);
 }
 public static String getEncryptedTrack2Data(String encryptedData){
  int unEncryptTrack1Length=getUnEncryptedTrack1Length(encryptedData);
  int unEncryptTrack2Length=getUnEncryptedTrack2Length(encryptedData);
  int encryptTrack1Length=getEncryptedTrack1Length(encryptedData);
  int encryptTrack2Length=getEncryptedTrack2Length(encryptedData);
  return encryptedData.substring(20+unEncryptTrack1Length+unEncryptTrack2Length+encryptTrack1Length,20+unEncryptTrack1Length+unEncryptTrack2Length+encryptTrack1Length+encryptTrack2Length);
 }
 
 private static String getUnUsedEncryptedData(String encryptedData){
  int unEncryptTrack1Length=getUnEncryptedTrack1Length(encryptedData);
  int unEncryptTrack2Length=getUnEncryptedTrack2Length(encryptedData);
  int encryptTrack1Length=getEncryptedTrack1Length(encryptedData);
  int encryptTrack2Length=getEncryptedTrack2Length(encryptedData);
  return encryptedData.substring(20+unEncryptTrack1Length+unEncryptTrack2Length+encryptTrack1Length+encryptTrack2Length, encryptedData.length()-46);
 }
 
 private static String getDeviceID(String encryptedData){
  return encryptedData.substring(encryptedData.length()-46, encryptedData.length()-26);
 }
 
 public static String getKSN(String encryptedData){
  return encryptedData.substring(encryptedData.length()-26, encryptedData.length()-6);
 }
 
 private static String getFooter(String encryptedData){
  return encryptedData.substring(encryptedData.length()-6, encryptedData.length());
 }
 
 public static String decryptData(String encryptedData) throws Exception{
  String track1=DukptAdapter.decryptData(getEncryptedTrack1Data(encryptedData),getKSN(encryptedData));
  String track2=DukptAdapter.decryptData(getEncryptedTrack2Data(encryptedData),getKSN(encryptedData));
  System.out.println("::::::::::::::::::::::::::::::::::Decrypt The Encrypted Data::::::::::::::::::::::::::::::::::::::::::");
  System.out.println("Track 1 Data   :"+track1.trim());
  System.out.println("Track 2 Data   :"+track2.trim());
  System.out.println("Decrypted Data :"+track1.trim()+" "+track2.trim());
  System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
  return track1.trim()+" "+track2.trim();
 }
 
 public static String decryptUnEncryptedData(String text) throws Exception{
  System.out.println("::::::::::::::::::::::::::::::::::Decrypt The UnEncrypted Data::::::::::::::::::::::::::::::::::::::::::");
  String track1=DukptAdapter.decryptUnEncryptedData(getUnEncryptedTrack1Data(text));
  String track2=DukptAdapter.decryptUnEncryptedData(getUnEncryptedTrack2Data(text));
  System.out.println("Track 1 Data   :"+track1);
  System.out.println("Track 2 Data   :"+track2);
  System.out.println("Decrypted Data :"+track1.trim()+" "+track2.trim());
  System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
  return track1.trim()+" "+track2.trim();
 }
 
 public static String enryptData(String text,String ksn) throws Exception{
  if(text.length()%8!=0)
   throw new Exception("Text SIze is not Multiple Of 8, Size is "+text.length());
  String encryptedData=DukptAdapter.encryptData(text,ksn);
  return encryptedData;
 }
 
 public static void showRequestDetails(String encryptedData) throws Exception {
  System.out.println("::::::::::::::::::::::::::::::::::Request Details::::::::::::::::::::::::::::::::::::::::::");
  System.out.println("Original Request      :"+encryptedData);
  System.out.println("Header                :"+getHeader(encryptedData));//Compulsory Fixed Length(20 hexString,10 bytes length)
  System.out.println("UnEncryptedTrack1Data :"+getUnEncryptedTrack1Data(encryptedData));//Compulsory Variable length
  System.out.println("UnEncryptedTrack2Data :"+getUnEncryptedTrack2Data(encryptedData));//Compulsory Variable length
  System.out.println("EncryptedTrack1Data   :"+getEncryptedTrack1Data(encryptedData));//Compulsory Variable length
  System.out.println("EncryptedTrack2Data   :"+getEncryptedTrack2Data(encryptedData));//Compulsory Variable length
  System.out.println("UnUsedEncryptedData   :"+getUnUsedEncryptedData(encryptedData));//Optional Variable length
  System.out.println("DeviceSN              :"+getDeviceID(encryptedData));//Compulsory Fixed Length(20 hexString,10 bytes)
  System.out.println("KSN                   :"+getKSN(encryptedData));//Compulsory Fixed Length (20 hexString,10 bytes)
  System.out.println("Footer                :"+getFooter(encryptedData));//Compulsory Fixed Length (6 hexString,3 bytes)
  System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
  DukptAdapter.showKeyDetails(getKSN(encryptedData));
 }
}


DukptDecryption.java
package com.java2depth.dukpt;

import org.jpos.security.jceadapter.DukptAdapter;
import org.jpos.security.jceadapter.IdtechAdapter;

public class DukptDecryption {
 
 public static void main(String[] args) throws Exception { 
    String encryptedData="02D500801F3723008383252A353135302A2A2A2A2A2A2A2A373836315E504159504153532F4D4153544552434152445E2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2A3B353135302A2A2A2A2A2A2A2A373836313D2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2AA096A6F5D1DCBE45B5F77EB2559FEE0411013232E3F42044C0397E3E9E6D9B3A11FB8ADE0712AFD097C23AA86DFDC9DBA0E73A6FD698FD2F80800C0E1E9ED1BEED5EEA9840DA53F41254FDB79E89B76B127C25FE44AE7524BAEB5BDAACF777FA31323334353637383930FFFF9876543210E0004ABBF903";
    IdtechAdapter.showRequestDetails(encryptedData);
    IdtechAdapter.decryptUnEncryptedData(encryptedData);
    IdtechAdapter.decryptData(encryptedData);    
    String track1Data=DukptAdapter.decryptData(IdtechAdapter.getEncryptedTrack1Data(encryptedData),IdtechAdapter.getKSN(encryptedData));
    String track2Data=DukptAdapter.decryptData(IdtechAdapter.getEncryptedTrack2Data(encryptedData),IdtechAdapter.getKSN(encryptedData));
    String ksn=IdtechAdapter.getKSN(encryptedData);
    
    System.out.println("ksn: "+ksn);
    
    System.out.println("track1Data: "+track1Data);
    System.out.println("track1Data Length: "+track1Data.length());
    System.out.println("track1Data(Trim): "+track1Data.trim().length());
    System.out.println("Encrypted Track1Data: "+DukptAdapter.encryptData(track1Data,ksn));
    
    System.out.println("track2Data: "+track2Data);
    System.out.println("track2Data Length: "+track2Data.length());
    System.out.println("track2Data(Trim): "+track2Data.trim().length());
    System.out.println("Encrypted Track2Data: "+DukptAdapter.encryptData(track2Data,ksn));
    
    
  /*  
    String encryptedData = DukptAdapter.encryptData("123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678","62994948360000600237");
    System.out.println("Encrypted Track2Data: "+encryptedData);
    System.out.println("Encrypted Track2Data: "+DukptAdapter.decryptData(encryptedData,"62994948360000600237"));*/  
 }
}


Input : 
02D500801F3723008383252A353135302A2A2A2A2A2A2A2A373836315E504159504153532F4D4153544552434152445E2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2A3B353135302A2A2A2A2A2A2A2A373836313D2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2AA096A6F5D1DCBE45B5F77EB2559FEE0411013232E3F42044C0397E3E9E6D9B3A11FB8ADE0712AFD097C23AA86DFDC9DBA0E73A6FD698FD2F80800C0E1E9ED1BEED5EEA9840DA53F41254FDB79E89B76B127C25FE44AE7524BAEB5BDAACF777FA31323334353637383930FFFF9876543210E0004ABBF903

Output :
::::::::::::::::::::::::::::::::::Request Details::::::::::::::::::::::::::::::::::::::::::
Original Request      :02D500801F3723008383252A353135302A2A2A2A2A2A2A2A373836315E504159504153532F4D4153544552434152445E2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2A3B353135302A2A2A2A2A2A2A2A373836313D2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2AA096A6F5D1DCBE45B5F77EB2559FEE0411013232E3F42044C0397E3E9E6D9B3A11FB8ADE0712AFD097C23AA86DFDC9DBA0E73A6FD698FD2F80800C0E1E9ED1BEED5EEA9840DA53F41254FDB79E89B76B127C25FE44AE7524BAEB5BDAACF777FA31323334353637383930FFFF9876543210E0004ABBF903
Header                :02D500801F3723008383
UnEncryptedTrack1Data :252A353135302A2A2A2A2A2A2A2A373836315E504159504153532F4D4153544552434152445E2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2A
UnEncryptedTrack2Data :3B353135302A2A2A2A2A2A2A2A373836313D2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A3F2A
EncryptedTrack1Data   :A096A6F5D1DCBE45B5F77EB2559FEE0411013232E3F42044C0397E3E9E6D9B3A11FB8ADE0712AFD097C23AA86DFDC9DBA0E73A6FD698FD2F
EncryptedTrack2Data   :80800C0E1E9ED1BEED5EEA9840DA53F41254FDB79E89B76B127C25FE44AE7524BAEB5BDAACF777FA
UnUsedEncryptedData   :
DeviceSN              :31323334353637383930
KSN                      :FFFF9876543210E0004A
Footer                   :BBF903
::::::::::::::::::::::::::::::::::::Key Details::::::::::::::::::::::::::::::::::::::::::
DUKPT Key Type  :BDK
BDK Key                :26FB71EA0C9CBBA1D51CA00CFFA36374
BDK check Value   :08D7B4
BDK Key Length   :128
BDK Class              :org.jpos.security.SecureDESKey
LMK Key               :5152DA52D5BF1A26D9F826E307973BB05152DA52D5BF1A26
KSN                        :FFFF9876543210E0004A
Initial Key              :6AC292FAA1315B4D858AB3A3D7D5933A
Derived Key           :6220B23D0B06787F73C17FB6FD9590E0
::::::::::::::::::::::::::Decrypt The UnEncrypted Data::::::::::::::::::::::::::::::::::::::::::
Track 1 Data   :%*5150********7861^PAYPASS/MASTERCARD^***************?*
Track 2 Data   :;5150********7861=***************?*
Decrypted Data :%*5150********7861^PAYPASS/MASTERCARD^***************?* ;5150********7861=***************?*
::::::::::::::::::::::::::Decrypt The Encrypted Data::::::::::::::::::::::::::::::::::::::::::
Track 1 Data   :%B5150710200107861^PAYPASS/MASTERCARD^090910140000202?>
Track 2 Data   :;5150710200107861=090910140000202?1
Decrypted Data :%B5150710200107861^PAYPASS/MASTERCARD^090910140000202?> ;5150710200107861=090910140000202?1



Inform:

Friday, March 15, 2019

E2EE and P2PE in Payment Industry



Whenever you send private data to another computer or server on the Internet, which you do many times a day,Once you send the data packets of your voice call, chat, email or credit card number over the jungle of the Internet, you have no control over who lays their hands on them. This is the nature of the Internet.This is what makes so many things running on it free, including Voice over IP, which gives you free calls. Your data and voice packets pass through many unknown servers, routers, and devices where any hacker, big brother or rogue state agent can intercept them.

Today, end-to-end encryption is part of your daily digital life. It is actually the ultimate security mechanism that protects your sensitive and private data online, like your credit card number during a transaction, or your phone call which is being wiretapped.

The very first instant messaging and calling apps that came with end-to-end encryption like internet calling, VoIP and instant messaging apps like WhatsApp, Facebook Messenger.



End-to-End Encryption (E2EE) :

  • End-to-end encryption (E2EE) is a method of secure communication that prevents third-parties from accessing data while it's transferred from one end system or device to another.
  • In E2EE, the data is encrypted on the sender's system or device and only the recipient is able to decrypt it.
  • End-to-end encryption  is an implementation of asymmetric encryption.
  • As the name implies, end-to-end encryption protects data such that it can only be read on the two ends, by the sender, and by the recipient. No one else can read the encrypted data, including hackers, governments, Internet service provider, application service provider or tamper with it.and even the server through which the data is passing.


 WhatsApp Example :
  • Consider two WhatsApp users (Bob and Alice ) communicating through instant messaging or calling over the Internet. Their data passes through a WhatsApp Server while transiting from Bob to Alice
  • First Bob sends a message to Server and this message is saved at the Server and then sent to Alice. The main draw back of this method is  that, if a 3rd person or hacker who is interested in this message being sent from Bob to Alice tap in the communication line between Bob and Server and gets to know all the messages that is being sent from Bob to Server.
  • To avoid this, a most secure form of communication was introduced, where Bob first encrypts the message and then sent it to the Server. In this way if the hacker tries to hack the communication line between Bob and Server won't get to know the message that is being sent from Bob to Server and the message once its arrived at Server is decrypted and saves at Server and the message is again encrypted and sent to Alice.
  • In this way the message is transferred from Bob to Alice , but the main drawback of this method is if a person who is working at the Server gets to know the message being sent from Bob to Alice as the message is decrypted and saved at Server .Since the hacker can't tap the communication line between Bob and Server , know he can directly hack the Server and get to know the communication happening between Bob and Alice.
  • To avoid the drawback end to end encryption was introduced where the message is first encrypted by Bob and then send to Server, but here the message is not decrypted and saved at Server. Instead this message is  forwarded directly to Alice, with this message the main advantage is the hacker if he hack the communication line between Bob and Server , he won't get to know what message is being sent from Bob to Server and Also if he wants to hack the Server then he won't get to know what message is being sent from Bob to Alice. because the messages are not saved at Server and the person who is working on the Server won't get to know the what message is being sent since the messages are not decrypted and saved at Server.
Hence E2EE encryption eliminates all the drawback which existed in previous methods.With the introduction of E2EE encryption it does not mean that the system can't be hacked. the hacking is mainly done at the end devices where the communicating medium at the end devices such as mobile phones or bugs and the conversations are recorded and sent to hacker. so the main form of protection is protecting by the end devices.

End-to-end encryption (E2EE) in the payments processing chain (payments industry)


  • As E2EE is the generic terminology used by the IT industry to describe any solution that encrypts communications from one endpoint to another endpoint. Some businesses also use end-to-end encryption (E2EE) to protect credit card information. Examples of E2EE include IPSec, SSL and TLS. 
  • In E2EE  key management of the encryption can be done by any party that has an endpoint such as a merchant or a service provider.

Drawbacks of E2EE


  • While third party key management is typically acceptable for small merchants, this does not work for merchants that switch their own transactions to various processors as do mid-sized and large merchants.

Point-to-Point Encryption (P2PE) :

 

  • P2PE is a subset of E2EE .With P2PE, your customers’ credit card information is automatically encrypted whenever they swipe their plastic at the counter. That information remains encrypted when sent directly to your payment processor.Although this credit card data still travels over unsecured Wi-Fi and cellular networks, unauthorized parties are unable to decode the information. Only the payment processor has the encryption key on its end.
  • Point-to-point encryption (P2PE) is a standard established by the PCI Security Standards Council. Payment solutions that offer similar encryption but do not meet the P2Pe standard are referred to as end-to-end encryption (E2Ee) solutions.
  • It has been validated by a third party Quality Security Assessor and have been certified to the PCI P2PE standard.
  • Under the P2PE standard, only the transaction processor or other third party is allowed to perform key management. The merchant is never allowed to perform encryption key management under the P2PE standard.  As a result, DUKPT can be used by both P2PE and E2EE solutions.
  • Point to Point Encryption (P2PE) ensures that credit card data that must be collected and transmitted after a purchase is encrypted by a one time encryption key as soon as the card is swiped into the card reader. That key is destroyed immediately after a single use.

   

A True P2PE solution is determined with three main factors:

 

  • The solution uses a hardware-to-hardware encryption and decryption process along with a POI device that has SRED (Secure Reading and Exchange of Data) listed as a function.
  • The solution has been validated to the PCI P2Pe Standard which includes specific POI device requirements such as strict controls regarding shipping, receiving, tamper-evident packaging and installation.
  • A solution includes merchant education in the form of a P2PE Instruction Manual, which guides the merchant on POI device use, storage, return for repairs and regular PCI reporting.

 

P2PE Decryption Key Storage :

 

  • Key storage and decryption happens in an isolated Hardware Security Module (or HSM) that have been validated by PCI and/or FIPS 140-2 level at the payment gateway. SafeNet's HSMs are at the foundation of the only Point to Point Encryption solutions to be validated to date.
  • P2PE is a special case where encryption is applied within a retail point-of-sale (POS) terminal.If the P2PE process is implemented correctly, with account data being encrypted within an approved, secure cryptographic device (SCD), such as a POS terminal, and not decrypted at all within the merchant environment, there is potential for the merchant to be taken almost completely out of scope for PCI DSS.
  • For P2PE to work as intended, strict controls for protection of and access to decryption keys must be in place. The current guidance requires the use of hardware security modules (HSMs) with an appropriate security rating to protect access to those keys.From a PCI DSS perspective, any system that has the capacity to decrypt account data comes into scope immediately, so the ability to insulate merchants by protecting keys within HSMs can have significant benefits for all concerned.

Hardware-Based Encryption Devices (HSM and TPM): 


TPM and HSM are two types of hardware modules used for encryption. Trusted Platform Module (TPM) and a hardware security module (HSM) can be used for hardware encryption.


HSM : 

  • A hardware security module (HSM) is a security device you can add to a system to manage, generate, and securely store cryptographic keys.
  • High performance HSMs are external devices connected to a network using TCP/IP. Smaller HSMs come as expansion cards you install within a server, or as devices you plug into computer ports.
  • One of the noteworthy differences between the two is that HSMs are removable or external devices. In comparison, a TPM is a chip embedded into the motherboard. You can easily add an HSM to a system or a network, but if a system didn’t ship with a TPM, it’s not feasible to add one later. Both provide secure encryption capabilities by storing and using RSA keys.
  • Vendors : Thales, Gemalto, Utimaco, Ultra Electronics - CIS, Atalla, Futurex, and IBM.

TPM :

  • A Trusted Platform Module (TPM) is a hardware chip on the computer’s motherboard that stores cryptographic keys used for encryption. Many laptop computers include a TPM, but if the system doesn’t include it, it is not feasible to add one. Once enabled, the Trusted Platform Module provides full disk encryption capabilities. It becomes the "root of trust" for the system to provide integrity and authentication to the boot process. It keeps hard drives locked/sealed until the system completes a system verification, or authentication check.
  • The TPM includes a unique RSA key burned into it, which is used for asymmetric encryption. Additionally, it can generate, store, and protect other keys used in the encryption and decryption process.
  • Vendors : Microsoft,Infineon,Google,Atmel,Oracle ships ,PrivateCore vCage,VMware ESXi ,Taiwanese ,Xen ,KVM

  Drawbacks of P2PE
  • The huge downside to P2PE for merchants is that once you decide on a given P2PE solution, you are pretty much stuck with it and the processor providing it.  That is because most processors offering P2PE are only offering one P2PE solution.  As a result, if a better deal comes along for processing your transactions, you will likely have to replace your terminals and possibly other equipment to switch to the new processor. For some merchants, that could be a costly proposition and make any switch not worth the effort.

 

Objective of E2EE and P2PE 

 

  • When you relay credit card data to your payment processor through a terminal,that information is usually sent over an unsecured network. With the right tools, anyone can theoretically intercept this information and begin racking up fraudulent charges.
  • E2EE is a generic term that describes any solution that encrypts communications from one endpoint to another endpoint. This makes P2PE a subcategory of E2EE. Both are methods of encryption that process payment card data when transactions are made at a POS (point-of-sale) terminal, or POI (point of interaction).
  • End-to-End Encryption (E2EE) and Point-To-Point Encryption (P2PE), are the two main ways that payment card data is protected when a transaction is made at a Point-of-Sale (POS) terminal. 
  • The objective of P2Pe and E2Ee is to provide a payment security solution that instantaneously converts confidential payment card (credit and debit card) data and information into indecipherable code at the time the card is swiped to prevent hacking and fraud. It is designed to maximize the security of payment card transactions in an increasingly complex regulatory environment.

 

Difference between E2EE and P2PE

 

  • E2E systems are not validated by the PCI Council. They’re offered by banks or other third parties as a way to securely transmit card data.
  • In E2EE  key management of the encryption can be done by any party that has an endpoint such as a merchant or a service provider. However, under P2PE, the key management must be done by a processor or other third party, not the merchant.
  • With P2PE, the transmission link between merchants and payment processors is direct. By contrast,  E2EE often relies on indirect relays, which create more opportunities for data interception.
  • Anyone can technically set up an E2EE connection and manage the encryption keys in house,   but only payment processors are authorized to maintain these keys when using P2PE
  • While the two technologies are similar i,e both encryption technologies are secure, P2P provides an element of security and certainty that E2E is unable to match at this point. Hence P2PE offers much greater protection.

 

P2PE Solution Provider

 

  • The P2PE solution provider is a third-party entity (for example, a processor, acquirer, or payment gateway) that has overall responsibility for the design and implementation of a specific P2PE solution, and manages P2PE solutions for its merchant customers. The solution provider has overall responsibility for ensuring that all P2PE requirements are met, including any P2PE requirements performed by third-party organizations on behalf of the solution provider 
  • Both P2PE and E2EE solutions encrypt payment data at point-of-interaction with the payment type (Swipe/MSR, Dip/EMV, Tap/NFC).  From there, the data will be transported to the solution provider which, depending on the type of solution, will occur in a non-integrated, semi-integrated or fully-integrated fashion.
  • The solution provider, which is almost always a payment gateway or back-end processor, will decrypt the data for processing.  For payment gateways, the packet is decrypted, and then sent to the relevant processor for processing in an encrypted, clear-text fashion.
  • That being said, the connection to back-end processor, such as First Data or Elavon,is usually over a direct circuit or through a SSL/TLS-encrypted tunnel.

 PCI P2PE Requirements

 

  • Secure encryption of payment card data at the point of interaction (POI)
  • P2PE validated application(s) at the point of interaction
  • Secure management of encryption and decryption devices
  • Management of the decryption environment and all decrypted account data
  • Use of secure encryption methodologies and cryptographic key operations, including key generation, distribution, loading/injection, administration and usage

DUKPT (Derived Unique Key Per Transaction):

 

  • One of the most common E2EE solutions used by merchants is derived unique key per transaction (DUKPT) also known as “duck putt”.  DUKPT is commonly used in the convenience store and gas station industries to encrypt sensitive authentication data (SAD) from the gas pump to the merchant or processor. 
  • DUKPT uses the 56-bit data encryption standard (DES) encryption or triple DES (3DES) algorithms. While DES and 3DES 56-bit and 112-bit are no longer considered secure, because DUKPT uses a unique key for every transaction, it means that every transaction has to be individually broken to gain access to the data.

For more details about DUKPT , click on this link https://www.java2depth.com/2019/03/dukpt-in-java-using-jpos.html?spref=fb&m=1

Inform:

Tuesday, March 12, 2019

TCP SYN Flood Attack , IP and Packets Spoofing ( DDoS)

TCP SYN Flood Attack


A SYN flood (half-open attack) is a type of denial-of-service (DDoS) attack which aims to make a server unavailable to legitimate traffic by consuming all available server resources. By repeatedly sending initial connection request (SYN) packets, the attacker is able to overwhelm all available ports on a targeted server machine, causing the targeted device to respond to legitimate traffic sluggishly or not at all.



Forged packets - Packet injection


Packet injection (also known as forging packets or spoofing packets) in computer networking, is the process of interfering with an established network connection by means of constructing packets to appear as if they are part of the normal communication stream. The packet injection process allows an unknown third party to disrupt or intercept packets from the consenting parties that are communicating, which can lead to degradation or blockage of users' ability to utilize certain network services or protocols. Packet injection is commonly used in man-in-the-middle attacks and denial-of-service attacks. 

By utilizing raw sockets, NDIS function calls, or direct access to a network adapter kernel mode driver, arbitrary packets can be constructed and injected into a computer network. These arbitrary packets can be constructed from any type of packet protocol (ICMP, TCP, UDP, and others) since there is full control over the packet header while the packet is being assembled.



General procedure packet injection :
  • Create a raw socket
  • Create an Ethernet header in memory
  • Create an IP header in memory
  • Create a TCP header or UDP header in memory
  • Create the injected data in memory
  • Assemble (concatenate) the headers and data together to form an injection packet
  • Compute the correct IP and TCP or UDP packet checksums
  • Send the packet to the raw socket
Packet injection has been used for :
  • Disrupting certain services (file sharing or HTTP) by Internet service providers and wireless access points
  • Compromising wireless access points and circumventing their security
  • Exploiting certain functionality in online games
  • Determining the presence of internet censorship
  • Allows for custom packet designers to test their custom packets by directly placing them onto a computer network
  • Simulation of specific network traffic and scenarios
  • Testing of network firewalls and intrusion detection systems
  • Computer network auditing and troubleshooting computer network related issues 
Detecting packet injection :

Through the process of running a packet analyzer or packet sniffer on both network service access points trying to establish communication, the results can be compared. If point A has no record of sending certain packets that show up in the log at point B, and vice versa, then the packet log inconsistencies show that those packets have been forged and injected by an intermediary access point. Usually TCP resets are sent to both access points to disrupt communication

 IP spoofing

 

  • IP spoofing is the creation of Internet Protocol (IP) packets which have a modified source address in order to either hide the identity of the sender, to impersonate another computer system, or both. It is a technique often used by bad actors to invoke DDoS attacks against a target device or the surrounding infrastructure.
  • Sending and receiving IP packets is a primary way in which networked computers and other devices communicate, and constitutes the basis of the modern internet. All IP packets contain a header which precedes the body of the packet and contains important routing information, including the source address. In a normal packet, the source IP address is the address of the sender of the packet. If the packet has been spoofed, the source address will be forged.












  • IP Spoofing is analogous to an attacker sending a package to someone with the wrong return address listed. If the person receiving the package wants to stop the sender from sending packages, blocking all packages from the bogus address will do little good, as the return address is easily changed. Relatedly, if the receiver wants to respond to the return address, their response package will go somewhere other than to the real sender. The ability to spoof the addresses of packets is a core vulnerability exploited by many DDoS attacks.
  • DDoS attacks will often utilize spoofing with a goal of overwhelming a target with traffic while masking the identity of the malicious source, preventing mitigation efforts. If the source IP address is falsified and continuously randomized, blocking malicious requests becomes difficult. IP spoofing also makes it tough for law enforcement and cyber security teams to track down the perpetrator of the attack.
  • spoofing is also used to masquerade as another device so that responses are sent to that targeted device instead. Volumetric attacks such as NTP Amplification and DNS amplification make use of this vulnerability. The ability to modify the source IP is inherent to the design of TCP/IP, making it an ongoing security concern.
  • Tangential to DDoS attacks, spoofing can also be done with the aim of masquerading as another device in order to sidestep authentication and gain access to or “hijack” a user’s session.

Protect against IP spoofing (packet filtering)

  • While IP spoofing can’t be prevented, measures can be taken to stop spoofed packets from infiltrating a network. A very common defense against spoofing is ingress filtering, outlined in BCP38 (a Best Common Practice document). Ingress filtering is a form of packet filtering usually implemented on a network edge device which examines incoming IP packets and looks at their source headers. If the source headers on those packets don’t match their origin or they otherwise look fishy, the packets are rejected. Some networks will also implement egress filtering, which looks at IP packets exiting the network, ensuring that those packets have legitimate source headers to prevent someone within the network from launching an outbound malicious attack using IP spoofing. 

How does a SYN flood attack work?


SYN flood attacks work by exploiting the handshake process of a TCP connection. Under normal conditions, TCP connection exhibits three distinct processes in order to make a connection.
  • First, the client sends a SYN packet to the server in order to initiate the connection.
  • The server than responds to that initial packet with a SYN/ACK packet, in order to acknowledge the communication.
  • Finally, the client returns an ACK packet to acknowledge the receipt of the packet from the server. After completing this sequence of packet sending and receiving, the TCP connection is open and able to send and receive data.



















To create denial-of-service, an attacker exploits the fact that after an initial SYN packet has been received, the server will respond back with one or more SYN/ACK packets and wait for the final step in the handshake. Here’s how it works:
  • The attacker sends a high volume of SYN packets to the targeted server, often with spoofed IP addresses.
  • The server then responds to each one of the connection requests and leaves an open port ready to receive the response.
  • While the server waits for the final ACK packet, which never arrives, the attacker continues to send more SYN packets. The arrival of each new SYN packet causes the server to temporarily maintain a new open port connection for a certain length of time, and once all the available ports have been utilized the server is unable to function normally.

In networking, when a server is leaving a connection open but the machine on the other side of the connection is not, the connection is considered half-open. In this type of DDoS attack, the targeted server is continuously leaving open connections and waiting for each connection to timeout before the ports become available again. The result is that this type of attack can be considered a “half-open attack”.

A SYN flood can occur in three different ways:

  • Direct attack: A SYN flood where the IP address is not spoofed is known as a direct attack. In this attack, the attacker does not mask their IP address at all. As a result of the attacker using a single source device with a real IP address to create the attack, the attacker is highly vulnerable to discovery and mitigation. In order to create the half-open state on the targeted machine, the hacker prevents their machine from responding to the server’s SYN-ACK packets. This is often achieved by firewall rules that stop outgoing packets other than SYN packets or by filtering out any incoming SYN-ACK packets before they reach the malicious users machine. In practice this method is used rarely (if ever), as mitigation is fairly straightforward – just block the IP address of each malicious system. If the attacker is using a botnet such as the Mirai botnet they won’t care about masking the IP of the infected device.
  • Spoofed Attack: A malicious user can also spoof the IP address on each SYN packet they send in order to inhibit mitigation efforts and make their identity more difficult to discover. While the packets may be spoofed, those packets can potentially be traced back to their source. It’s difficult to do this sort of detective work but it’s not impossible, especially if Internet service providers (ISPs) are willing to help.
  • Distributed attack (DDoS): If an attack is created using a botnet the likelihood of tracking the attack back to its source is low. For an added level of obfuscation, an attacker may have each distributed device also spoof the IP addresses from which it sends packets. If the attacker is using a botnet such as the Mirai botnet, they generally won’t care about masking the IP of the infected device.
By using a SYN flood attack, a bad actor can attempt to create denial-of-service in a target device or service with substantially less traffic than other DDoS attacks. Instead of volumetric attacks, which aim to saturate the network infrastructure surrounding the target, SYN attacks only need to be larger than the available backlog in the target’s operating system. If the attacker is able to determine the size of the backlog and how long each connection will be left open before timing out, the attacker can target the exact parameters needed to disable the system, thereby reducing the total traffic to the minimum necessary amount to create denial-of-service.

Methods Of Mitigation SYN flood attack :

 

While modern operating systems are better equipped to manage resources, which makes it more difficult to overflow connection tables, servers are still vulnerable to SYN flood attacks.
There are a number of common techniques to mitigate SYN flood attacks, including:
  • Micro blocks : Administrators can allocate a micro-record (as few as 16 bytes) in the server memory for each incoming SYN request instead of a complete connection object.
  • SYN cookies : Using cryptographic hashing, the server sends its SYN-ACK response with a sequence number (seqno) that is constructed from the client IP address, port number, and possibly other unique identifying information. When the client responds, this hash is included in the ACK packet. The server verifies the ACK, and only then allocates memory for the connection.
  • RST cookies : For the first request from a given client, the server intentionally sends an invalid SYN-ACK. This should result in the client generating an RST packet, which tells the server something is wrong. If this is received, the server knows the request is legitimate, logs the client, and accepts subsequent incoming connections from it.
  • Stack tweaking : Administrators can tweak TCP stacks to mitigate the effect of SYN floods. This can either involve reducing the timeout until a stack frees memory allocated to a connection, or selectively dropping incoming connections.
  • Increasing Backlog queue : Each operating system on a targeted device has a certain number of half-open connections that it will allow. One response to high volumes of SYN packets is to increase the maximum number of possible half-open connections the operating system will allow. In order to successfully increase the maximum backlog, the system must reserve additional memory resources to deal with all the new requests. If the system does not have enough memory to be able to handle the increased backlog queue size, system performance will be negatively impacted, but that still may be better than denial-of-service.
  • Recycling the Oldest Half-Open TCP connection : Another mitigation strategy involves overwriting the oldest half-open connection once the backlog has been filled. This strategy requires that the legitimate connections can be fully established in less time than the backlog can be filled with malicious SYN packets. This particular defense fails when the attack volume is increased, or if the backlog size is too small to be practical.