# Gossips on Cryptography – Part 1

In this blog series , We will learn about encryption and decryption basics  in a very casual fashion . We will start discussing from origin of cryptography and then learns about the modern techniques

One of the important and main tech in encryption is Cryptography

Cryptography is a tech which is very very common and which is used in everywhere right now weather any software as follows :

• Routers we use in our homes
• Whatsapp we use to send receive messages
• Any site we are opening on https
• ……. And so on ..

Now , At the same time cryptography is very common , it is extremely complex also . Complex in understanding , implementing and even using it correctly .

Need of Cryptography:

• Why we need password on our phone
• Why to lock the door of our home when going outside and take keys with ourselves

Same is answer to use cryptography – To assures that the sender or receiver is the right one and they can only see the right form of data

To understand how it works let’s start from old age method known as : Caesar Cipher

Caesar Cipher

The Caesar Cipher is a type of substitution cipher in which each letter in a plaintext is shifted a certain number of places down the alphabet. This simple encryption technique is named after Julius Caesar, who used it to encrypt messages sent to his officials. The process of encryption is simple, a shift value ( also known as key) is chosen and each letter of the plaintext is shifted by that number of positions down the alphabet.

For example, with a shift of 3, A would be replaced by D, B would be replaced by E, and so on.

Plaintext: Sahil

Shift(Key): 3

Ciphertext: Vdklo

To decrypt the message, the shift value is used in the opposite direction.

Ciphertext: Vdklo

Shift(Key): -3

Plaintext: Sahil

It is important to note that the Caesar Cipher is very easy to break and should not be used for any serious encryption purposes as it can be broken by simple methods such as frequency analysis.

Here Algorithm is Simple: shift a letter N number of times and then replace it with that letter and Continue this process till our plain text will be Converted into cipher text .

A Caesar Cipher table is a tool that can be used to manually encrypt and decrypt messages using the Caesar Cipher method. It is a table that lists all of the letters of the alphabet and their corresponding encrypted or decrypted letters, based on a chosen shift value (or key).

Here is an example of a Caesar Cipher table with a shift(Key) value of 3:

And so on …

With Caesar cipher, someone can easily reverse engineer this Caesar cipher text and  decode the messages encrypted using this algorithm by identifying the pattern , one can easily determine the key .  This was just an example to get the readers familiar with the cryptography and encryption decryption concepts .

Till Now we have heard about some important terms

• Cryptography
• Algorithm
• Plain Text
• Key
• Cipher Text

Please keep them in mind as these are the generic terms used everywhere in world of encryption and decryption  .

In next Blog we will gossip about some other things like

• Making strong Algo as compare to caesar cipher
• What is latest Algo used now a days
• What type of Cryptography Techniques are present and when one should be used
• and so on …

Stay tuned for next part …

# Introduction

The new Content-Security-Policy HTTP response header helps you reduce XSS risks on modern browsers by declaring, which dynamic resources are allowed to load.

The core functionality of CSP can be divided into three areas:

• Requiring that all scripts are safe and trusted by the application owner (ideally by making sure they match an unpredictable identifier specified in the policy called the CSP nonce),
• Ensuring that page resources, such as images, stylesheets, or frames, are loaded from trusted sources,
• Miscellaneous other security features: preventing the application from being framed by untrusted domains(frame-ancestors), transparently upgrading all resource requests to HTTPS, and others.

Now the major concerns here are as follows :

• What should be the value of csp header to provide utmost security
• What should be the value of csp header so that it will be applicable by all vapt vendors and also no major change required if my application is old .
• What all things need to take care while deciding the header value  , How Strict the header value should be  .
• How to write code (if someone is making a new application) so that it remains CSP Standards compatible .

In this Blog all the above doubts will be cleared .

# Example of a Strict Value of Header which can be applied at Production Setups :

``````Content-Security-Policy:
object-src 'none';
script-src 'nonce-{random}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:;
base-uri 'none';
frame-ancestors https://example.com``````

Let’s look at the properties of this policy as interpreted by a modern browser:

