Tuesday, December 5, 2017

Security: JAAS,JCE,KERBEROS, NTLM, OUTH2, BASIC ,DIGEST,Spring Security :Outh2


Security is
  • Declarative Security
  • Programmatic Security
 KEY FEATURES
  1. Integrity

  2. Authentication

  3. Confidentiality

  4. Non-Repudiation 

  5. Authorization

1.Data Integrity: data as Sent Shall Be Received

2. Confidentiality: Only the Intended Receiver of Information Shall Be Able to Understand the Information

3. Authentication: Mechanism to Ensure, the Virtual Identity Claimed Shall Match With Actual Person

4. Authorization: Allowing User Access to Information According to His/her Role

5. Non-repudiation: the Sender/receiver Can Not Deny Their Signature on the Sent Document


APIS
  1. Data Integrity: Jce
  2. Confidentiality : ssl[basic | Digest | Self Signed| Cert- X09| Third Party 
  3. Authentication and Autherization : JAAS [ldap|db|kerberos|ntlm]
  4. Non-repudiation : Jce |digital Signatures
 Characteristics of application security.
  1. Authentication - Authentication is the means by which a user or client proves to a server that it is authorized to access a specific resource and vice-versa.
  2. Authorization - Authorization is the means by which a server determines if a user has permissions to access a specific resource or data.
  3. Data Integrity - Data integrity means that the data that is exchanged by a client and server is not modified by an unauthorized third party.
  4. Confidentiality or Data privacy - This ensures that information is send to only those users or clients that are authorized to access the data.
  5. Non-repudiation - This means that you can prove that a transaction or action has occurred. So a user who has performed a certain action, cannot deny doing so.

Security Mechanism

  1. Application-Layer Security - provided by the component containers
  2. Transport-Layer Security - Secure Sockets Layer (SSL)
  3. Message-Layer Security -Message-Layer security secures the SOAP messages that are exchanged between client and server using XML web services.
What are Realms, Users, Groups and Roles ?
  1. Realms [a field or domain of activity or interest.]- Realms are security domains or protection spaces setup for web or application servers. Each realm has its own authentication scheme and contains a collection of Users and Groups.
  2. Users - Users are individual or application entities defined in an identity store that access the application resources.
  3. Group - Groups are abstract entities defined in Java EE that contains a set of users having common traits.
  4. Roles - Roles are are abstract entities defined in Java EE that has permission
  5. to access a set of secured resources in an application.
  6. Users or Groups are mapped to Roles.






































JAAS 

  1. JAAS protects the system from users by allowing or denying access based upon who or what runs the program.
  2. javax.security.auth.callback.CallbackHandler interface. javax.security.auth.callback

 JAAS can simplify your Java security development by putting an abstraction layer between your application and disparate underlying authentication and authorization mechanisms.
This independence from platforms and algorithms allows you to use different security mechanisms without modifying your application-level code. As with most Java security APIs, JAAS achieves this implementation-independence through an extensible framework of pluggable service provider interfaces (SPIs): a set of abstract classes and interfaces to which specific implementations are developed. JAAS can perform both authentication and authorization. Using JAAS authentication from your application typically involves the following steps:

Steps to create
ü  Create a LoginContext
ü  Optionally pass a CallbackHandler to the LoginContext, for gathering or processing authentication data
ü  Perform authentication by calling the LoginContext's login() method
ü  Perform privileged actions using the returned Subject (assuming login succeeds)   Underneath the covers, a few other things occur:

During initialization,
ü  the LoginContext finds the configuration entry "MyExample" in a JAAS configuration file (which you configured) to determine which LoginModules to load (see Figure 2)[JAAS.CONF]
ü  During login, the LoginContext calls each LoginModule's login() method
ü  Each login() method performs the authentication or enlists a CallbackHandler
The CallbackHandler uses one or more Callbacks to interact with the user and gather input
A new Subject instance is populated with authentication details such as Principals and credentials

FLOW OF EXECUTION: Any class that implements javax.security.auth.callback.CallbackHandler interface. javax.security.auth.callback.

CallbackHandler has only one method which we can use to provide a password for a given identifier. These passwords may be retrieved from a database, from a protected configuration file or the password callback handler may even delegate this functionality to some other component within the application like a user manager component, where the user management functionality is centralized.







ü  Optionally pass a CallbackHandler to the LoginContext, for gathering or processing authentication data
ü  Perform authentication by calling the LoginContext's login() method
ü  Perform privileged actions using the returned Subject (assuming login succeeds)                                                                                                            Underneath the covers, a few other things occur:

During initialization,
ü  the LoginContext finds the configuration entry "MyExample" in a JAAS configuration file (which you configured) to determine which LoginModules to load (see Figure 2)[JAAS.CONF]
ü  During login, the LoginContext calls each LoginModule's login() method
ü  Each login() method performs the authentication or enlists a CallbackHandler
The CallbackHandler uses one or more Callbacks to interact with the user and gather input
--> A new Subject instance is populated with authentication details such as Principals and credentials

----------------------------------------------------------------------------------------------------------------------



















----------------------------------------------------------------------------------------------------------------------








----------------------------------------------------------------------------------------------------------------------



JCE

4.WHAT ARE TWO TYPE OF CRPTYOGRAPHIC ALGORITHMS ?
·       SYMMETRIC
·       ASYMMETRIC

5.WHAT IS CIPHER ?
A cipher (or cypher) is an algorithm for performing encryption or decryption. 

6.WHAT IS CIPHER TEXT ?
ciphertext or cyphertext is the result of encryption performed on plaintext using an algorithm,


7.WHAT IS CODE BOOK
A codebook contains a lookup table for coding and decoding; each word or phrase has one or more strings which replace it. To decipher messages written in code, corresponding copies of the codebook must be available at either end


8. WHAT ARE BLOCK CIPHERS?
Encryption algos that encrypts block of data of fixed size



9.WHAT ARE STREAM CIPHER ?
Which uses  encrypts ciphers inconsistent sizes

10. WHAT ARE initialization vectors ?
·       An initialization vector (IV) or starting variable (SV)[5] is a block of bits that is used by several modes to randomize the encryption and hence to produce distinct ciphertexts even if the same plaintext is encrypted multiple times, without the need for a slower re-keying process.[6]

·       An initialization vector has different security requirements than a key, so the IV usually does not need to be secret. However, in most cases, it is important that an initialization vector is never reused under the same key

·        






11.WHAT ARE SYMMETRIC ALGORITHMS?
ü  ONLY ONE KEY IS USED TO PRODUCE/COMSUME A CIPHER
ü  FASTER
ü  MAINTAINING SECRECY OF KEYS
SOME SYMMETRIC KEY ALGORITHMS
DES( Data-Encryption-Standard).. developed in 1970 and recommended by US government. Though it is not fool-proof, it is considered to be sufficiently safe and is in wide use. It has different modes of operation.
ü  Electronic Cook book ( ECB)
ü  Cipher Block Chaining ( CBC)
ü  Output Feedback Mode (OFB)
ü  Cipher Feedback Mode ( CFB)
TripleDES( also known as DESede). An improved and very safe method of DES.
IDEA:INTERNATIONAL DATA ENCRYPTION ALGORITHM
(International Data Encryption Algorithm). This is used in PGP ( Pretty-Good-Privacymethod of secure Email).
An important advantage of Secret-key algorithm is that a hardware-approach is possible. This results in very high speed encryption. The hardware implementation by a VLSI chip can be about 20 times faster than the corresponding software implementation!IDEA has been implemented in hardware.
Blowfish… This algorithm was designed by Bruce Schneier. It is not patented and he has placed the implementation in public domain.
Password-Based Encryption(PBE). We will have a brief description of this method , with code example, shortly. Ready-made implementations for many of these algorithms are available in SunJCA/JCE and the programmer just chooses the desired algorithm and uses it. No deep knowledge of the mathematical theory of the algorithms or how these algorithms are implemented ,is required .Such topics are highly mathematical and are dealt with inbooks on Cryptography .

9. WHAT ARE ASYMMETRIC ALGORITHMS/PUBLIC KEY ALGORITHMS?
This algorithm is also known as ‘Public Key’ algorithm. There are two keys in this scheme. One key is known as ‘public key’ and the other key is known as ‘private key’.(It should be noted that ‘secret key’ does not mean ‘private key’.)

The basic theory of Public key Cryptography was developed by two research workers at StanfordUniversity Diffie&Hellman in 1976. The DH algorithm is known as Key-Agreement method. RSA algorithm is an implementation , named after the initials of the three academics who invented it. ( Rivest,Shamir & Adleman).RSA is the defacto standard.Another Asymmetric algorithm isDSA

( Digital Signature Algorithm). Yet another algorithm is known as ECC(Elliptic-Curve Cryptography). It is reputed to be very efficient and fast.[ However, SunJCA/JCE does not provide ready-made implementation for ECC.]

The public key and private key are known as ‘keypair’.The public key and private key are mathematically related in the sense that if a message is encrypted by using a particular public key, it can be decrypted by the corresponding private key and vice-versa(ie) the data can
also be encrypted by using a private key and can be decrypted by the corresponding public key, and not by any other public key. But
the problem is that any person who knows Sam’s public key can decrypt the message. So, RSA system uses public key of the recipient to encrypt the data.( But, the private key cannot be derived from public key. Similarly, the public key cannot be derived from private key).

RSA method is the most widely used scheme. When Sam wants to send a secret message to Tom, he should know the public key of Tom to begin with.( Just as we should know the mail-id of our friend first, if we want to send email to him). Samencrypts the message by using Tom’spublic keyand sends it to Tom.At the receiving end, Tom uses his (Tom’s)private key and decrypts the letter and reads it.The advantage of this scheme is that it ensures that only Tom will be able to read the message, as only his private-key can decrypt the message encrypted with his public key.A person’s private key need never be known to anyone else and there is no sharing the key with another person.Only the public key needs to be informed to others. ( like the difference in sharing our mail-id and sharing our password!).Thus key-administration problem is less.


12.WHAT ARE DIGITAL SIGNATURES?
The Asymmetric system has another use as well. It can be used for creating the Digital Signature, to ensure that the message came from Sam.Though the message itself can be signed without creating a digest, the usual method is to sign the messagedigest,so that Integrity of
data also can be ensured.

13.HOW IS NON REPUDIATION ENSURED?
THROUGH DIGITAL SIGNATURES

14.WHAT ARE MESSAGE DIGEST?
A ‘Message Digest’ isa digital fingerprint.It isoften referred to simply as a digest ( summary) or hash. It is an one-way process ( ie) it is impossible to reconstruct the original from the hash

15.WHAT ARE MESSAGE DIGESTING ALGORITHMS ?
WHICH PRODUCES MESSAGE DIGESTS
ü  MD5
ü  SHA-1

TO SECURE A MESSAGE YOU NEED TO PASS IT THROUGH


Using the same oneway hash algorithm on the text message, Tom creates another hash(hash2).If hash2exactly matches hash1, it means that the data has not been altered in transit. Thus, we get assurance of Confidentiality and Data Integrity. It also ensures the identity of the sender, because the the hash1 was obtained by using the public key of Sam to decrypt the package.


16.WHAT ARE DIGITAL CERTIFICATES ?
Just now , we saw that Tommade use of Sam’s public key to verify his Digital Signature. How does Tom getto know the public key of Sam?Sam could have published his public key in the internet or could have sent it to Tom, personally. A person’s public key can be freely published and shared and for this reason, anybody can use it , not necessarily Sam. A Digital signature of Sam can be verified only if Sam’s public key is available to Tombut as it is a public key, impersonation is possible. A trusted third-party is required to certify that the said key is really Sam’s public key.This is known as Digital Certificate and the authorities who issue such certifictes are Certifying Authority.


17. WHAT ARE Public Key Infrastructure( PKI)?
When Sam wants his public key to be certified by a CA, he generates a keypair and sends the public key to an appropriate CA with some proof of his identification. The CA checks the identification and then after satisfying that the key has not been modified in transit, issues a certificate relating the public key of Sam with his identity,by signing the public key of Sam with the private key of the CA. The standard format of issuing the certificate is known as X509.

Who is to attest the CA themselves? The CA are self-attested.

The PKI standard has been developed by RSA Security Systems in collaboration with Industry leaders like SUN, IBM and Microsoft and is the industry standard.

18. WHAT IS CERTIFICATE REVOCATION?
A certificate becomes invalid after the expiry of validation period. Sometimes, the private key associated with a public key gets compromised (ie) exposed, and in that case also, the cerificate should be withdrawn( revoked).The owner of the privatekey also may like to change it.The CA publishes a list of such defunct certificates and Tom should verify that Sam’scertificate is still valid, before important transactions.




19. WHAT IS MAC ? MESSAGE AUTHTICATION CODE/SECRET KEY ALGORITHM ?
Digital Signature makes use of Sam’s private key to sign the hash. An alternative to Digital Signature is to use a secret key to encrypt the hash. By its very definition, secret key is common to both Sam & Tom. So Tom can use the secret key at his end and get back the hash.
The code thus generated by mixing the hash and the secret key is known as MAC. Digital Signature is better than MAC because it does not need any ‘secret’ key. In the context of E-Commerce, where there are thousands of parties , secret key administration is always very difficult.

The scheme outlined above is suitable for most purposes. However, for very large amounts of data, encryption and decryption of databy public-key systems becomestime consuming and requires large resources.

In such cases, it is preferred to use Symmetric Encryption systems with some modifications. Hybrid Systems make use ofAsymmetric method for agreeing upon a secret key and the actual encryption and decryption of data is done by this secretkey.Some such methodis the usual Industrial practice. The Secret keyused here is valid only for a particular instance of transmission of message and so is usually called ‘session-key’. ( This is not the ‘session’ as usually understood in servlets, because this is an one-time operation).



20.WHAT IS DIGITAL ENVOLPE ?
An illustration of Hybrid method is a Digital Envelope. In this scheme, Sam encrypts the message by a random Secret key, ( known as DEK i.e.Data-Encryption-keyor session key).Next Sam encrypts this session key with Tom’s public key. At this stage, Sam sends both the encrypted message and the encrypted session key to Tom.

At the receiving end, Tom uses his private key to get the session key. Using this session key, Tom decrypts the message.As Symmetric method is about 1000 times faster thanAsymmetric method , this is a good combination. Though public key method also has been used here, it is only for encrypting the session key and not the message.This can be further improved by creating a hash of the message and sigining it. Also, there is no permanent Secret key betweenSam & Tom,and the required secret key is produced just as required and then discarded after the job. Thus, the method is fast and secure.

With this background information, let us now see some simple code examples,specific to JDK.

There are a number ofCryptographic Engines in SunJCA & SunJCE. They are listed below. It will be immediately evident that the names will beGreek & Latin to us , unless we have a background in Crypto terminology. That is why, a broad outline was given. The function of some of the engines will be evident from the earlier discussion. A few more of the remaining items will be clear when we deal with code examples.

21.WHAT ARE CRYPTOGRAPHIC ENGINES ?
1.    KeyGenerator( symmetric) (Blowfish, DES,TripleDES,HmacMD5, HmacSHA1,RC5)
2.    KeyPairGenerator( asymmetric) (DiffieHellman, DSA, RSA)
3.    Mac ( message authentication code) HmacMD5, HmacSHA1)
4.    MessageDigest (MD5,SHA1)
5.    Signature (MD5withRSA, SHA1withRSA, SHA1withDSA)
6.    Cipher ( Blowfish, DES, TripleDES etc)
7.    CertificateFactory ( X509)
8.    KeyAgreement( DiffieHellman)
9.    KeyFactory
10. SecretKeyFactory
11. SecureRandom ( SHA1PRNG) (ie) ( SHA1 ..pseudo-random-number-generator)
12. TrustManagerFactory
13. KeyManagerFactory
14. KeySore ( JKS, PHCS12)
15. SSLContext
16. AlgorithmParameterGenerator
17. AlgorithmParameters



