Tuesday, November 24, 2026

Secure coding best practices

 To create secure code, here are a few things I would do -  build security into the entire development process:




  1. Understand the security requirements. Identify the sensitive data the application handles, who should have access, and what confidentiality, integrity, and availability protections it needs.

  2. Perform threat modeling. Map how data moves through the application, identify entry points and trust boundaries, and consider how an attacker could misuse each feature.

  3. Design for least privilege. Give users, applications, and service accounts only the permissions they need. Separate sensitive operations and limit the impact of a compromised component.

  4. Validate input. Treat data from users, files, APIs, databases, and external services as untrusted. Check types, lengths, ranges, formats, and permitted values on the server.

  5. Prevent injection attacks. Use parameterized database queries, safe process APIs, and context-appropriate output encoding. Avoid executing untrusted input as code or incorporating it into shell commands and template source.

  6. Secure authentication and sessions. Use established authentication libraries or identity providers, support multifactor authentication where appropriate, and protect sessions with secure cookies, expiration, and proper logout handling.

  7. Enforce authorization. Check permissions on every protected operation and resource, including individual records. Deny access by default and verify authorization on the server.

  8. Protect sensitive data. Minimize collection and retention, use established encryption libraries, protect data in transit and at rest, and store passwords using a suitable password-hashing algorithm with unique salts.

  9. Manage secrets securely. Keep passwords, tokens, and encryption keys out of source code and logs. Use a secrets manager, restrict access, and support rotation and revocation.

  10. Use trustworthy dependencies. Select maintained libraries, minimize unnecessary packages, review their provenance, and scan for known vulnerabilities. Control dependency versions and apply security updates.

  11. Handle errors safely. Return useful but limited error messages to users. Keep stack traces, credentials, and internal system details out of public responses.

  12. Add secure logging and monitoring. Record security-relevant events, protect logs from tampering and injection, and avoid recording secrets or unnecessary personal information.

  13. Protect files and network access. Restrict upload types and sizes, prevent path traversal, and store uploads safely. Limit outbound requests to prevent server-side request forgery and access to internal services.

  14. Prevent business logic abuse. Check transaction rules and state changes, handle concurrency safely, and use rate limits, timeouts, and resource limits to reduce misuse and denial of service.

  15. Use secure defaults. Disable debug features in production, restrict exposed services, configure browser security controls where relevant, and isolate workloads according to their risk.

  16. Review and test the code. Conduct peer security reviews and test failed authentication, unauthorized access, malformed input, and abuse scenarios. Use SAST, DAST, dependency scanning, secret scanning, and fuzz testing where appropriate.

  17. Secure the build and deployment pipeline. Protect repositories and branches, review changes, restrict CI/CD permissions, and verify the integrity of release artifacts. Scan infrastructure and container configurations.

  18. Maintain security after release. Monitor for vulnerabilities, patch affected components, investigate alerts, and maintain an incident response process. Add regression tests for security defects so they do not recur.

The goal is to prevent weaknesses, detect those that remain, and limit the damage if an attacker exploits one. Automated tools support this work, but they need to be combined with sound design, review, and ongoing maintenance.

Types of injection attacks and how can we prevent them?

An injection attack happens when an application treats untrusted input as instructions. That input might come from a form, API request, uploaded file, HTTP header, or external service.

The central rule is keep untrusted data separate from executable instructions. Input validation supports that rule, but it does not replace parameterized queries, safe APIs, or context-specific encoding. Least privilege limits the damage if an injection flaw is exploited.



Common types and their defenses include:

Injection typeWhat happensHow to prevent it
SQL injectionInput changes a database query, potentially exposing or modifying data.Use parameterized queries or prepared statements. Allowlist dynamic table names, column names, and sort options that cannot be parameterized. Limit database permissions.

Operating system command injectionInput changes a shell command, allowing unintended commands to execute.Prefer language APIs over shell commands. When invoking a process, use a fixed executable and pass arguments separately with the shell disabled. Validate arguments and restrict permitted options.

Code injectionInput executes as application code through features such as eval() or dynamic execution.Avoid evaluating untrusted text as code. Use data parsers and predefined operations. Isolate execution when running untrusted code is a required feature.

Cross-site scripting (XSS)Attacker-controlled content runs as JavaScript in another user’s browser.Use context-appropriate output encoding and safe DOM APIs such as textContent. Sanitize intentionally supported HTML with a maintained sanitizer. Use Content Security Policy as an additional defense.