• object-src ‘none’ Prevents fetching and executing plugin resources embedded using <object>, <embed> or <applet> tags. The most common example is Flash.
• script-src nonce-{random} ‘unsafe-inline’ The nonce directive means that <script> elements will be allowed to execute only if they contain a nonce attribute matching the randomly-generated value which appears in the policy.
Note: In the presence of a CSP nonce the unsafe-inline directive will be ignored by modern browsers. Older browsers, which don’t support nonces, will see unsafe-inline and allow inline scripts to execute.
• script-src ‘strict-dynamic’ https: http: ‘strict-dynamic’ allows the execution of scripts dynamically added to the page, as long as they were loaded by a safe, already-trusted script (see the specification).
Note: In the presence of ‘strict-dynamic’ the https: and http: whitelist entries will be ignored by modern browsers. Older browsers will allow the loading of scripts from any URL.
• ‘unsafe-eval’ allows the application to use the eval() JavaScript function. This reduces the protection against certain types of DOM-based XSS bugs, but makes it easier to adopt CSP. If your application doesn’t use eval(), you can remove this keyword and have a safer policy.
• base-uri ‘none’ Disables <base> URIs, preventing attackers from changing the locations of scripts loaded from relative URLs. If your application uses <base> tags, base-uri ‘self’ is usually also safe.
• frame-ancestors https://example.com  – This means that your application page can be opened in iframe of application page served by example.com only .

Now , if you have decided some CSP header value and want to check if it is ok to use or not ,

You can check  at the following link : CSP Evaluator

I hope First two concerns listed above are cleared and now moving to next one

# Not only setting the correct value makes your application safe , we need to make some changes to client side code also to make the application CSP compatible   .

## Code Changes

### Random Nonce in Code

• Above we talk about the  random nonce which needs to be set on CSP header , but the question how security can be achieved by setting the random nonce in the header . the answer of this question is as follows :
• We also need to set this same nonce in the parent script tag also and when the browser is requesting a page it checks nonce value from script tag and header and matches it and if it does not match then mark script as unsafe .
• With ’strict-dynamic’, dynamically generated scripts implicitly inherit the nonce from the trusted script that created them. This way, already- executing, legitimate scripts can easily add new scripts to the DOM without extensive application changes. However, an attacker who finds an XSS bug, not knowing the correct nonce, is not able to abuse this functionality because they are prevented from executing scripts in the first place.

Code Before CSP compatibility

``````<script src="/path/to/script.js"></script>
<script>foo()</script>``````

Code After CSP compatibility

``````/path/to/script.js
<script nonce="\${nonce}">foo()</script>``````

### Refactor inline event handlers and javascript: URIs

Inline event handlers (onclick=”…”, onerror=”…”) and <a href=”javascript:…”> links can be used to run scripts, so an attacker who finds an XSS bug could inject such HTML and execute malicious JavaScript. CSP requires refactoring those patterns into safer alternatives.

In most cases the changes will be straightforward. To refactor event handlers, rewrite them to be added from a JavaScript block:

Code before CSP compatability

``````<script> function doThings() { ... } </script>
<span onclick="doThings();">A thing.</span>``````

Code after CSP compatability

``````<span id="things">A thing.</span>

<script nonce="\${nonce}">
document.getElementById('things')
.addEventListener('click', function doThings() { ... });
});
</script>
``````

For javascript: URIs, you can use a similar pattern:

Code before CSP compatability

``<a href="javascript:linkClicked()">foo</a>``

Code after CSP compatability

``````<a id="foo">foo</a>

<script nonce="\${nonce}">
document.getElementById('foo')
});
</script>``````

### Uses of eval().

If your application uses eval() to convert JSON string serializations into JS objects, you should refactor such instances to JSON.parse().

If you cannot remove all uses of eval() you can still set a CSP policy, but you will have to use the ‘unsafe-eval’ CSP keyword which will make your policy slightly less secure.

There are many frameworks in this time , where we do not write the html and js instead we write coe in java and framework convert it into js for example GWT . Now in these case  the code generated should be CSP compatible is the responsibility of frameworks  .

For more knowledge on CSP you can read the following research paper  and for knowing what all other options  can be added to csp header and browser support  visit content-security-policy.com

Please comment more suggestions if any related to CSP .

You can checkout the following video for explanation of this blog .

# How to start your journey into Microservices Part -3 – Authentication Strategies

In the last blog we learned that we could use DDD to breakup the system into diff. microservices.

In this blog we will understand where and how we can implement authentication in Microservices.

## How to implement:

Let’s understand what all mechanisms are there to implement authentication and authorizations:

• Session Token <A long unidentifiable string> Based
• not meant for microservices enviornment as generally there will be multiple nodes and tying a request to one particular node is not good
• Redis or Any Other Caching tool
• store the session token in a cache after the login is done
• any request which needs to be checked verify the token from the cache
• JWT Tokens as Session Token<JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.>
• No external caching required
• Can be done at Service level only without any external call
• Challenges on keeping the signing secret constantly changing

In this both the approach has its pros and cons but i generally prefer Session Token and Cache based authentication for user based API and can use JWT for Service to Service communications , now a days JWT tokens are also used extensively.