import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESedeKeySpec;

import javax.crypto.spec.IvParameterSpec;



import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;




/**

          * encrypts the source data

          *

          * @param keyToEncrypt

          * @param sourceTextData

          * @return

          */

public static String encrypt(String keyToEncrypt, String sourceTextData) {

                  String encryptedData = null;
                  if (sourceTextData != null) {



try {

Security.addProvider(new com.sun.crypto.provider.SunJCE());
// Create an array to hold the key
byte[] byteKeyToEncrypt = null;
if (keyToEncrypt != null) {
                   byteKeyToEncrypt = keyToEncrypt.getBytes(ASCII);
          } else {
// handle with defaultKey
byteKeyToEncrypt = DEFAULT_MAGMA_ENCRYPTED_KEY.getBytes(ASCII);

                                    }



                                    // Create a DESede key spec from the key

                                    DESedeKeySpec spec = new DESedeKeySpec(byteKeyToEncrypt);



                                    // Get the secret key factor for generating DESede keys

                                    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_KEY_DESEDE);



                                    // Generate a DESede SecretKey object

                                    SecretKey theKey = keyFactory.generateSecret(spec);



                                    // Create a DESede Cipher

                                    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, CIPHER_KEY_PROVIDER);



                                    // Initialize the cipher and put it into encrypt mode

                                    cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);



                                    byte[] bytePlainText = sourceTextData.getBytes(ASCII);



                                    // Encrypt the data

                                    byte[] encryptedBytes = cipher.doFinal(bytePlainText);



                                    if (encryptedBytes != null) {

                                             BASE64Encoder base64Encoder = new BASE64Encoder();

                                             encryptedData = base64Encoder.encode(encryptedBytes);

                                    }



                           } catch (Exception e) {

                                    throw new EHRuntimeException(e);

                           }

                  }

                  return encryptedData;

         }