Server-side template injectionInput becomes part of a template’s source and executes template expressions.Keep templates fixed and pass user content only as data. Avoid compiling user-controlled templates; isolate execution if that capability is necessary.

NoSQL injectionInput introduces query operators or changes a document database query’s structure.Build queries using typed APIs, enforce expected input types, and reject unexpected operators or fields. Do not accept arbitrary client-supplied query objects.

LDAP or XPath injectionInput alters directory searches or XML queries, potentially bypassing access checks or exposing records.Use parameterized interfaces where supported; otherwise apply escaping specific to the query language and context. Avoid building expressions through string concatenation.

XML external entity (XXE) injectionMalicious XML causes a parser to access local files or make unintended network requests.Disable DTDs, external entities, and external resource resolution when unnecessary. Use securely configured XML parsers.

HTTP header / CRLF injectionInput inserts line breaks or additional headers into an HTTP response.Use framework header APIs, reject carriage returns and line feeds in header values, and validate redirects and cookies through dedicated APIs.

Log injectionInput creates misleading log entries or introduces control characters that obscure events.


Use structured logging with correct serialization. Encode or reject control characters and render log content safely in viewers.


Monday, January 27, 2020

Protection against OTP abuse

The first factor identification with any internet application happens through sign up functionality and if there is a requirement to associate the user with phone number for the apps like e-commerce, food delivery, medicine delivery, events lookup etc, then the Signup is programmed to happen to OTPs.

Since any and every user is expected to produce OTP while signing up, the feature as such should not be bound by any security headers. This makes the OTP generation and delivery of OTP SMS vulnerable to an array of attacks like

1. DDoS attack - No further SMSes can be sent when the allocated SMS threshold for a given time for an application from the SMS service provider is reached due to increased requests.
2. Resource exhaustion attack - Exhausting allocated cost per unit time for sending SMS due to DDoS
3. Unintentional sending of SMS to customers that lead to annoyance and even to unregistered customers



Some of the counter measures to stop the abuse

1. Rate limiting - Both phone no. and IP wise
When the requests are received more than a no. of times from the same phone no. or from same ip for different phone no.s then they should not be served.

2. If same ip is sending OTP requests, though they are repelled, the ip should be blacklisted as the rate limit will hold good for a certain time range and the ip again becomes a valid ip after some time

3. Captcha is good option which looks for a valid recaptcha token in all the requests and these tokens are dynamically generated. The cons is that it obstructs the UX on the mobile apps

4. Use of invisible captcha which sends the captcha token and the captcha score along with the request. The score is based on the ip of the device where the request originates. Say this score is 0.9 for a genuine user.  If a same device is generating many requests, this score becomes less and less with every request. Say 0.7.  There will be a threshold score that the application has set in its server and (May be 0.8). If the score that request bring in lesser than the threshold score, then the requests are rate limited later on

5. Posing the recaptcha only when the requests attempts exceeded the number defined by the application.

6. Using a device-id which uniquely identifies the user's device in the request. There can be rate limits on this one as well where the check for device-id being associated for more than 2 phone no.s is blacklisted or rate limited.

7. Checking for proxy, tor requests and blocking them all together.

8. The phone no.s can be encrypted before using them in the requests so that attacker do not know the exact phone no.s. The phone no.s can be modified with a combination of hashing, salting, concatenating with time stamps etc so that it becomes difficult for the attacker to guess the 10 digit phone so it can be enumerated.

9. Finally there are apps and solutions that help you protect against the OTP abuse. They make use of machine learning and look up the global data bases for threat posing ips and actors and block them for your application. Few of the examples are Alibaba cloud Web application Firewall, Cloudfare solutions, Akamai solutions.

Please let me know your thoughts in the comments.


Sources:

https://www.ijert.org/research/sms-based-one-time-password-vulnerabilities-and-safeguarding-otp-over-network-IJERTV3IS051538.pdf

https://security.stackexchange.com/questions/184619/prevent-against-otp-abuse-in-app-sign-up-flow?rq=1

https://ringcaptcha.com/voice-sms-otp-resource-exhaustion-attacks

Friday, January 24, 2020

SSL Handshake

This is no rocket science either. All communication over the internet happens with the SSL(Secure sockets layer) handshake which is now called as the TLS(Transport layer security) handshake. SSL was designed for HTTP connections and TLS has replaced the SSL.