• JWT challenges on being used in browser side
• No easy way to un-autheticate the JWT token as it is self verified <one way is time bound in that case token lives for ~5 min even after user logout> vs you can simply remove the token from
• You can sort of simulate invalidation of a JWT, for a particular verifying party, by storing the JWT ID (jti claim) or equivalent, into a “revoked” list. For example, in a cache stored in API Gateway. Use a TTL that is longer than the JWT Expiry. (This will not work well if the JWT does not have an expiry!)
• Other challenge is to manage the private keys very securely and constantly change it.

## When to implement:

Let’s understand the categories when we need authentication and authorization

• External API calls – api calls done from outside the system deployment either from UI or from third party.
• Internal API calls – api calls done internally from one service to another either in respect of a external API calls or internal timer jobs.
• Sometimes people do tend to overlook this area and make the internal API calls free from any authentication. Not the right approach
• To implement this we need ways to transparently paas<Try to do it at the Framework Level rather than every dev take care of this> authentication tokens from one service to another.
• With this is in place now every service becomes the owner for their data.

## Where to Implement:

• API Gateway Level
• In this we use a API gateway which does all the authentication either via Session Token or JWT or other mechanisms
• Any request coming at the gateway <l7 gateway eg: nginx,traefik> will checked for authentication and then only the request goes to the service
• Do not have to implement form scratch <even though almost every framework provides it out of the box>
• Service dosen’t seem to worry about authentication. <still when we talk about service to service communication for internal API call Service has to pass through the token>
• For any communication between services a gateway between services will also be required.
• Service Level
• At service level there are various frameworks <Spring Security , Passport JS for Node > which provides authentication and authorization part so that one dosen’t have to code them from scratch .
• Service <or Framework on which service is written> need to understand the token so that it can pass it through for Internal API calls.

It is very highly depends on the way you are integrating things that at which level you implement.

## Horizontal Aspects

• Auditing
• very important – must be considered from very starting.
• Many frameworks provide support for this eg: Spring Boot
• External IDP – Identity Providers
• If your are starting from scratch and want integrations with many third party like google , facebook and many others for single sign on external IDP is a very good choice.
• Auth0 , AWS Cognito , Okta are some of the external IDP
• Many things like password expiration policies , two factor authentication all available out of the box.

By now you must have got some gist about authentication in microservices world. For any doubts do put that into comments section.

# Vulnerability Updates | Week of June 21, 2021

The CISA Vulnerability Bulletin provides a summary of new vulnerabilities that have been recorded by the National Institute of Standards and Technology (NIST) National Vulnerability Database (NVD) in the past week. NVD is sponsored by CISA. In some cases, the vulnerabilities in the bulletin may not yet have assigned CVSS scores. Please visit NVD for updated vulnerability entries, which include CVSS scores once they are available.

Vulnerabilities are based on the Common Vulnerabilities and Exposures (CVE) vulnerability naming standard and are organized according to severity, determined by the Common Vulnerability Scoring System (CVSS) standard. The division of high, medium, and low severities correspond to the following scores:

• High: vulnerabilities with a CVSS base score of 7.0–10.0
• Medium: vulnerabilities with a CVSS base score of 4.0–6.9
• Low: vulnerabilities with a CVSS base score of 0.0–3.9

Entries may include additional information provided by organizations and efforts sponsored by CISA. This information may include identifying information, values, definitions, and related links. Patch information is provided when available. Please note that some of the information in the bulletin is compiled from external, open-source reports and is not a direct result of CISA analysis.

In this Blog , i am writing about High vulnerabilities only and some of Medium and Low if they it feels important to me .

For list of all vulnerabilities you can check CISA Bulletin .

## High Vulnerabilities

For the complete list Please visit https://us-cert.cisa.gov/ncas/bulletins/sb21-179

# Vulnerability Updates | Week of June 14, 2021

The CISA Vulnerability Bulletin provides a summary of new vulnerabilities that have been recorded by the National Institute of Standards and Technology (NIST) National Vulnerability Database (NVD) in the past week. NVD is sponsored by CISA. In some cases, the vulnerabilities in the bulletin may not yet have assigned CVSS scores. Please visit NVD for updated vulnerability entries, which include CVSS scores once they are available.

Vulnerabilities are based on the Common Vulnerabilities and Exposures (CVE) vulnerability naming standard and are organized according to severity, determined by the Common Vulnerability Scoring System (CVSS) standard. The division of high, medium, and low severities correspond to the following scores:

• High: vulnerabilities with a CVSS base score of 7.0–10.0
• Medium: vulnerabilities with a CVSS base score of 4.0–6.9
• Low: vulnerabilities with a CVSS base score of 0.0–3.9

