Security & Safe Coding Practices in Python

Introduction

Security ek bahut important topic hai jab hum production-level Python apps likhte hain. Chahe wo web app ho, API ho ya CLI tool — galat code likhne se sensitive data leak ho sakta hai ya hackers system me ghus sakte hain. Yahaan hum seekhenge kuch best practices jo aapke code ko safe aur reliable banayenge.

1️⃣ Input Validation

Kabhi bhi user se directly input lene par blindly trust mat karo. Pehle check karo ki input valid hai ya nahi — warna injection attacks ho sakte hain.

# Unsafe example
username = input("Enter username: ")
print("Welcome " + username)

# Safe example
import re
username = input("Enter username: ")
if re.match("^[A-Za-z0-9_]+$", username):
    print("Welcome", username)
else:
    print("Invalid username!")

Hamne regular expression se ensure kiya ki input me sirf alphanumeric characters ho. Isse code injection ka risk kam hota hai.

2️⃣ Avoid Using eval() and exec()

eval() aur exec() user input execute karte hain — ye bahut dangerous ho sakta hai agar input trusted nahi hai.

# Extremely unsafe
user_input = input("Enter code: ")
eval(user_input)  # can run anything!

Aise code me koi bhi harmful command run ho sakti hai, jaise files delete karna ya system access karna. Hamesha alternatives use karo — jaise predefined commands aur if-else logic.

3️⃣ Secure Password Handling

Kabhi bhi passwords plain text me store mat karo. Hamesha hashing use karo taaki even agar database leak ho jaye to passwords secure rahein.

import hashlib

password = "mysecret123"
hashed = hashlib.sha256(password.encode()).hexdigest()
print("Hashed password:", hashed)

Hashing irreversible hoti hai — original password recover nahi hota. Production me aur secure hashing ke liye bcrypt ya argon2 library use karo.

4️⃣ Environment Variables for Secrets

API keys, database passwords, aur secret tokens kabhi bhi code ke andar hardcode mat karo. Iske liye dotenv ya os.environ ka use karo.

# .env file
API_KEY=abcd1234xyz

# main.py
import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv("API_KEY")
print(api_key)

Ye method secrets ko code ke bahar rakhta hai, jo security ke liye best practice hai.

5️⃣ File Handling Safely

File open karte waqt user input se file path directly mat lo — warna directory traversal attacks possible hain.

import os

filename = input("Enter file name: ")
safe_dir = "/safe_folder/"
filepath = os.path.join(safe_dir, os.path.basename(filename))

with open(filepath, "r") as f:
    print(f.read())

os.path.basename() ensure karta hai ki sirf file name use ho, path traversal nahi.

6️⃣ Use HTTPS for Network Requests

Jab bhi APIs ya web requests use karo, ensure karo ki URL https:// se start ho. http:// se data plain text me transmit hota hai jo intercept ho sakta hai.

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

HTTPS data ko encrypt karta hai, isliye secure communication ke liye mandatory hai.

7️⃣ Keep Dependencies Updated

Outdated libraries me known vulnerabilities hoti hain. Isliye regularly update karte raho:

pip list --outdated
pip install --upgrade package_name

Aap pip-audit ya safety tools bhi use kar sakte ho dependency security check ke liye.

8️⃣ Principle of Least Privilege

Apne application ko sirf utni permissions do jitni zarurat ho. For example, agar app ko sirf read access chahiye, to write/delete permission mat do.

Ye principle aapke system ke damage ko limit karta hai agar kabhi koi vulnerability exploit hoti hai.


OOP & Design Patterns Iterators & Generators Decorators & Context Managers Concurrency & Async File & Data Handling Networking & APIs Testing Performance Packaging Security Projects