The TLS handshake happens between the client and the server. The two parties involved will do the following


  • Specify the version of TLS they are using 
  • The type of cipher suite 
  • Identify the server and authenticate it through server's public key or SSL certificate authority's digital signature.
  • Establish session keys to use the symmetric encryption for further data in transit. 




Below are the exact steps that occur during the TLS DH handshake


  • The browser(client) will send the "Hello" message to server with details of its TLS version and cipher suites. It also sends string of random bytes known as client random
  • The server replies with to the client with its SSL certificate, cipher suite and server random. 
  • The client verifies the server's SSL certificate with the certificate authority that issued it. This confirms that the server is who it says it is, and that the client is interacting with the actual owner of the domain.
  • The client sends one more random string of bytes, the "premaster secret." The premaster secret is encrypted with the public key and can only be decrypted with the private key by the server. (The client gets the public key from the server's SSL certificate.)
  • The server decrypts the premaster secret using the private key
  • Both client and server generate session keys from the client random, the server random, and the premaster secret. They should arrive at the same results.
  • The client sends a "finished" message that is encrypted with a session key.
  • The server sends a "finished" message encrypted with a session key.


Homomorphic encryption

Homomorphic encryption is a type of encryption where the data in transit can be accessed, computed, analysed all the while the data remains encrypted. This can be extension of both symmetric and asymmetric encryption(See Symmetric and Asymmetric Encryption for more details). This can be used for outsourcing encrypted data for storage and computation to the cloud environments

In plain language homomorphic encryption is like this - Assume there are many things in a bag and you put your hands inside, manipulate their positions, access them and sense them but you cant pull them out and see for real what they are.



This kind of data transmission is required in healthcare where the privacy is of most concern. The same holds good for voting purposes where the data needs to be encrypted for privacy purpose but also should be assessed. In the banking sectors too this is used to protect the PII and still perform the required processing on the data.

The computations on the data are represented by either Boolen or arithmetic circuits.

Types of homomorphic encryption 

Partially homomorphic encryption: 


encompasses schemes that support the evaluation of circuits consisting of only one type of gate, e.g., addition or multiplication.


Somewhat homomorphic encryption:
can evaluate two types of gates, but only for a subset of circuits

Leveled fully homomorphic encryption :

supports the evaluation of arbitrary circuits of bounded (pre-determined) depth

Fully homomorphic encryption(FHE): 

allows the evaluation of arbitrary circuits of unbounded depth, and is the strongest notion of homomorphic encryption

For the majority of homomorphic encryption schemes, the multiplicative depth of circuits is the main practical limitation in performing computations over encrypted data.

Symmetric and Asymmetric encryption

This is no rocket science that I am writing about. Its the next post that will need this information.

Symmetric encryption




Its the encryption where the source thats encrypting the information and the destination thats decrypting it will make use of the same key. This means to say that you encrypt and decrypt using the same key. This key is often called as secret key. The key is generally a password or code or a random generated number(RNG). Two types of symmetric encryption -

Block algorithms:


Set lengths of bits are encrypted in blocks of electronic data with the use of a specific secret key. As the data is being encrypted, the system holds the data in its memory as it waits for complete blocks

Stream algorithms: 

Data is encrypted as it streams instead of being retained in the system’s memory. 

Symmetric Encryption use cases: 

Due to the better performance and faster speed of symmetric encryption (compared to asymmetric), symmetric cryptography is typically used for bulk encryption / encrypting large amounts of data, e.g. for database encryption. In the case of a database, the secret key might only be available to the database itself to encrypt or decrypt.
Some examples of where symmetric encryption is used are in banking sector: 
  • Payment applications, such as card transactions where PII needs to be protected to prevent identity theft or fraudulent charges
  • Validations to confirm that the sender of a message is who he claims to be
Asymmetric encryption


This is also called as Public key encryption which is the basis for public key infrastructure(PKI). There are two keys - Public and Private. The Public key is used by the client to encrypt. Private key is saved at the server which is used to decrypt. The keys are mathematically connected. 

One of the ways of using the asymmetric encryption is through digitally signature. The information is signed with sender's private key and only those who produce the public key for the same will receive access to the information sent. 

Examples of Asymmetric encryption

Diffie–Hellman key exchange:

The simplest and the original implementation of the protocol uses the multiplicative group of integers modulo p, where p is prime, and g is a primitive root modulo p. These two values are chosen in this way to ensure that the resulting shared secret can take on any value from 1 to p–1



RSA: 

The intention is that messages encrypted with the public key can only be decrypted in a reasonable amount of time by using the private key. The public key is represented by the integers n and e; and, the private key, by the integer d (although n is also used during the decryption process. Thus, it might be considered to be a part of the private key, too). m represents the message (previously prepared with a certain technique explained below)







Wednesday, January 15, 2020

Bug bounty - Simple tips and tricks

Its been a couple of months that I am bug hunting and I think I got hang of it now. Bug bounties are the most fancied way of earning money among the ethical hackers and otherwise engineers. I get many requests on Linkedin and Telegram to teach them about bug bounty. I have followed a few big time bug hunters and learnt from them. There are awesome writeups, podcasts and tutorials on Pentester.Land





Here are a few tips and tricks to get started with any bounty program.

Follow platforms like HackerOne and BugCrowd. They have organised bounty programs which reward in points and money according to the priority of the bug found. They have charity programs too if you wish to donate.

So, when there are new programs launched for websites, mobile apps and APIs, you get to see whats in scope of the program and whats not. If you are reporting a bug thats not in scope, you get -ve points. There will be rules of the program which you MUST read carefully to understand the type of program and areas of focus. Some look for issues in UI. Some look for issue in Broken Authentication and session management mechanisms, Some for functional security issues. Be sure to get their point of view.

When you find a bug, be sure you choose the right category to report. This is important because reporting in a lesser priority category do not get the attention that the bug requires. It does not mean you choose P1 or P2 for all bugs that you choose. Just choose right.

Make a POC of the bug with log trace, screenshots, replication method and explain the impact of the bug in plain english and do not disclose your personal information or any sensitive information thats known to you.

Submit the bug and wait for the response. Generally they will reply within 2 days to 7 days if its from HackerOne or BugCrowd. If the bug is duplicate or rejected, you get nothing.

You can look for private bounty programs by searching on google too using any string that corresponds to bug disclosure. Examples like
insite: Responsible disclosure policy
insite: Security issue disclosure.

So here are the most commonly seen and found issues in the bug bounties.

1. Rate limiting - Rate limit can be for email or OTP. Look for places like Sign Up and Reset Password, Forgot Password. Provide the same email or phone # and see if there is rate limiting. If you can get hundreds of reset password links or OTPs, then you found the bug.

2. No email validation - Again look for Sign up mechanism where one needs to register. If there is an ask to enter email and there is no validation(You get an email on the registered email id and you got to click on it to activate your account), then attacker/you can enter anyone's email and get the signing up going on.

3. Rate limiting login attempts - From the burp suite, identify which is the login API and check for params sent with it. Send the API to intruder. Add a few usernames and passwords. Send the requests. After a few times for a given username, the application should error out saying no more login attempts or provide a captcha.

4. Brute forcing login - Use Burp Suite again to capture login API. If you know/guess any of the usernames and their passwords, try them or use a dictionary file in the intruder brute force the login. This only works if there is no rate limiting on the login attempts

5. Third party reset token leak - When a password reset token is sent to the legitimate user, see if the same is sent as part of any calls made in the third parties integration calls.

6. Captcha bypass - Use a proxy like FoxyProxy or SmartProxy or JetProxy and open the website link where the captcha is posed to the user. If the website opens, you have bypassed the captcha implemented on the website

7. Injections - Look for a search field in the website and see if the search string gets attached to the URL of the page as an extension. Eg: https://example.com?search/key-alumni
Modify this and inject "><script>alert('pop up')</script>
XSS injections and HTML injection are the most commonly seen apart from sql injections.

8. Clickjacking - Make use of chrome extensions like "Clickjacking test" to generate the HTML or simply use the below code. Change the iframe src to the one you are testing. If there is an output, then there is a bug
<html>
<--Report Generated by Clickjacking Test v1.0-->

<head>
<title>Clickjack test page</title>
</head>
<body>
<p>Website is vulnerable to clickjacking!</p>
<iframe src="https://cloudinary.com" width="500" height="500"></iframe>
</body>

</html>





Secure coding best practices

 To create secure code, here are a few things I would do -  build security into the entire development process: Understand the security requ...