In this Blog , i am writing about High vulnerabilities only and some of Medium and Low if they it feels important to me .

For list of all vulnerabilities you can check CISA Bulletin .

## High Vulnerabilities

For the complete list Please visit https://us-cert.cisa.gov/ncas/bulletins/sb21-172

# Vulnerability Updates | Week of June 7, 2021

The CISA Vulnerability Bulletin provides a summary of new vulnerabilities that have been recorded by the National Institute of Standards and Technology (NIST) National Vulnerability Database (NVD) in the past week. NVD is sponsored by CISA. In some cases, the vulnerabilities in the bulletin may not yet have assigned CVSS scores. Please visit NVD for updated vulnerability entries, which include CVSS scores once they are available.

Vulnerabilities are based on the Common Vulnerabilities and Exposures (CVE) vulnerability naming standard and are organized according to severity, determined by the Common Vulnerability Scoring System (CVSS) standard. The division of high, medium, and low severities correspond to the following scores:

• High: vulnerabilities with a CVSS base score of 7.0–10.0
• Medium: vulnerabilities with a CVSS base score of 4.0–6.9
• Low: vulnerabilities with a CVSS base score of 0.0–3.9

In this Blog , i am writing about High vulnerabilities only and some of Medium and Low if they it feels important to me .

For list of all vulnerabilities you can check CISA Bulletin .

## Medium Vulnerabilities

For the complete list Please visit https://us-cert.cisa.gov/ncas/bulletins/sb21-165

# Checklists – System is Hacked – Part 2 – Preventive Steps for Infra (OS Hardening)

In last article we described List of Checks which can determine if system is compromised or hacked .  In this article we will talk about preventive steps (specially infra related) can be taken care to avoid hacking or to make system more secure  . There are many directions in which we can secure our application  as follows :

• OS hardening (Infra Level Security)
• Secure Coding guidelines
• Encryption Of Sensitive Data  .
• Ensure No Vulnerability exists in system .

In this Blog we will be concerned about OS hardening (Infra Level Security) in Linux systems(CentOS/Redhat). We will Cover Other parts in Future Blogs .

Now Let’s go to the System Part. It has following things to be taken care of :

• SSH Configuration :
• In linux based system SSH default port is 22 . This Defaut port should be changed to some unused port to enhance security .
• Use SSH Protocol 2 Version
• Ensure SSH X11 forwarding is disabled
• Port Configuration at Firewall :  Generally , in any application there are many applications running on set of servers and each running on some different ports , Say for example :
• Application server at  8080 port
• Database Server at 5432 port

So,  as in above Case Users need to login through 8080 port so only this port should be opened for public as Database needs to interact generally with application server so 5432 port should be allowed from Application Server’s IP  .

• Multi Factor Authentication for SSH should be enabled   —  For setting up Google Authentication on CentOS or Redhat you can follow the link
• Root login for any server must be disabled
• Ensure password expiration is 365 days or less
• Ensure minimum days between password changes is 7 or more
• Ensure password expiration warning days is 7 or more
• Ensure inactive password lock is 30 days or less
• Ensure Password should be strong enough when user change its password
• Application and Database should be on different Servers  :  this is because of that if due to some vulnerability  application hacked than acces to database in that case is protected  .
• Regular package updates   :  Configure Auto update or regularly update packages on all configured servers .
• Tune Network Kernel Parameters :
• IP forwarding should be disabled on all servers
• Do the following entry in sysctl.conf
• net.ipv4.ip_forward = 0
• Packets Redirecting  should be diabled on all servers .
• Do the following entry in sysctl.conf
• net.ipv4.conf.all.send_redirects = 0
• net.ipv4.conf.default.send_redirects = 0
• Selinux should be enabled and configured .
• Antivirus must  be installed on all servers .

All Above are basic minimum checklists which should be applied to all the servers in any production environment . For implementing in-depth OS Hardening specially for CentOS based Systems , one need to follow the latest CIS CentOS Benchmarklatest CIS

You can also check the below benchmark list from CIS for CentOS hardening : Below doc also explain how to implement things on CentOS .

In Our Future blog we will explain other parts like Secure Code guidelines , Encryption , VAPT scan etc  to make system more secure .

Stay tuned .

# Checklists – System is Compromised or Hacked – Part 1

## Introduction

As in my previous Blog where i explained how i came to know if my system is hacked or compromized (link here). Here in this blog i will explain what basic things we can check on our system when we have doubt if our system is compromized .

This Blogs have 3 parts