A cipher (or cypher) is an algorithm for performing encryption or decryption.  A codebook contains a lookup table for coding and decoding; each word or phrase has one or more strings which replace it. To decipher messages written in code, corresponding copies of the codebook must be available at either end.Symmetric key algorithms (Private-key cryptography), where the same key is used for encryption and decryption, and
Asymmetric key algorithms (Public-key cryptography), where two different keys are used for encryption and decryption. Block ciphers, which encrypt block of data of fixed size, and Stream ciphers, which encrypt continuous streams of data.ciphertext or cyphertext is the result of encryption performed on plaintext using an algorithm, An initialization vector (IV) or starting variable (SV)[5] is a block of bits that is used by several modes to randomize the encryption and hence to produce distinct ciphertexts even if the same plaintext is encrypted multiple times, without the need for a slower re-keying process.[6]

An initialization vector has different security requirements than a key, so the IV usually does not need to be secret. However, in most cases, it is important that an initialization vector is never reused under the same key. A block cipher works on units of a fixed size (known as a block size), but messages come in a variety of lengths. So some modes (namely ECB and CBC) require that the final block be padded before encryption.The simplest is to add null bytes to the plaintext to bring its length up to a multiple of the block size.The purpose of cipher modes is to mask patterns which exist in encrypted data.
-->











Security: Outh2

No comments:

Post a Comment