• List of Checks which can determine if system is compromised or hacked – Part 1
• List of checks which can give a direction how system is compromised or hacked – Part 2
• What preventive steps (specially infra related) can be taken care to avoid hacking or to make system more secure – Part 3

Here , i am assuming system is Linux system with Centos installed .

## List of Checks which can determine if system is compromised or hacked

• Generally when hacker break into a linux system it is high chance that it will alter you main packages like openssh,kernel etc.. , So first if of please check if these packages are altered or there are some changes in the files or binaries provided by these packages . Following are commands to check on Centos
• `sudo rpm -qa | grep openssh | xargs -I '{}' sudo rpm -V '{}'`
• If therr are files shown by above command in which you did not change anything then it means there is high chance your system is compromised
• Run rootkit Hunter to check if you system is compromised
• `Download rkhunter.tar.gz `
• `copy it in /root and goto /root `
• `tar zxvf rkhunter-1.4.2.tar.gz `
• `cd rkhunter-1.4.2/ `
• `sh installer.sh --layout default --install `
• `changes in /etc/rkhunter.conf ENABLE_TESTS="all" DISABLE_TESTS="none" HASH_CMD=SHA1 HASH_FLD_IDX=4 PKGMGR=RPM 7`
• `/usr/local/bin/rkhunter --propupd `
• `/usr/local/bin/rkhunter --update `
• `/usr/local/bin/rkhunter -c -sk 10. `
• `note output or check and copy /var/log/rkhunter.log`
• `you can also check the link for using rkhunter`
• Check /var/log/secure to check if there are many authentication failure requests and someone trying brute force to enter in to system
• following will be the comand :
• `[root@localhost ~]# less /var/log/secure | grep 'authentication failures'`
• and output will be something like :
• `Apr 25 12:48:46 localhost sshd[2391]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.29.14 user=root`
• `Apr 25 12:49:33 localhost sshd[2575]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.29.14 user=root`
• In above output you can see the rhost from where login attempt are made . If you see lots of entries like this then also check if at some point of time some login attempt will be successful from any of attempting rhosts . In secure logs accepted logs will looks something like as follows :
• `Apr 25 12:53:10 localhost sshd[3551]: Accepted password for root from 192.168.29.14 port 36362 ssh2`

• Check in Processes if some unusual process is running and consuming high CPU using top and ps commands .
• Command to list all process running in system : `ps aux | less`
• Also check using top command if some unusual process trying to utiize high cpu
• Check if there is some unusual entry in crontab of all users made on system
• `crontab -u <user> -l . by default user is root`
• Check if in id_rsa.pub , if some attacker has somehow made its entry in .ssh folder in every users’s home directory .

This was the Part 1 of the Blog , In later Parts i will explain some further checklist to ensure that you system will remain less hackable .

Thankyou .

# Linux Machine Compromized/Broken -Power of Observation

Introduction :

In Debugging any issue or any dealing any problem or circumstance two things are important

• Observation — Observation not only at the time of issue but in general times also .
• Combining your general observations and Observations at the time of issue to conclude something .

In this Blog , I will explain the following :

• What was happening on my machine
• How i came to know my machine is broken into — Power of observation

### What was happening on my machine

• Load on my machine is going very high
• On top command one process ./kwsapd0 is consuming around 3000% cpu

From here we get to know that kswapd is consuming process , The process kswapd0 is the process that manages virtual memory . So I thought that may be our some process is consuming more RAM and Virtual Memory is being used due to which kswapd process is doing its work but after hours of debugging we found no process is consuming RAM and around 80% RAM was free .

### How i came to know my machine is broken into — Power of observation

There were two general observation which i observed and helped my geeting know what was the issue

• 1st is kswapd process looks in top command like [kswapd] not ./kswapd
• Kswapd0 can only consume 100% as it uses only one core in the machine .

From there I got to know that this kswapd0 is something unusual . On further debugging

I found ./.configrc/a/kswapd0 in root users directory .

Contents of this directory was :

\$ find .configrc -type f
.configrc/dir2.dir
.configrc/a/kswapd0
.configrc/a/dir.dir
.configrc/a/a
.configrc/a/bash.pid
.configrc/a/run
.configrc/a/stop
.configrc/a/init0
.configrc/a/.procs
.configrc/a/upd
.configrc/cron.d
.configrc/b/sync
.configrc/b/dir.dir
.configrc/b/a
.configrc/b/run
.configrc/b/stop

There was also an entry in cron to run this .

So , From all of this i got to know that my system was compromised .

Yet I was unable to find out how my system was broken into . But in my future Blog i will explain what things one can check if your system is compromised and how it is compromised and what all security we can apply to our system to make it less hackable .