Overview
This chapter introduces Web Applications and Security for Class 10 Information Technology (Code 402). It explains what web applications are, how they work (client-server model, browsers, servers and web protocols), and why they are central to modern life — from online learning and e-commerce to social networking and cloud services. The chapter also emphasises web security: common threats (like phishing, malware, XSS and SQL injection), safe user practices (strong passwords, HTTPS, avoiding suspicious links), and basic developer-side protections (input validation, authentication, encryption and regular updates). Students will learn to identify components of a simple web application, understand how data flows on the web, recognise security risks, apply safe browsing and data-handling habits, and appreciate the principles behind secure design and responsible online behaviour.
Learning Objectives
- Define key web concepts such as web client, web server, URL, HTTP and HTTPS.
- Explain the purpose and functioning of DNS and how domain names map to IP addresses.
- Describe the functions of web browsers and common features for navigation, bookmarking and privacy.
- Identify common web application components such as HTML forms, cookies, sessions and databases.
- Apply basic input validation techniques to prevent client-side errors and reduce security risks.
- Demonstrate how cookies and sessions maintain state in web applications and explain associated privacy implications.
- Explain common web security threats including phishing, malware, XSS, SQL injection and CSRF, with examples.
- Analyze the differences between HTTP and HTTPS and explain how SSL/TLS provides encrypted communication.
Topics in this chapter
22 topics · tap a topic title to jump straight to it.
Overview of Web Applications
Overview of Web Applications
Key Point: Uptime percentage = (Total time service is available / Total observed time) × 100
Definition: A web application is a software application that runs on web servers and is accessed by users through a web browser over the Internet or an intranet. Unlike desktop applications, web apps do not need to be installed on the user's computer.
How a web application works (simple flow):
- User (client/browser) sends an HTTP request (for a page, form submission, API call).
- Web server receives the request and forwards it to the application logic (application server).
- Application logic processes the request, may read/write data from a database, and generates a response (HTML, JSON, etc.).
- Web server returns an HTTP response to the browser, which renders the result for the user.
Main components:
- Client (browser/mobile app) — user interface and presentation layer.
- Web server — handles HTTP requests and responses (e.g., Apache, Nginx).
- Application server — runs the web application code (business logic).
- Database server — stores and retrieves persistent data (e.g., MySQL, PostgreSQL).
Types of web applications:
- Static web pages — fixed content (HTML/CSS).
- Dynamic web applications — content generated on demand (login, forms, personalized pages).
- Single Page Applications (SPA) — load once and update content dynamically (examples: Gmail, Google Maps).
- Progressive Web Apps (PWA) — web apps with native-app-like features (offline support, installable).
Key characteristics: platform independent (runs on any device with a browser), requires internet/network, easier to update centrally, can be responsive (work on multiple screen sizes).
Security and maintenance basics: Web apps must handle authentication (confirm user identity), authorization (control actions), data encryption (HTTPS) and input validation (prevent malicious inputs). Regular backups, updates and patches are part of maintenance.
Advantages: No installation, central updates, cross-platform access, easy sharing of data. Limitations: Requires network access, performance depends on server and connection, security risks if not properly protected.
Real-world usage: web-based email, online banking, e-commerce sites, school portals, online quizzes and learning platforms, social networking sites and cloud-based office suites.
- Online banking portal — access account details, transfer funds, view statements via a browser.
- E-commerce website (e.g., Amazon) — browse products, add to cart, checkout and payment through a web interface.
- Web-based email (e.g., Gmail) — read, compose and manage emails using only a browser.
- Online learning platform (e.g., Google Classroom or an LMS) — attend classes, submit assignments, view grades.
- Ticket booking website — search availability, select seats and make payment online.
- Cloud office suite (e.g., Google Docs) — create and edit documents collaboratively in real time.
- \[Uptime percentage = (Total time service is available / Total observed time) × 100\]
- \[Average response time = (Sum of individual response times) / (Number of requests)\]
- \[Throughput (requests per second) = Total requests served / Total time (seconds)\]
- \[Bandwidth usage = Total data transferred (bytes) / Time (seconds)\]
- \[Cache hit ratio = (Number of cache hits) / (Total cache requests)\]
Client‑Server Architecture
Client‑Server Architecture
Key Point: Throughput = Number of requests served / Time (requests per second)
Definition: Client‑Server Architecture is a network model in which tasks and services are divided between providers (servers) and requesters (clients). A client sends requests to a server, the server processes them (possibly using a database or other services) and returns responses.
Basic components:
- Client: The application or device that initiates requests (web browser, mobile app).
- Server: The system that waits for and responds to client requests (web server, application server, database server).
- Network/Protocol: The medium and rules used to communicate (TCP/IP and HTTP/HTTPS for web apps).
How it works (request–response cycle):
- Client sends a request (for example an HTTP GET or POST) to the server's IP and port (commonly port 80 for HTTP or 443 for HTTPS).
- Network routes the request to the server.
- Server processes the request (may query a database, run business logic) and creates a response.
- Server returns the response (HTML, JSON, file, status code) to the client, which renders or uses it.
Web specifics: Most web applications use stateless HTTP: each request is independent. To maintain state (login sessions, shopping carts) servers use cookies, session IDs or tokens.
Types of servers:
- Web server: serves static content (HTML, CSS, images).
- Application server: runs application logic (processes forms, handles transactions).
- Database server: stores and retrieves persistent data.
Advantages: centralized data and control, easier maintenance, resource sharing, scalable by adding servers.
Limitations & solutions: A single server can become a bottleneck. Solutions include load balancing, caching, replication and using multi‑tier (n‑tier) architectures.
Security considerations: Use HTTPS (SSL/TLS) to encrypt data in transit, authenticate users, validate inputs on server side, protect databases, configure firewalls and keep servers patched to reduce vulnerabilities.
Typical technologies/protocols: HTTP/HTTPS, TCP/IP, REST APIs, SOAP (legacy), ports 80/443, SSL/TLS, cookies/sessions, JSON/XML data formats.
Simple example flow: When you type a URL in a browser: DNS resolves domain → browser (client) sends HTTP GET → web server receives and forwards to application layer → app queries database → server sends HTML/JSON back → browser displays page.
- Browsing a website: Your browser (client) requests a page and the web server returns HTML/CSS/JS to render the page.
- Online banking: Client app sends login and transaction requests to bank servers; the server authenticates, checks data, updates accounts and sends confirmations.
- Cloud file storage (e.g., Google Drive): Client uploads/downloads files; servers store files, handle permissions and sync across devices.
- Email: Mail clients use protocols (SMTP, IMAP, POP3) to send/receive messages from mail servers.
- Streaming video: The client requests video segments from a streaming server which delivers content adapted to network speed.
- \[Throughput = Number of requests served / Time (requests per second)\]
- \[Response time ≈ Transmission time + Processing time + Queuing time (simple breakdown)\]
- \[Availability (%) = (Uptime / (Uptime + Downtime)) × 100\]
- \[Latency (approx) = Round Trip Time (RTT) = Time from request sent to response received\]
Web Browsers and Web Servers
Web Browsers and Web Servers
Key Point: URL structure: protocol://domain[:port]/path?query#fragment
Overview: A web browser is a client program that requests, receives and displays web resources (web pages, images, videos) to users. A web server is software (and often the machine it runs on) that stores, processes and serves web resources when requested by browsers using the HTTP/HTTPS protocols.
How they interact (Client–Server model)
- User types a URL in the browser or clicks a link.
- Browser resolves the domain via DNS to an IP address.
- Browser opens a TCP connection (usually to port 80 for HTTP or 443 for HTTPS) and sends an HTTP request.
- Web server processes the request (serves static files or runs server-side code) and sends an HTTP response.
- Browser renders the response (HTML → DOM, CSS → CSSOM, JavaScript executed) and shows the page.
Browser components and rendering process
- User Interface: address bar, bookmarks, back/forward.
- Networking: manages HTTP/HTTPS requests and responses.
- HTML parser & DOM builder: converts HTML into a DOM tree.
- CSS engine: builds CSSOM and computes styles.
- Layout / Render tree: calculates geometry for each node.
- Painting & Compositing: draws pixels to screen.
- JavaScript engine: executes scripts and can modify the DOM; may trigger reflow/repaint.
- Storage: cookies, localStorage, sessionStorage, indexedDB.
Web server responsibilities
- Accept and parse HTTP requests.
- Serve static content (HTML, CSS, JS, images).
- Run server-side code for dynamic content (PHP, Node.js, Python, Java, etc.).
- Manage sessions, authentication, logging and security features.
- Handle load (threads, processes, event loops) and scale (load balancers).
HTTP basics and status
- Common methods: GET (fetch), POST (submit), PUT, DELETE, HEAD.
- Status codes: 2xx success, 3xx redirection, 4xx client error, 5xx server error.
- HTTPS = HTTP over TLS: encrypts traffic, verified by digital certificates.
Security considerations
- Use HTTPS to protect data in transit (prevents eavesdropping and man-in-the-middle attacks).
- Validate and sanitize user input on the server to prevent SQL injection and XSS (cross-site scripting).
- CSRF protection, secure cookies (HttpOnly, Secure, SameSite).
- Keep server and software up to date; use firewalls and least privilege.
Example HTTP exchange (simplified)
GET /index.html HTTP/1.1 Host: example.com User-Agent: MyBrowser/1.0 HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 1254 <!doctype html> <html>...</html>
Key takeaway: Browsers are clients that present web content to users; web servers store and deliver that content and run web applications. The HTTP/HTTPS protocols and related web standards define how they communicate, while security best practices protect data and users.
- Using Google Chrome (browser) to open https://www.wikipedia.org (web server behind the site answers requests and serves the page).
- A company hosting its website on Apache or Nginx (web server software). When a user visits the site, the browser sends an HTTP GET and the server returns HTML/CSS/JS files.
- A mobile app acting as a browser-like client calling a REST API on a web server (e.g., weather app requests data from api.weather.com).
- HTTPS example: logging into Gmail; the browser establishes a TLS connection so username/password and mails are encrypted in transit.
- \[URL structure: protocol://domain[:port]/path?query#fragment\]
- \[Request–Response flow (conceptual): Browser (Client) --HTTP request--> Server --HTTP response--> Browser\]
- \[Latency (simple): Latency ≈ DNS_lookup + TCP_handshake + Server_processing + Transfer_time\]
- \[Throughput (simple): Throughput = Total_bytes_transferred / Total_time_taken\]
- \[Common ports: HTTP = 80\]\[HTTPS = 443\]
URL, Domain Names and IP Addresses
URL, Domain Names and IP Addresses
Key Point: Total IPv4 addresses = 2^32 = 4,294,967,296
Overview: A URL (Uniform Resource Locator) identifies the address of a resource on the web. Domain names are human-readable names that map to numerical IP (Internet Protocol) addresses which identify devices on a network. The Domain Name System (DNS) translates domain names to IP addresses so browsers can locate servers.
URL — Components and types
- Structure (example):
https://sub.example.com:443/path/page.html?search=it#section - Components:
- Protocol: e.g.,
http,https— tells how to access the resource. - Subdomain: e.g.,
sub— optional prefix to organize services (likewww). - Domain name: e.g.,
example.com— the human name of the site. - Port: e.g.,
443— optional, default ports are 80 for HTTP and 443 for HTTPS. - Path: location of a specific resource on the server (folders/files).
- Query string: parameters sent to the server (after
?). - Fragment: client-side anchor (after
#).
- Protocol: e.g.,
- Types: Absolute URLs (full address) and Relative URLs (relative to current location).
Domain Names and DNS
- Domain name structure from right to left:
Top-Level Domain (TLD)>Second-Level Domain (SLD)>subdomain. Example: inmail.google.com,comis TLD,googleis SLD,mailis a subdomain. - DNS is a distributed database that resolves domain names to IP addresses. Typical resolution sequence: resolver → root servers → TLD servers → authoritative name servers → response to client.
- DNS records include A (IPv4 address), AAAA (IPv6 address), CNAME (canonical name), MX (mail exchange), etc.
IP Addresses
- IP identifies devices on networks. Two major versions: IPv4 (32 bits) and IPv6 (128 bits).
- IPv4 format: four octets in dotted decimal, e.g.,
192.168.1.10. Range: 0.0.0.0 to 255.255.255.255 (4,294,967,296 addresses total). - IPv6 format: eight groups of four hexadecimal digits separated by colons, e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334. Much larger address space (2^128 addresses). - Public vs Private IPs: Public IPs are routable on the internet. Private IPs (RFC 1918 ranges like
192.168.x.x,10.x.x.x,172.16.x.x) are used inside local networks and not directly reachable from the internet. - Static vs Dynamic: Static IPs stay constant (useful for servers); dynamic IPs are assigned temporarily by DHCP (common for home devices).
- Subnetting basics: Networks are described with a prefix (CIDR) like
192.168.1.0/24. The/24means the first 24 bits are network bits; remaining bits are host bits.
How it all works together (simple flow)
- User enters
https://www.example.com/pagein browser. - Browser asks the DNS resolver for
www.example.com. - Resolver obtains the IP (e.g.,
93.184.216.34) via DNS servers and returns it. - Browser opens a connection to that IP using the specified protocol (HTTPS > TLS handshake > HTTP GET request).
- Server responds with the resource; browser renders the page.
Security note: URLs beginning with https:// use TLS/SSL to encrypt data between client and server. DNS security (DNSSEC) helps ensure DNS responses are authentic.
Class-level summary: Remember these keywords — URL (location), Domain name (human name), IP address (numeric identifier), DNS (translator). Understanding how they connect helps explain how the web finds and delivers pages.
- URL breakdown: https://subdomain.example.com:8443/articles/index.html?topic=it#part2 — protocol=https, subdomain=subdomain, domain=example.com, port=8443, path=/articles/index.html, query=topic=it, fragment=part2.
- Domain hierarchy: For mail.google.com — 'com' is TLD, 'google' is SLD, 'mail' is subdomain (mail service).
- DNS resolution example: Typing www.example.com → Local resolver checks cache → queries root → queries .com TLD → queries example.com's authoritative DNS → returns A record 93.184.216.34 → browser connects to 93.184.216.34.
- IPv4 private vs public: 192.168.0.5 (private IP inside home Wi‑Fi); router has a public IP assigned by ISP (used on the internet).
- IPv6 example: 2001:0db8::1 is a shortened IPv6 address (consecutive zeros compressed with '::').
- \[Total IPv4 addresses = 2^32 = 4,294,967,296\]
- \[Total IPv6 addresses = 2^128 (vast number, ≈ 3.4 × 10^38)\]
- \[Hosts in an IPv4 subnet (given CIDR /n): host_bits = 32 - n\]\[usable_hosts = 2^(host_bits) - 2 (subtract network & broadcast addresses\]\[apply only to traditional IPv4 subnets).\]
- \[Example: For /24 → host_bits = 8 → usable_hosts = 2^8 - 2 = 254.\]
- \[To convert CIDR to subnet mask: /n → mask has n ones then (32-n) zeros\]\[e.g., /24 → 255.255.255.0.\]
- \[Decimal to binary for an IPv4 octet: octet_decimal → binary of 8 bits (e.g., 192 → 11000000).\]
HTTP and HTTPS
HTTP and HTTPS
Key Point: URL structure: scheme://host[:port]/path[?query][#fragment] e.g., https://www.example.com:443/path?x=1#section
HTTP (HyperText Transfer Protocol)
HTTP is an application-layer protocol used by web browsers and servers to exchange hypertext (web pages) and related resources. It follows a client-server, request-response model and is stateless (each request is independent).
- How it works (basic): The browser (client) sends an HTTP request (method, URL, headers, optional body) to the server; the server responds with a status line, headers and a body (HTML, JSON, images, etc.).
- Common methods: GET (retrieve), POST (submit data), PUT, DELETE, HEAD.
- Common status codes: 200 (OK), 301 (Moved Permanently), 404 (Not Found), 500 (Server Error).
- Default port: 80.
HTTPS (HTTP Secure)
HTTPS is HTTP layered over a cryptographic protocol (TLS/SSL). It provides three main security properties:
- Confidentiality: encrypts data so eavesdroppers cannot read it.
- Integrity: detects tampering of messages.
- Authentication: verifies the server’s identity using a digital certificate issued by a trusted Certificate Authority (CA).
Browsers show HTTPS by a padlock icon and the URL scheme "https://". The default port is 443.
TLS handshake (simplified)
- ClientHello (lists supported cipher suites, TLS version, random nonce).
- ServerHello (selects cipher, sends server certificate containing public key).
- Key exchange — client verifies certificate, then both sides create or exchange information to derive a symmetric session key (e.g., using Diffie–Hellman/ECDHE or RSA).
- Finished — encrypted messages confirm secure channel; subsequent HTTP messages travel inside the encrypted session.
Why HTTPS is preferred
- Protects passwords, payment details and personal data from eavesdropping.
- Prevents attackers from altering content in transit (man-in-the-middle attacks).
- Browsers mark HTTP sites as "Not secure"; search engines and modern web features favour HTTPS.
Practical considerations
- Mixed content: Loading HTTP resources on an HTTPS page breaks security and may be blocked by browsers.
- Performance: TLS adds a handshake cost, but HTTP/2 and TLS optimisations (session resumption, persistent connections) reduce overhead.
- Redirects: Websites commonly redirect http:// URLs to https:// (301 permanent redirect).
Summary: HTTP carries web content; HTTPS carries the same over an encrypted, authenticated channel using TLS/SSL — making web communication secure and trusted.
- Online banking site: all pages and transactions must use HTTPS so account details and passwords are encrypted.
- E-commerce checkout: payment information submitted via HTTPS to protect card numbers and personal data.
- Logging into email: credentials sent over HTTPS to prevent interception and misuse.
- API calls in mobile apps: REST requests to https://api.example.com protect data in transit and authenticate the server.
- Visiting a public news site: while content could be served over HTTP, modern news sites use HTTPS to protect user privacy and avoid tampering.
- \[URL structure: scheme://host[:port]/path[?query][#fragment] e.g.\]\[https://www.example.com:443/path?x=1#section\]
- \[HTTP request-line format: METHOD SP Request-URI SP HTTP-Version e.g.\]\[GET /index.html HTTP/1.1\]
- \[HTTP status-line format: HTTP-Version SP Status-Code SP Reason-Phrase e.g.\]\[HTTP/1.1 200 OK\]
- \[Common ports: HTTP = 80\]\[HTTPS = 443\]
- \[TLS handshake (conceptual flow): ClientHello -> ServerHello + Certificate -> KeyExchange -> Finished -> Encrypted HTTP\]
- \[Conceptual encryption relation: Ciphertext = Encrypt(Plaintext\]\[SessionKey)\]\[Plaintext = Decrypt(Ciphertext\]\[SessionKey)\]
Web Technologies and Tools
Web Technologies and Tools
Key Point: URL structure: protocol://domain:port/path?query#fragment (example: https://www.example.com:443/shop?q=shoes#top)
Overview: Web Technologies and Tools cover the software, protocols and utilities used to create, host, access and secure websites and web applications. Key elements include the client (browser), server, network protocols (HTTP/HTTPS), markup (HTML), styling (CSS), behavior (JavaScript), data exchange formats (JSON, XML), storage (databases), and security measures (SSL/TLS, authentication, input validation).
Core concepts:
- Client–Server model: The browser (client) sends requests to a web server which processes them and returns responses (HTML, JSON, files).
- URLs: Uniform Resource Locator structure: protocol://domain:port/path?query#fragment (e.g., https://example.com:443/search?q=it#results).
- HTTP and HTTPS: HTTP is the protocol for web requests. HTTPS = HTTP + TLS/SSL encryption. Common ports: HTTP 80, HTTPS 443.
- Frontend technologies: HTML for structure, CSS for presentation, JavaScript for interactivity. Frameworks/libraries (React, Vue, Angular) help build rich interfaces.
- Backend technologies: Server-side languages (PHP, Python, JavaScript/Node.js, Java) and web servers (Apache, Nginx). Backends handle business logic, authentication and database queries.
- APIs and AJAX: RESTful APIs return data (often JSON). AJAX/fetch allows webpages to request data asynchronously without reloading the page.
- Databases: Relational (MySQL, PostgreSQL) and NoSQL (MongoDB) store persistent data used by web apps.
- Tools: Code editors/IDEs, browser DevTools (inspect, console, network), version control (Git), FTP/SFTP, CMS (WordPress), and hosting platforms (shared hosting, VPS, cloud services like AWS/GCP).
Security fundamentals:
- Encryption: Use HTTPS (TLS) to protect data in transit.
- Authentication & sessions: Use secure login, session management, and consider two-factor authentication (2FA).
- Input validation & sanitization: Prevent SQL injection and cross-site scripting (XSS) by validating and encoding user input.
- Cookies & same-origin policy: Cookies store session data; set secure and HttpOnly flags. Same-origin policy prevents some cross-site attacks; CSRF tokens mitigate cross-site request forgery.
- Backups & updates: Keep software updated and maintain regular backups to reduce risk from vulnerabilities and data loss.
How it works together (request–response flow):
- User types URL or clicks link → browser resolves domain via DNS → browser opens a TCP connection to server (TLS handshake if HTTPS) → browser sends HTTP request (GET/POST) → server processes request and may query database or API → server sends back HTTP response with status code and content → browser renders page and may run JavaScript to fetch more data asynchronously.
Practical classroom tips: Use browser DevTools to inspect HTML/CSS/JS and network calls; validate HTML/CSS using online validators; test form input and see how requests appear in the Network tab; check padlock for HTTPS; practice deploying a simple site via GitHub Pages or a basic hosting provider.
- Online banking: The browser connects via HTTPS to the bank server; TLS encrypts data, the server authenticates the user, and API calls show account balance. Cookies and secure session tokens maintain a logged-in state.
- E-commerce product page: HTML/CSS renders layout, JavaScript loads product reviews via AJAX (fetching JSON from an API), and the checkout uses POST requests to send order details to the server which stores them in a database.
- Google Maps embedding: A web page calls Google Maps API (a REST API) to display maps and markers; API key authenticates requests and data is returned as JSON.
- Content management with WordPress: WordPress (a CMS) provides a backend UI for authors; it runs on a web server connected to a MySQL database and serves pages to visitors.
- Using browser DevTools: Inspect element to change CSS temporarily, view Network tab to see resources loaded, examine response codes (200 OK, 404 Not Found, 500 Server Error).
- \[URL structure: protocol://domain:port/path?query#fragment (example: https://www.example.com:443/shop?q=shoes#top)\]
- \[Average response time (ms) = (Sum of response times) / (Number of requests)\]
- \[Bandwidth (bytes/sec) = Data size (bytes) / Time (seconds)\]
- \[Availability (%) = (Uptime / Total time) × 100\]
- \[Common HTTP status code groups: 1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error\]
Web Forms and Data Handling
Web Forms and Data Handling
Key Point: Total storage needed (bytes) = number_of_records × average_record_size (bytes)
What is a Web Form?
A web form is an HTML page element that collects input from users (text, choices, files) and sends it to a server to be processed or stored. Web forms are the primary interface for user interaction on websites.
Common form elements
- input types: text, password, email, number, date, file, checkbox, radio, hidden
- textarea for multi-line text
- select (drop-down) and option
- button / submit to send data
Important attributes
action: URL where form data is sentmethod: HTTP method —GET(data in URL) orPOST(data in request body)enctype: encoding type (usemultipart/form-datafor file uploads)name,id,value,placeholder,required,maxlength,pattern
Basic form submission flow
- User fills form and clicks Submit
- Browser validates client-side rules (HTML5, JavaScript)
- Browser sends HTTP request (GET/POST) to the server
actionURL - Server receives, performs server-side validation and sanitization
- Server stores data (database/file) and returns a response (success/failure)
- Client displays response to user (redirect, message)
Client-side vs Server-side validation
- Client-side (HTML5 attributes, JavaScript) improves user experience and reduces invalid requests but can be bypassed.
- Server-side validation is mandatory for security — never trust client data.
Data handling & storage
- Form data is parsed on the server and typically stored in a database (e.g., MySQL, SQLite) or saved to files.
- Common operations: INSERT new records, SELECT to read, UPDATE to change, DELETE to remove.
- Sanitization and prepared statements (parameterized queries) prevent SQL injection attacks.
Security concerns & best practices
- Use HTTPS to protect data in transit.
- Validate and sanitize all inputs on the server.
- Use prepared statements or ORM to avoid SQL injection.
- Implement CSRF tokens to prevent cross-site request forgery.
- Use CAPTCHA to stop automated spam submissions when appropriate.
- Store passwords hashed (e.g., bcrypt) not in plain text.
Accessibility & usability
- Use labels linked to inputs (
<label for="id">) for screen readers. - Provide clear placeholders, error messages, and logical tab order.
- Minimize required fields and use inline validation for better completion rates.
Small example (HTML snippet)
<form action="/submit" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name" required maxlength="50" /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <button type="submit">Send</button> </form>
Summary
Web forms are the entry point for collecting user data. Proper form design, client- and server-side validation, secure data handling, and good UX/accessibility are essential parts of web applications.
- Contact form on a company website (name, email, message) — used to send queries to support teams.
- User registration form for an online portal (username, email, password, profile picture) — stores account data in a database; passwords are hashed.
- Online order/checkout form (items, quantity, billing/shipping address, payment info) — sensitive data handled over HTTPS and payment via secure gateways.
- Feedback/survey forms (ratings, comments, multiple-choice) — analyze responses for improvements.
- File upload form for assignments or resumes — uses enctype="multipart/form-data" and server-side checks for file type and size.
- \[Total storage needed (bytes) = number_of_records × average_record_size (bytes)\]
- \[Average submission time (seconds) = total_time_taken_for_all_submissions / number_of_submissions\]
- \[Completion rate (%) = (completed_submissions / started_forms) × 100\]
- \[Basic SQL operations (examples): INSERT: INSERT INTO students(name\]\[email) VALUES('Asha', 'asha@example.com')\]\[SELECT: SELECT name\]\[email FROM students WHERE id = 1\]\[UPDATE: UPDATE students SET email = 'new@example.com' WHERE id = 1\]\[DELETE: DELETE FROM students WHERE id = 1\]
Databases and Web Applications
Databases and Web Applications
Key Point: Basic SQL examples: SELECT name, grade FROM students WHERE grade = 'A'; INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com'); UPDATE products SET stock = stock - 1 WHERE id = 101; DELETE FROM sessions WHERE expires < NOW();
What is a Database?
A database is an organized collection of data stored and accessed electronically. In web applications, databases store users, products, transactions, logs and other persistent data. Common types: relational (tables with rows & columns) and NoSQL (key-value, document, graph).
Core concepts (relational)
- Table: collection of records (rows).
- Field/Column: attribute (e.g., name, id, price).
- Record/Row: one item/entry in a table.
- Primary Key: unique identifier for a record.
- Foreign Key: field that links to a primary key in another table.
- Relationships: one-to-one, one-to-many, many-to-many.
- Normalization: organizing tables to reduce redundancy (1NF, 2NF, 3NF).
Web Application Architecture (how DB and web apps interact)
- Client (Browser/App): sends requests (HTTP) and displays responses.
- Web Server: handles HTTP requests (e.g., Apache, Nginx).
- Application Server / Backend: runs server-side code (PHP, Node.js, Python) that implements business logic, interacts with the database, and returns responses.
- Database Server: stores and retrieves data on request (MySQL, PostgreSQL, MongoDB).
Typical flow: client sends request → web/app server processes it → backend runs queries on the database → DB returns data → backend formats response → client receives result.
CRUD and SQL
Web apps perform CRUD operations mapped to SQL statements:
- Create: INSERT
- Read: SELECT
- Update: UPDATE
- Delete: DELETE
Example SQL patterns are shown below (in examples/formulas).
Transactions & ACID
When multiple related database operations must succeed together, they are wrapped in a transaction. ACID properties:
- Atomicity: all or nothing.
- Consistency: DB moves from one valid state to another.
- Isolation: concurrent transactions don’t interfere.
- Durability: once committed, changes persist.
Performance features
Indexing speeds up lookups; caching (e.g., Redis) reduces repeated DB reads; connection pooling reuses DB connections to reduce overhead.
Security principles for web apps & databases
- Encryption (HTTPS/TLS): protect data in transit.
- Hashing & Salting: store passwords with a strong hash (bcrypt, Argon2) and a unique salt.
- Authentication & Authorization: verify identity and limit access (roles, permissions).
- Input Validation & Output Encoding: prevent malformed input and cross-site scripting (XSS).
- SQL Injection Prevention: use parameterized queries / prepared statements, avoid string concatenation for queries.
- Least Privilege: DB users should have only required permissions.
- Backups & Replication: regular backups and replicas for availability and disaster recovery.
Common web-to-DB connection example
// Pseudocode (server-side)
openConnection();
preparedStatement("SELECT * FROM users WHERE email = ?");
bindParameter(1, userEmail);
execute();
closeConnection();
Summary
Databases are the persistent storage for web applications. Building robust web apps requires correct database design (tables, keys, normalization), safe query handling (prepared statements, transactions), attention to performance (indexes, caching), and strong security (encryption, validation, access control). Understanding the request-response flow and how CRUD maps to SQL is central to building functional and secure web applications.
- Online shopping site: Product table, User table, Orders table; checkout form triggers INSERT into Orders and UPDATE of product stock within a transaction.
- School management system: Student, Class, Marks tables; teachers submit marks via forms which run INSERT/UPDATE and reports use JOINs for consolidated views.
- Banking app: Accounts and Transactions tables; transfers require ACID transactions to debit one account and credit another atomically.
- Library system: Books, Members, BorrowRecords; foreign keys link borrow records to members and books; overdue logic runs periodic queries.
- Social media: Users, Posts, Comments tables; feeds produced by querying and joining posts and user data; caching used for often-read posts.
- \[Basic SQL examples: SELECT name\]\[grade FROM students WHERE grade = 'A'\]\[INSERT INTO users (name\]\[email) VALUES ('Asha', 'asha@example.com')\]\[UPDATE products SET stock = stock - 1 WHERE id = 101\]\[DELETE FROM sessions WHERE expires < NOW()\]
- \[JOIN example: SELECT o.id\]\[u.name\]\[o.total FROM orders o JOIN users u ON o.user_id = u.id WHERE o.date > '2025-01-01'\]
- \[Prepared statement pattern (placeholder shown): PREPARE stmt FROM 'SELECT * FROM users WHERE email = ?'\]\[EXECUTE stmt USING @email\]
- \[Database size estimate: Total DB size ≈ (average record size in bytes) × (number of records).\]
- \[Average response time = (sum of all response times) / (number of requests).\]
- \[Throughput (requests per second) = total requests / total time (seconds).\]
Session Management and Cookies
Session Management and Cookies
Key Point: Cookie header example format: Set-Cookie:
Overview: Session management and cookies are techniques web applications use to remember information about a user between HTTP requests. HTTP is a stateless protocol — the server does not automatically remember previous requests — so sessions and cookies provide a way to maintain state (e.g., login status, shopping cart contents, preferences).
Cookies (client-side)
- Definition: A small piece of data (name=value) stored by the browser and sent to the server with subsequent requests to the same domain.
- Structure: A cookie has a name, value and optional attributes like Expires/Max-Age, Domain, Path, Secure, HttpOnly, SameSite.
- Types:
- Session cookie: Lives only for the browser session and is deleted when the browser closes (no Expires/Max-Age).
- Persistent cookie: Stored until a set expiry time (has Expires or Max-Age).
- First-party vs Third-party: Depends on which domain set/read the cookie.
- Example cookie header (from server to browser):
Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600
Sessions (server-side)
- Definition: Server-side storage of user-specific data. The server creates a session record and gives the client a session identifier (usually stored in a cookie).
- How it works (basic flow):
- User logs in → server creates a session object (data store) and generates a unique session ID.
- Server sends session ID to the browser (commonly via a cookie).
- Browser sends the session ID cookie with each subsequent request; server looks up the session ID and retrieves user state.
Security concerns and countermeasures
- Session hijacking (stealing session ID): Mitigate by using Secure (only over HTTPS), HttpOnly (not accessible to JavaScript), SameSite attributes, short session timeouts, and regenerating session IDs on login.
- Cross-Site Scripting (XSS): Prevent by input validation and HttpOnly cookies so scripts cannot read cookie values.
- Cross-Site Request Forgery (CSRF): Use SameSite cookies and CSRF tokens for state-changing requests.
- Logout & invalidation: On logout, server must invalidate the session and instruct the browser to delete the cookie.
When to use cookies vs sessions: Use cookies for small client-side preferences (language, theme). Use sessions for sensitive data or larger server-side state (authentication, shopping cart contents). Cookies may store only the session ID, not secret user data.
Best practices summary:
- Use HTTPS for all pages that use authentication cookies.
- Set HttpOnly and Secure flags for authentication cookies.
- Set SameSite attribute to reduce CSRF risk.
- Regenerate session ID after login and on privilege changes.
- Use reasonable session timeout values and explicit logout behavior.
- E-commerce shopping cart: When you add items to a cart without logging in, the site creates a session (server-side) and stores the cart items in that session. The browser keeps a cookie with the session ID. When you return within the session, the server uses the ID to show your cart.
- "Remember me" on a login form: A persistent cookie stores a token tied to your account so the site keeps you logged in across browser restarts. The server checks the token and issues a fresh session if valid.
- Language or theme preference: The site stores your chosen language or theme in a cookie (persistent) so the page loads with your preference on subsequent visits.
- Analytics: First-party cookies can store a unique visitor id so analytics systems count returning visitors separately from new ones.
- Single Sign-On (SSO): A central authentication server issues a session cookie; other applications trust that session when the browser presents the cookie.
- \[Cookie header example format: Set-Cookie: <name>=<value>\]\[Expires=<date>\]\[Max-Age=<seconds>\]\[Domain=<domain>\]\[Path=<path>\]\[Secure\]\[HttpOnly\]\[SameSite=<Lax|Strict|None>\]
- \[Session timeout check (conceptual): expired = (lastActivityTimestamp + timeoutInterval) < currentTimestamp\]
- \[Persistent cookie expiry timestamp: expiryTimestamp = currentTimestamp + Max-Age (seconds)\]
- \[Session lifecycle (pseudo-steps): createSession(user) -> sessionId = generateUniqueId() -> storeServer(sessionId\]\[data) -> setCookie('sessionId'\]\[sessionId) -> onRequest: data = getServer(sessionId)\]
Hosting, Deployment and FTP
Hosting, Deployment and FTP
Key Point: File transfer time (approx) = File size (bits) / Bandwidth (bits per second). Example: 100 MB (~800 Mb) on a 10 Mbps link takes ~80 seconds.
Overview
Hosting, deployment and FTP are core concepts for making a website or web application available on the Internet and maintaining it. Hosting is where your site files live; deployment is the process of moving your application from development to a live environment; FTP is one traditional protocol used to transfer files to the host.
Hosting
Web hosting is the service that stores website files (HTML, CSS, images, scripts) on a server connected to the Internet. When a user types your domain name, DNS points to the hosting server and the server delivers the site to the user.
- Types of hosting: shared hosting (many sites on one server), VPS (virtual private server — a partitioned environment), dedicated server (entire physical server), cloud hosting (scalable resources across multiple machines), and managed hosting (provider handles maintenance).
- Key hosting components: storage, CPU, memory (RAM), bandwidth, IP address, control panel (cPanel, Plesk) and database support (MySQL, PostgreSQL).
Deployment
Deployment is the sequence of steps to move an application from development to production. It can be manual or automated (CI/CD). Typical steps:
- Build: compile or package code (minify, bundle assets).
- Test: run automated tests (unit, integration).
- Stage: deploy to a staging environment for final review.
- Release/Deploy: move to production server and update DNS if needed.
- Monitor: check uptime, logs and performance; roll back if needed.
Modern deployment methods include FTP/FTPS/SFTP uploads, Git-based deploys, container-based deployment (Docker), platform services (GitHub Pages, Netlify) and cloud platforms (AWS, Azure, Google Cloud).
FTP (File Transfer Protocol)
FTP is a protocol for transferring files between a client and a server over TCP/IP. Basic FTP is unencrypted; secure alternatives are FTPS (FTP over TLS) and SFTP (SSH File Transfer Protocol). FTP commonly uses port 21 (control) and a secondary port for data (varies by active/passive mode).
Common FTP operations: connect, login (username/password), list files (ls or dir), upload (put), download (get), change directory (cd), remove files (rm).
Security and Best Practices
- Prefer SFTP or FTPS over plain FTP to protect credentials and data.
- Use strong passwords, SSH keys, and restrict access by IP where possible.
- Keep server software and CMS plugins updated; use least-privilege file permissions.
- Use backups and a rollback plan for deployment failures.
When to use what
- Small static sites: GitHub Pages, Netlify, or shared hosting (simple deployment).
- Dynamic sites (databases): VPS, managed hosting or cloud with database support.
- Highly scalable apps: cloud services with autoscaling (AWS/GCP/Azure) or container orchestration (Kubernetes).
- School website on shared hosting: A small school buys a shared hosting plan, uploads HTML/CSS files via SFTP and points their domain to the host. This is low-cost and easy to manage.
- Updating a WordPress site using FTP: An administrator edits a theme file locally and uses an FTP client (FileZilla) to upload the changed file to /public_html/wp-content/themes/yourtheme/ to apply the change.
- Deploying a web app with Git and CI/CD: Developers push code to GitHub. A CI pipeline builds and tests the app, then deploys automatically to a cloud service (e.g., Netlify, Heroku or AWS Elastic Beanstalk) on success.
- Using SFTP for secure file transfer: A company uses SFTP (SSH keys) to transfer customer reports nightly to a production server. This avoids sending credentials in plaintext.
- Scaling with cloud hosting: An e-commerce site uses cloud hosting with auto-scaling so extra servers launch during sales traffic spikes, then scale down afterward to save cost.
- \[File transfer time (approx) = File size (bits) / Bandwidth (bits per second)\]\[Example: 100 MB (~800 Mb) on a 10 Mbps link takes ~80 seconds.\]
- \[Uptime percentage = (Total time - Downtime) / Total time × 100\]\[Example: 99.9% uptime ≈ max 43.2 minutes downtime per month.\]
- \[Bandwidth usage (per month) = Average page size × Page views × (1 + overhead factor) — useful to estimate hosting bandwidth needs.\]
- \[Estimated monthly hosting cost = Base plan cost + (extra storage × unit price) + (extra bandwidth × unit price).\]
- \[Common FTP commands (like short 'formulas'): USER username (login)\]\[PASS password (authenticate)\]\[LIST or NLST (list files)\]\[CWD pathname (change directory)\]\[PUT localfile remotefile (upload)\]\[GET remotefile localfile (download)\]\[DEL filename (delete).\]
E‑commerce and Online Transactions
E‑commerce and Online Transactions
Key Point: Conversion rate (%) = (Number of purchases / Number of site visits) × 100
What is E‑commerce? E‑commerce (electronic commerce) is buying and selling goods and services or transferring funds and data over electronic networks, primarily the Internet. It includes online stores, marketplaces, mobile apps and digital payment services.
Types / Models
- B2C (Business to Consumer): e.g., Amazon, Flipkart.
- B2B (Business to Business): manufacturers selling to retailers, e.g., IndiaMART.
- C2C (Consumer to Consumer): eBay, OLX.
- C2B (Consumer to Business): freelancers bidding to companies.
- G2C / C2G (Government and Citizen): online tax filing, e‑governance portals.
Components of an Online Transaction
- Buyer (customer) — selects items and initiates payment.
- Merchant (seller) — lists products/services and receives payment.
- Payment Gateway — securely transmits card/UPI data to banks.
- Acquirer Bank (merchant's bank) and Issuer Bank (cardholder's bank).
- Card Networks / Switches (Visa, Mastercard, NPCI/UPI) — route authorization.
- Settlement & Clearing — funds move from buyer's bank to merchant's account.
Typical Steps in an Online Payment
- Customer places order, proceeds to checkout.
- Customer provides payment details (card/UPI/wallet).
- Payment gateway encrypts data and sends authorization request to acquirer.
- Acquirer forwards to card network / switch, which contacts issuer bank.
- Issuer authenticates (OTP/3D Secure/biometric) and approves/declines.
- Response sent back to merchant; if approved, order is confirmed.
- Capture & settlement occur later: funds transferred to merchant after fees.
Security Measures & Standards
- HTTPS with SSL/TLS — encrypts data in transit.
- Digital Certificates / PKI — verify server identity.
- Two‑Factor Authentication (2FA) / OTP / 3D Secure — user authentication.
- Tokenization — replaces card data with tokens to limit exposure.
- End‑to‑End Encryption — sensitive data never stored in plain text.
- PCI DSS compliance — security standards for storing/processing card data.
- Fraud detection — pattern analysis, velocity checks, device fingerprinting.
Advantages: convenience, 24×7 availability, wider reach, price comparisons, digital records.
Challenges: fraud, privacy breaches, delivery/logistics, return management, digital divide.
Legal & Ethical Considerations: consumer protection (refunds, cancellations), data privacy (consent, storage), transparency in pricing, complying with local laws (GST, e‑commerce rules).
Practical Tips for Safe Online Transactions
- Use websites/apps with HTTPS lock icon and valid certificate.
- Prefer reputed payment methods (bank UPI apps, verified wallets, card with 3D Secure).
- Enable 2FA, avoid saving card details on unknown sites.
- Check bank SMS/email confirmations and reconciliations regularly.
Concept summary: E‑commerce combines online storefronts, secure payment systems and backend banking networks. Strong encryption, authentication and regulatory compliance ensure safe, reliable online transactions.
- Amazon (B2C): Customer orders a book online, pays with card/UPI, payment gateway authorizes and the seller ships the book.
- Flipkart (Marketplace): Marketplace lists seller products; payment is routed through Flipkart's gateway and settled to seller after fees.
- Paytm / Google Pay / PhonePe (Payments/Wallets & UPI): Instant peer‑to‑peer transfers and merchant payments using UPI or wallet balance.
- eBay / OLX (C2C): Individuals list used items; buyer pays via integrated payment or escrow service.
- Ola / Uber (On‑demand services): Customer books a ride, pays via card/UPI/wallet; platform facilitates payment and commissions.
- Government portals (G2C): Online tax payment or utility bill payment through secure government gateways.
- \[Conversion rate (%) = (Number of purchases / Number of site visits) × 100\]
- \[Average Order Value (AOV) = Total revenue / Number of orders\]
- \[Cart abandonment rate (%) = (1 - Purchases / Carts started) × 100\]
- \[Transaction success rate (%) = (Successful transactions / Total transaction attempts) × 100\]
- \[Fraud rate (%) = (Fraudulent transactions / Total transactions) × 100\]
- \[Payment gateway fee = Transaction_amount × fee_percentage + fixed_fee\]
Common Security Threats
Common Security Threats
Key Point: Risk = Likelihood × Impact — a simple risk assessment formula to prioritise which threats to address first.
Overview
Common security threats are actions or events that can harm computer systems, data, users or services on the internet. They exploit weaknesses in software, networks or human behavior to steal data, disrupt services, or damage systems. Understanding them helps users and administrators reduce risk.
Major types of threats
- Malware — Malicious software such as viruses (attach to files), worms (self-replicate across networks) and trojans (disguised as useful programs). Malware can steal, corrupt or encrypt data.
- Ransomware — A type of malware that encrypts files and demands payment for the decryption key. It can paralyze organizations.
- Phishing — Fraudulent messages (emails, SMS) that trick users into revealing sensitive information (passwords, card details) or clicking malicious links.
- Social engineering — Manipulating people into revealing confidential information or performing actions (e.g., pretexting, impersonation).
- Man-in-the-Middle (MitM) — An attacker intercepts communication between two parties (e.g., on unsecured public Wi‑Fi) to eavesdrop or alter messages.
- Injection attacks — Improperly validated input allows attackers to insert malicious commands. Examples: SQL Injection (database queries) and Cross-Site Scripting (XSS) which run malicious scripts in a user’s browser.
- Distributed Denial of Service (DDoS) — Overwhelming a website or service with traffic from many compromised devices, making it unavailable to legitimate users.
- Password attacks — Techniques such as brute force, dictionary attacks or credential stuffing to guess or reuse passwords and gain unauthorized access.
- Spyware and adware — Programs that secretly monitor user activity or display unwanted ads, often compromising privacy.
How threats work (high level)
Threats exploit vulnerabilities (weaknesses) in systems or humans. An attacker finds a vulnerability, delivers a payload (malware, malicious input, fake message), and achieves an impact (data theft, service outage, financial loss). Effective security adds layers (patches, authentication, education) to break this chain.
Common mitigations
- Keep software and operating systems up to date (patch vulnerabilities).
- Use strong, unique passwords and enable multi-factor authentication (MFA).
- Install reputable antivirus/endpoint protection and enable firewalls.
- Validate and sanitize user inputs on web applications to prevent injection attacks.
- Use HTTPS and VPNs on public networks to protect against MitM attacks.
- Back up important data regularly and keep offline copies to recover from ransomware.
- Educate users to recognize phishing and social engineering attempts.
Why this matters for students
Students use web apps, email, cloud drives and school networks. Awareness of common threats helps protect personal data (projects, photos), avoid scams, and use the internet responsibly.
- Phishing email that appears to be from a bank asking a student to ‘verify’ their account — the student enters credentials on a fake site and the attacker steals the login.
- Ransomware attack on a small clinic: patient records encrypted and the clinic forced to use backups or pay ransom to restore service.
- SQL Injection on a website’s login form where an attacker inputs ' OR '1'='1 to bypass authentication and access user accounts (illustrates why input validation is necessary).
- Man-in-the-Middle on public Wi‑Fi: attacker intercepts unencrypted traffic and captures session cookies, allowing access to a user’s account.
- DDoS attack on an online game server that floods the server with traffic, making it impossible for players to connect.
- \[Risk = Likelihood × Impact — a simple risk assessment formula to prioritise which threats to address first.\]
- \[Probability of guessing a password (uniform random): P = 1 / N^L where N = size of character set (e.g., 26 lowercase + 26 uppercase + 10 digits = 62) and L = password length.\]
- \[Password entropy (bits) ≈ L × log2(N) — higher entropy means stronger password\]\[Time to brute-force ≈ (2^entropy) / attempts_per_second.\]
Web Application Vulnerabilities and Attacks
Web Application Vulnerabilities and Attacks
Key Point: Risk (qualitative) = Likelihood x Impact. Used to prioritize which vulnerabilities to fix first.
Introduction
Web application vulnerabilities are weak points in websites or web services that attackers can exploit to gain unauthorized access, steal data, modify content, or disrupt services. Understanding common vulnerabilities and how attacks work helps developers, administrators, and users reduce risk.
Common Vulnerabilities (high-level)
- Broken Authentication and Session Management: Poor login, password storage, or session handling lets attackers impersonate users.
- Cross Site Scripting (XSS): When an application includes untrusted input in web pages without proper encoding, an attacker can inject scripts that run in other users browsers.
- SQL Injection: If user input is concatenated directly into database queries, attackers can manipulate queries to read or change data.
- Cross Site Request Forgery (CSRF): An attacker tricks a logged-in user into submitting unwanted actions to a web application.
- Insecure Direct Object References: Predictable references to files, database records, or IDs allow access to resources that should be protected.
- Unvalidated File Uploads: Allowing arbitrary files or executable content to be uploaded can enable remote code execution.
- Security Misconfiguration: Default settings, exposed admin interfaces, or old libraries can create vulnerabilities.
How Attacks Work (conceptual)
Attackers look for input points (forms, URLs, headers) and try to manipulate input to change application behavior. Successful attacks often follow stages: discovery (scan), exploitation (use input to trigger vulnerability), escalation (gain more access), and persistence or data exfiltration.
Safe Examples of Bad vs Good Code Practices
Unsafe pattern (conceptual)
query = "SELECT * FROM users WHERE name = '" + user_input + "'"
Safer pattern using parameterized queries or prepared statements (conceptual)
statement = db.prepare("SELECT * FROM users WHERE name = ?")
statement.execute(user_input)Note: Do not attempt to exploit vulnerabilities. Learn and apply secure coding and configuration practices.
Prevention and Best Practices
- Validate and sanitize all input on server side; escape output in HTML contexts.
- Use parameterized queries or ORM APIs to avoid SQL injection.
- Implement proper authentication, multi factor authentication where possible, and secure session handling.
- Use Content Security Policy (CSP) and input encoding to mitigate XSS.
- Use anti CSRF tokens and check Referer/Origin headers for state-changing requests.
- Keep software and libraries up to date; remove unused features and close admin interfaces.
- Perform regular security testing: code review, static analysis, and penetration testing.
Summary
Web application security combines secure design, careful coding, correct configuration, and regular testing. Awareness of common vulnerabilities and adoption of simple defenses protect users and data.
- MySpace Samy worm (2005) - a cross site scripting (XSS) worm that spread by injecting JavaScript into profile pages.
- TalkTalk data breach (2015) - attackers exploited weaknesses in a web application to access customer data, widely reported as involving SQL injection style flaws.
- Equifax breach (2017) - attackers exploited a known Apache Struts vulnerability in a web application framework to gain access to sensitive consumer records.
- \[Risk (qualitative) = Likelihood x Impact\]\[Used to prioritize which vulnerabilities to fix first.\]
- \[Password entropy approximation = L * log2(N) where L is password length and N is size of character pool\]\[Higher entropy means harder to guess.\]
- \[Estimated brute force attempts needed = 2^(entropy)\]\[Time to crack approx = 2^(entropy) / attempts_per_second.\]
Authentication and Authorization
Authentication and Authorization
Key Point: Password entropy (bits) ≈ L × log2(N), where L = password length, N = size of character pool (e.g., 26 for lowercase letters).
Overview
Authentication and authorization are two fundamental concepts in computer security that control who you are and what you are allowed to do.
Authentication
Authentication is the process of verifying the identity of a user or system. It answers the question: "Are you really who you claim to be?" Common authentication factors are:
- Something you know — passwords, PINs.
- Something you have — smart card, security token, mobile phone for OTP.
- Something you are — biometrics like fingerprint, face, iris.
Stronger authentication uses two or more factors (Multi-Factor Authentication, MFA). Authentication typically involves steps: identify (enter username), authenticate (prove identity), and establish a session (receive a session token or cookie).
Authorization
Authorization happens after authentication and determines what an authenticated user may do. It answers the question: "What resources can this user access and what actions can they perform?" Authorization mechanisms include:
- Role-Based Access Control (RBAC) — users are assigned roles (e.g., student, teacher, admin) and roles have permissions.
- Access Control Lists (ACL) — lists that specify which users or groups can access a resource and with what permissions (read, write, execute).
- Discretionary and Mandatory Controls — discretionary (owner decides), mandatory (policy enforced centrally).
How they work together
Typical sequence in a web application:
- User provides credentials (authentication).
- Server verifies credentials and issues a session token or cookie.
- For each request, the server checks the token and then checks the user's permissions to decide if the action is allowed (authorization).
Security considerations and best practices
- Use HTTPS to protect credentials in transit.
- Enforce strong password policies and limit login attempts to reduce brute-force attacks.
- Use MFA where possible to reduce dependence on passwords.
- Implement the principle of least privilege — give users only the access they need.
- Expire sessions after inactivity and revoke tokens on logout.
Examples in everyday life
- ATM: card (something you have) + PIN (something you know) — authentication; withdrawal limits and account access rules — authorization.
- Smartphone unlock: fingerprint or face (biometric authentication); apps may have permission settings (authorization).
- School computer lab: students login with ID/password (authentication); only teachers can install software (authorization via roles).
Summary
Authentication proves identity; authorization grants or denies permission. Both are essential for secure web applications.
- Email login: username + password (authentication); ability to read/write particular folders is authorization.
- ATM machine: card + PIN for authentication; daily withdrawal limit and access to only own accounts is authorization.
- Mobile phone: fingerprint unlock for authentication; app permissions (camera, contacts) are authorization settings.
- School website: student, teacher, admin roles. After login (authentication), role determines pages and actions available (authorization).
- Corporate VPN: certificate or token for authentication; access to internal servers is controlled by authorization policies.
- \[Password entropy (bits) ≈ L × log2(N)\]\[where L = password length\]\[N = size of character pool (e.g., 26 for lowercase letters).\]
- \[Time to brute-force ≈ 2^{entropy} / attempts_per_second\]\[Use this to estimate resistance to guessing attacks.\]
- \[Biometric error measures: False Acceptance Rate (FAR) = (false accepts) / (total impostor attempts)\]\[False Rejection Rate (FRR) = (false rejects) / (total genuine attempts)\]\[Equal Error Rate (EER) is where FAR = FRR and is used to compare sensors.\]
- \[Session lifetime policy: Expiry_time = Login_time + Session_timeout (set by server\]\[shorter timeout reduces risk of hijacking).\]
Encryption, SSL/TLS and Certificates
Encryption, SSL/TLS and Certificates
Key Point: General encryption/decryption: Ciphertext = E(Key, Plaintext); Plaintext = D(Key, Ciphertext)
What is Encryption?
Encryption is the process of converting readable information (plaintext) into a scrambled form (ciphertext) so that only authorized parties can read it. It protects confidentiality and integrity of data sent over networks or stored on devices.
Two main types of encryption
- Symmetric (Secret-key) Encryption: Same secret key is used to encrypt and decrypt. Fast and used for bulk data. Example algorithms: AES.
- Asymmetric (Public-key) Encryption: Uses a key pair: a public key (shared openly) to encrypt and a private key (kept secret) to decrypt. Useful for secure key exchange, digital signatures. Example algorithms: RSA, ECC.
How asymmetric and symmetric work together
Because public-key operations are slower, systems usually use asymmetric encryption to securely exchange a short symmetric session key, and then use that symmetric key to encrypt the rest of the communication.
What is SSL/TLS?
SSL (Secure Sockets Layer) and its successor TLS (Transport Layer Security) are protocols that create a secure channel between a web browser and a web server. When you see "https://" and a padlock in the browser, TLS is protecting the data exchanged.
TLS purpose: Confidentiality (encryption), integrity (detect tampering), and authentication (confirming server identity).
Simple TLS handshake (high level)
- ClientHello: Browser sends supported protocol versions, cipher suites, and a random value.
- ServerHello: Server picks protocol/cipher, sends its random value and its digital certificate (contains server's public key).
- Certificate verification: Client checks certificate is valid and signed by a trusted Certificate Authority (CA).
- Key exchange: Client uses server's public key (or uses ephemeral Diffie–Hellman) to securely create a shared symmetric session key.
- Finished messages: Both sides confirm keys and start encrypted communication using the session key (symmetric encryption).
What is a Digital Certificate?
A digital certificate (often an X.509 certificate) is a document issued by a Certificate Authority (CA) that binds a public key to the identity of an entity (for example, a website). It contains the subject (owner), issuer (CA), validity dates, public key, serial number, and the CA's digital signature.
Certificate Authority (CA) and Chain of Trust
A CA is a trusted organization that signs certificates. Browsers come with a list of trusted root CAs. A certificate may be signed directly by a root CA or by an intermediate CA, creating a chain of trust up to a trusted root.
How certificates help security
When the browser verifies a certificate signature using a CA's public key, it gains proof the server really owns the public key in the certificate and that the certificate was issued by a trusted authority. This prevents impersonation (spoofing) and man-in-the-middle attacks.
Everyday examples
Online banking, e-commerce checkouts, social media logins, email over TLS, messaging apps using end-to-end encryption — all rely on encryption and certificates to protect data.
Important notes for Class 10 level
- Encryption scrambles data; decryption recovers it with the right key.
- Public & private keys form a pair: what one encrypts only the other can decrypt.
- SSL is the older name; TLS is the modern, secure version used today.
- Always check for the padlock and correct site address before giving sensitive information online.
- HTTPS website: When you visit https://www.bankexample.com, TLS encrypts the information you send (passwords, account details) so attackers cannot read it.
- Secure email: Many email services use TLS to encrypt the connection between mail servers so messages are protected while in transit.
- Messaging apps: Apps like WhatsApp use end-to-end encryption (a form of public-key + symmetric encryption) so only sender and receiver can read messages.
- VPN: A Virtual Private Network encrypts all your internet traffic between your device and the VPN server, protecting it on public Wi‑Fi.
- \[General encryption/decryption: Ciphertext = E(Key\]\[Plaintext)\]\[Plaintext = D(Key\]\[Ciphertext)\]
- \[Symmetric example (concept): C = E(Ks\]\[M) and M = D(Ks\]\[C) where Ks is symmetric key\]
- \[Asymmetric (RSA\]\[simplified): C = m^e mod n\]\[m = C^d mod n (m = message\]\[(e,n) public key\]\[d private exponent)\]
- \[Diffie–Hellman shared secret (concept): Shared = g^(a⋅b) mod p (each party computes using their secret exponent)\]
- \[TLS idea: Use asymmetric method to securely exchange a random session key Ks\]\[then use symmetric encryption with Ks for bulk data\]
Digital Signatures and Non‑repudiation
Digital Signatures and Non‑repudiation
Key Point: H = Hash(message) // example: SHA‑256(message)
What is a Digital Signature?
A digital signature is an electronic equivalent of a handwritten signature that proves the origin and integrity of a digital message or document. It uses cryptographic techniques (asymmetric key cryptography + hashing) to provide authentication, integrity and non‑repudiation.
Key properties
- Authentication: Verifies the identity of the sender.
- Integrity: Ensures the message has not been altered.
- Non‑repudiation: Prevents the sender from denying they sent the message.
How it works (step by step)
- Sender computes a hash of the message: H = Hash(message) (e.g., SHA‑256).
- Sender encrypts the hash using their private key to produce the digital signature: S = Sign_private(H).
- Sender sends the message and the signature (and usually their public certificate) to the recipient.
- Recipient computes the hash of the received message: H2 = Hash(received message).
- Recipient decrypts the signature using the sender's public key to recover the signed hash: H1 = Verify_public(S).
- If H1 == H2, the signature is valid (message origin and integrity confirmed).
Role of PKI and Certificates
Public Key Infrastructure (PKI) and Certificate Authorities (CAs) bind a public key to an identity through digital certificates. Certificates help recipients trust that a given public key belongs to the claimed sender.
Non‑repudiation explained
Non‑repudiation means the sender cannot later deny having sent the message because only they hold the private key that created the signature. Time‑stamping and secure key management strengthen non‑repudiation (prevents claims that a signature was created later or with a compromised key).
Common algorithms: RSA, DSA, ECDSA for signing; SHA family (SHA‑256, SHA‑3) for hashing.
Limitations and countermeasures
- If private key is compromised, signatures can be forged — protect private keys (hardware tokens, smart cards).
- Replay attacks can be mitigated by using timestamps, nonces, or session IDs.
- Trust in CA is crucial — use trusted certificate authorities and certificate revocation lists (CRLs) or OCSP.
Legal and practical use
Many countries legally recognize qualified digital signatures when issued under regulated PKI. Digital signatures are widely used for contracts, e‑filing, code signing, and secure email.
- Signing a PDF contract: A buyer digitally signs a sales contract and sends it to the seller. The seller verifies the signature using the buyer's public key to confirm authenticity and that the document was not changed.
- Signed email (S/MIME or PGP): An employee digitally signs an email; recipients verify the signature to be sure the email really came from that employee and content is intact.
- Software code signing: Developers sign application binaries so users and operating systems can verify the code publisher and that code wasn’t tampered with.
- Online banking transaction signing: A bank signs transaction confirmations or requires customer signatures (via secure keys) to prevent repudiation of transfers.
- E‑filing taxes: A taxpayer signs the return digitally to legally affirm submission and prevent later denial.
- \[H = Hash(message) // example: SHA‑256(message)\]
- \[Signature S = Encrypt_private(H) // sign the hash with sender's private key\]
- \[H' = Decrypt_public(S) // recover the signed hash using sender's public key\]
- \[Verify: Hash(message) == Decrypt_public(S) // true → valid signature\]
- \[Optional timestamp token: TS = Sign_TSA(Hash(S || time)) // trusted timestamping of signature\]
Network Security and Firewalls
Network Security and Firewalls
Key Point: CIA (conceptual): Confidentiality + Integrity + Availability (no numeric formula; fundamental goals).
What is Network Security?
Network security is the practice of protecting a computer network and the data transmitted across it from unauthorized access, misuse, modification, or denial of service. The main goals are summarized by the CIA triad: Confidentiality, Integrity and Availability.
Common network threats
- Malware (viruses, worms, Trojans)
- Phishing and social engineering
- Man-in-the-Middle (MitM) attacks and eavesdropping
- Denial of Service (DoS) / Distributed DoS (DDoS)
- IP spoofing and session hijacking
- Unauthorized access due to weak passwords or misconfiguration
Security controls and principles
- Defense in depth: multiple layers (router, firewall, host security, encryption).
- Least privilege: give users and systems only the access they need.
- Fail-safe defaults: deny by default, allow by exception.
- Authentication, authorization and accounting (AAA).
- Encryption for confidentiality (TLS / SSL, VPNs).
What is a Firewall?
A firewall is a device or software that monitors and controls incoming and outgoing network traffic based on an applied set of security rules. It acts as a barrier between a trusted internal network and untrusted external networks (like the Internet).
Firewall functions
- Packet filtering: allow or block packets based on IP, port, protocol.
- Stateful inspection: track active connections and make decisions based on connection state.
- Application-layer filtering / proxying: inspect and filter specific application traffic (HTTP, FTP).
- NAT (Network Address Translation): hide internal addresses.
- Logging and alerts: record traffic and suspicious events.
Types of firewalls
- Packet-filtering firewall (stateless): fast, checks packet headers.
- Stateful firewall: tracks connection states (SYN, ESTABLISHED, FIN).
- Application-level firewall / proxy: examines application data and can block specific commands or payloads.
- Next-generation firewall (NGFW): combines stateful filtering with deep packet inspection, intrusion prevention and application awareness.
- Host-based firewall: software running on a single host (e.g., Windows Firewall).
- Network-based firewall: hardware appliance protecting a whole network segment.
Where firewalls are placed
- Perimeter/edge: between the internal LAN and the Internet.
- DMZ (Demilitarized Zone): hosts (web servers, mail servers) placed between two firewalls to isolate them from the internal network.
- Internal segmentation: additional firewalls between departments or sensitive systems.
How a firewall processes a packet (simple flow)
- Receive packet from interface.
- Check firewall rules in order (first match applies).
- If stateful, check connection table (is this part of an established session?).
- Allow, drop, or reject (with ICMP) the packet and optionally log the event.
Best practices
- Use deny-by-default policy and allow only necessary services (least privilege).
- Keep firewall software/firmware updated and maintain rule hygiene (remove unused rules).
- Use VPN and TLS for remote access, especially over public networks.
- Combine firewall with IDS/IPS, antivirus, and strong authentication.
- Monitor logs regularly and react to alerts.
Simple example rule (conceptual)
1. deny all inbound from 0.0.0.0/0 to internal_network except TCP port 443 (HTTPS) 2. allow outbound from internal_network to 0.0.0.0/0 on established connections 3. allow DNS (UDP port 53) to company DNS server
Firewalls are a foundational control but not a complete solution — they should be part of a broader security strategy including encryption, user education, patching and backups.
- Home Wi‑Fi router firewall blocking incoming requests from the Internet; you can still browse out but unsolicited inbound connections are blocked.
- School network blocks social media and gaming ports during class hours using firewall rules or a proxy to keep students focused.
- Bank web servers are placed in a DMZ behind a perimeter firewall and use TLS (HTTPS) to encrypt customers' data in transit.
- A company uses a VPN with strong encryption and authenticates remote employees before allowing access to internal resources.
- An office uses a stateful firewall that permits responses to internal requests (established sessions) but blocks new unsolicited inbound connections.
- An email gateway proxy filters attachments and scans for malware before delivering messages to employees' inboxes.
- \[CIA (conceptual): Confidentiality + Integrity + Availability (no numeric formula\]\[fundamental goals).\]
- \[Risk (qualitative): Risk ≈ Threat × Vulnerability × Impact (used to prioritize controls).\]
- \[Expected loss (quantitative): Expected Loss = Probability_of_Incident × Impact_of_Incident.\]
- \[Password entropy (bits): Entropy = length × log2(character_pool_size)\]\[Example: 8 characters using 94 printable ASCII ≈ 8 × log2(94) ≈ 52.6 bits.\]
- \[Brute-force time (estimate): Time ≈ (2^bits_of_entropy) / attempts_per_second\]\[Shows exponential growth with key/entropy size.\]
Secure Coding Practices
Secure Coding Practices
Key Point: Password entropy (bits) ≈ L × log2(R), where L = password length, R = size of character set (e.g., 26 lowercase + 26 uppercase + 10 digits + symbols).
What are secure coding practices?
Secure coding practices are a set of rules and techniques programmers follow to design and write source code that is resistant to security vulnerabilities and attacks. These practices reduce the risk of data breaches, unauthorized access, and application misuse.
Why it matters (Class 10 context)
- Web applications often accept input from users and interact with servers and databases—if code is not protected, attackers can exploit it.
- Secure coding protects user data, preserves privacy, and keeps systems available and trustworthy.
Core principles
- Validate input: Always check and restrict user input (type, length, format) before processing.
- Output encoding: Encode data before showing it on web pages to prevent injection into HTML/JavaScript.
- Least privilege: Give programs and users the minimum access they need.
- Secure authentication & authorization: Confirm identity (authentication) and enforce access rights (authorization).
- Fail-safe defaults: If in doubt, deny access or handle errors securely.
- Keep secrets safe: Never hardcode passwords or API keys in source code; store them securely.
- Use secure communication: Use HTTPS/TLS to encrypt data in transit.
- Error handling & logging: Do not reveal sensitive info in error messages; log enough for debugging and auditing.
- Update dependencies: Keep libraries and frameworks patched to avoid known vulnerabilities.
- Regular testing: Use code reviews, static analysis, and security tests (e.g., penetration testing).
Common coding techniques
- Parameterized queries / prepared statements: Prevent SQL injection by separating code and data.
- Output escaping/encoding: Use HTML encoding to prevent Cross-Site Scripting (XSS).
- Use secure cookies: Set HttpOnly, Secure, and SameSite attributes to protect session cookies.
- Use strong password storage: Store passwords as salted hashes (e.g., bcrypt, Argon2).
- CSRF protection: Use anti-CSRF tokens for state-changing requests.
- Limit login attempts: Rate-limit to reduce brute-force attacks.
Benefits for students and small projects
- Build safer apps for classmates or school projects.
- Learn industry best practices early—useful for future courses and careers.
Quick secure-coding checklist
- Validate & sanitize all inputs
- Encode outputs
- Use parameterized DB queries
- Never store plaintext passwords
- Use HTTPS
- Handle errors without leaking info
- Keep libraries updated
- SQL injection: A login form takes a username and password. If code builds an SQL string directly using user input, an attacker can enter ' OR '1'='1 to bypass login. Fix: use parameterized queries.
- Cross-Site Scripting (XSS): A comment box displays user input without encoding, allowing an attacker to submit <script> alert('XSS') </script>. Fix: HTML-encode user content before display.
- Insecure password storage: Storing user passwords in plaintext in a file—if breached, all passwords are exposed. Fix: store salted hashes (e.g., bcrypt).
- Hardcoded API keys: Committing API keys in source control can leak credentials. Fix: use environment variables or secret managers.
- Missing HTTPS: A banking site using HTTP exposes login credentials to network sniffers. Fix: enable HTTPS/TLS site-wide.
- Session fixation: Not regenerating session IDs after login allows attackers to reuse a session. Fix: generate a new session identifier on authentication.
- \[Password entropy (bits) ≈ L × log2(R)\]\[where L = password length\]\[R = size of character set (e.g., 26 lowercase + 26 uppercase + 10 digits + symbols).\]
- \[Stored hash = H(password + salt)\]\[where H is a secure hash function (use slow\]\[adaptive functions like bcrypt/Argon2).\]
- \[Brute-force time ≈ 2^entropy / guesses_per_second (gives approximate time to try all combinations).\]
- \[Rate limit (attempts/minute) = max_attempts / time_window_minutes (use to configure login throttling).\]
Privacy, Data Protection and Cookies
Privacy, Data Protection and Cookies
Key Point: CIA triad (security goals): Confidentiality + Integrity + Availability
Privacy means a person's right to control how their personal information is collected, used and shared. In the web context it covers what data websites, apps and online services collect about you (name, email, location, browsing history, preferences) and who can see or use that data.
Data protection refers to the technical, organizational and legal measures used to keep personal data safe from unauthorised access, misuse, alteration or loss. Good data protection reduces the risk of identity theft, financial loss and violation of user rights.
Why it matters
- Protects individuals' dignity and freedom.
- Prevents fraud, identity theft and reputational damage.
- Builds trust between users and service providers.
Types of personal data (simple categories)
- Identity data: name, date of birth, government ID
- Contact data: phone, address, email
- Online identifiers: IP address, device ID, cookies
- Sensitive data: health, religion, biometrics (requires extra protection)
Core principles of data protection
- Lawfulness, fairness, transparency: users must be told what is collected and why.
- Purpose limitation: collect data only for a specific, legitimate purpose.
- Data minimization: collect only what is necessary.
- Accuracy: keep data correct and up to date.
- Storage limitation: don’t keep personal data longer than needed.
- Integrity and confidentiality: protect data against unauthorized access and breaches.
Common technical measures
- Encryption: convert data to unreadable form in transit (HTTPS/TLS) and at rest.
- Access control and authentication: passwords, multi-factor authentication, role-based access.
- Anonymization & pseudonymization: remove or mask identifiers when full identity is not needed.
- Backups and secure deletion: regular backups for availability and secure wiping when disposing data.
- Logging and monitoring: detect unauthorized access and respond quickly to breaches.
Cookies — what they are
Cookies are small text files websites store on your browser to remember information about you. They are sent between the server and the browser using HTTP headers.
Types of cookies
- Session cookies: temporary, deleted when browser closes (used for logged-in sessions, shopping cart while browsing).
- Persistent cookies: remain until a set expiry date (used for remembering language or preferences).
- First-party cookies: set by the website you are visiting.
- Third-party cookies: set by other domains (often advertising or analytics providers) and used for cross-site tracking.
Common uses of cookies
- Keeping users logged in (session management).
- Remembering user preferences (language, theme).
- Storing items in a shopping cart.
- Collecting analytics (page visits, time on page).
- Targeted advertising and tracking across sites.
Cookie attributes (security & privacy important ones)
- Secure: cookie sent only over HTTPS.
- HttpOnly: not accessible to JavaScript (helps prevent theft via XSS).
- SameSite: controls cross-site sending (Lax, Strict, None) to reduce cross-site request forgery.
- Expires / Max-Age: when the cookie should be removed.
Risks and threats
- Tracking and profiling by advertisers (privacy invasion).
- Cookie theft (via Cross‑Site Scripting) leading to session hijacking.
- Data breaches exposing stored personal data.
- Over-collection and sharing of unnecessary personal data without consent.
User best practices
- Read cookie banners and privacy policies; give consent selectively.
- Use browser privacy settings: block third-party cookies, clear cookies regularly, use incognito mode if needed.
- Use strong, unique passwords and enable two-factor authentication.
- Keep software and browser updated to fix security vulnerabilities.
Developer & website owner best practices
- Collect only needed data and explain purpose clearly.
- Implement HTTPS (TLS) site-wide; use Secure and HttpOnly cookie flags.
- Provide clear cookie controls (allow/deny categories) and an easy opt-out mechanism.
- Minimize use of third-party trackers and carefully vet external scripts.
- Prepare a data-breach response plan and keep logs for audits.
Legal & ethical aspects (short)
Many countries have laws requiring transparency and protection of personal data. Consent, purpose limitation and the right to access/delete personal data are common legal principles. Ethically, organizations should respect user autonomy and avoid deceptive data practices.
Summary: Privacy and data protection ensure that personal information collected online is used fairly, stored securely and shared only when necessary and lawful. Cookies are useful tools for web functionality, but when misused they can threaten privacy—so both users and developers must follow good practices.
- Logging into a webmail account: the server sets a session cookie so you remain logged in as you move between pages. If an attacker steals that cookie, they could hijack your session.
- Shopping website remembering items in your cart: a persistent cookie stores cart contents so closing and reopening the browser still shows your items.
- Targeted ads following you across sites: third-party tracking cookies or trackers from ad networks build a profile of visited sites and interests.
- Data breach at a small company: unencrypted customer databases leaked, exposing names, emails and passwords—shows importance of encryption and access control.
- Browser blocking third-party cookies: prevents many cross-site trackers and reduces targeted advertising but may break some embedded features.
- \[CIA triad (security goals): Confidentiality + Integrity + Availability\]
- \[Risk (conceptual): Risk = Threat × Vulnerability × Impact (used to prioritize protection measures)\]
- \[Consent components (conceptual): Valid Consent = Informed + Freely Given + Specific + Unambiguous\]
- \[Typical Set-Cookie header format: Set-Cookie: name=value\]\[Expires=DATE\]\[Domain=example.com\]\[Path=/\]\[Secure\]\[HttpOnly\]\[SameSite=Lax\]
Safety Best Practices for Users
Safety Best Practices for Users
Key Point: Password entropy (bits) ≈ L × log2(N) — where L is password length and N is alphabet size (e.g., lowercase=26, lowercase+uppercase+digits+symbols≈94). Higher entropy = stronger password.
Safety Best Practices for Users covers the practical steps every internet user should follow to protect personal data, devices, and privacy while using web applications and online services. Good security is layered: it combines strong authentication, careful behaviour, software hygiene, and recovery planning.
- Strong, unique passwords: Use a different password for every important account. Make passwords long and random (avoid dictionary words). Prefer passphrases or a password manager to generate and store credentials.
- Two-factor authentication (2FA): Enable 2FA for email, banking, social media and any service that offers it. 2FA significantly reduces the chance of account takeover even if a password is leaked.
- Keep software updated: Apply OS, browser, app and firmware updates promptly. Many attacks exploit known vulnerabilities for which patches already exist.
- Verify secure connections (HTTPS): Check for the padlock/HTTPS in the browser address bar before entering sensitive information. Be cautious of certificate warnings and typosquatted domains.
- Be careful with email and links: Don’t open unexpected attachments or click suspicious links. Phishing often impersonates trusted organizations. Verify sender addresses and hover over links to see the destination URL.
- Use reputable sources for apps and downloads: Install apps only from official stores (Google Play, Apple App Store) and vendor websites. Check app permissions and reviews.
- Secure your network: Protect home Wi‑Fi with WPA2/WPA3 and a strong router password; change default admin credentials. Avoid untrusted public Wi‑Fi or use a VPN when necessary.
- Antivirus and firewall: Use up-to-date antivirus and enable the device firewall to detect and block malware and suspicious traffic.
- Backup regularly: Keep regular, tested backups (offline or cloud) so you can recover from ransomware or accidental deletion. Follow the 3-2-1 backup rule (3 copies, 2 media, 1 offsite).
- Privacy and social media hygiene: Limit personal information shared online, review privacy settings, and think before posting (once online, data may be hard to remove).
- Device security: Use screen locks, biometric or PIN authentication, encrypt devices where possible, and enable remote-find/remote-wipe features.
- Understand social engineering: Attackers exploit trust. Verify unusual requests (by phone or other channel) especially those asking for money, credentials, or sensitive data.
- Children and family safety: Use parental controls, teach kids safe browsing habits, and supervise younger users.
- Respond and report: If you suspect compromise, change passwords, notify relevant services (bank, email provider), and report phishing or fraud to appropriate authorities and the service provider.
Applying these best practices reduces risk by combining preventive measures (strong auth, updates), detective measures (antivirus, monitoring) and corrective measures (backups, incident response). Security is an ongoing habit, not a one-time action.
- A bank-like phishing email asks you to ‘verify’ your account. Instead of clicking the link, you type the bank’s known URL directly into the browser and call their support number to confirm — this prevents credential theft.
- Using the same password on a social site and bank leads to credential stuffing: attackers reuse leaked passwords to log into other services. Using a password manager with unique passwords prevents this.
- Connecting to free coffee-shop Wi‑Fi and logging into email without a VPN can expose your session to eavesdroppers. Using a VPN or waiting until you’re on a trusted network avoids data interception.
- Ransomware encrypts your files after opening a malicious attachment. Because you kept offline backups (3-2-1 rule), you restore your data without paying the ransom.
- A mobile app requests access to your contacts and microphone but has few installs and poor reviews. You avoid installing it or revoke unnecessary permissions to reduce privacy risk.
- Enabling 2FA on your social account stops an attacker who obtained your password from signing in because they don’t have your second factor (authenticator code or SMS).
- \[Password entropy (bits) ≈ L × log2(N) — where L is password length and N is alphabet size (e.g.\]\[lowercase=26\]\[lowercase+uppercase+digits+symbols≈94)\]\[Higher entropy = stronger password.\]
- \[Key space (number of possible passwords) = N^L — e.g.\]\[for N=94 and L=10\]\[key space = 94^10 possible combinations.\]
- \[Risk ≈ Likelihood × Impact — use to prioritize protections\]\[reducing likelihood (through 2FA\]\[updates) lowers overall risk.\]
- \[Combined compromise probability with independent controls: P(compromise) = P1 × P2 × ... (e.g.\]\[if P(password stolen)=0.01 and P(2FA bypass)=0.001\]\[combined ≈ 0.00001).\]
Cyber Ethics, Laws and Reporting
Cyber Ethics, Laws and Reporting
Key Point: CIA triad (security goals): Confidentiality + Integrity + Availability = Secure information systems (conceptual, not numeric).
What is Cyber Ethics?
Cyber ethics are the moral principles that guide behaviour online: respect for others' privacy and property, honesty, responsibility, and not causing harm. They apply to using social media, email, web services, and any online interactions.
Key principles
- Respect privacy and confidentiality of others
- Do not steal, copy or use someone else’s work without permission (copyright and plagiarism)
- Do not spread false information or hate speech
- Protect your personal information and respect others’ digital identity
- Be responsible: report abuse, do not retaliate, follow terms of service
Common unethical or illegal acts: hacking, phishing, identity theft, cyberbullying, distributing malware, unauthorized access to accounts, posting obscene/defamatory content, piracy.
Laws (India) — what to know
The Information Technology Act, 2000 (and subsequent amendments) is the primary law dealing with cyber offences in India. Important provisions (short description only):
- Section 43A — liability for inadequate protection of sensitive personal data (compensation)
- Section 66 — computer-related offences (unauthorized access, damage) under criminal provisions
- Section 66C — identity theft (fraudulently using another person’s electronic signature, password, etc.)
- Section 66D — cheating by personation using a computer resource
- Section 66E — violation of privacy (capturing/distributing images of private areas)
- Sections 67/67A — publishing obscene material online
- Section 72 — breach of confidentiality and privacy by a service provider
- Section 79 — intermediary liability and safe-harbour rules for online intermediaries
Note: Section 66A (criminalizing offensive online content) was struck down by the Supreme Court in 2015 (Shreya Singhal v. Union of India) as unconstitutional. For details and exact penalties consult the latest text of the IT Act and relevant case law — laws change and local provisions vary.
International laws & standards: examples include the EU GDPR (data protection and privacy), the US Computer Fraud and Abuse Act (CFAA), and global standards like ISO/IEC 27001 for information security management.
Reporting cyber incidents — immediate steps
- Do not panic. Disconnect the affected device from the internet (for malware) or preserve the evidence (take screenshots, keep emails).
- Do not delete messages or logs; document date/time, URLs, sender IDs, transaction IDs, IP addresses if available.
- Change passwords from a safe device; enable two-factor authentication.
- If financial details were exposed, contact your bank or payment provider immediately to block cards/transactions.
- Report the incident through official channels: local cyber police station or the National Cyber Crime Reporting Portal (https://cybercrime.gov.in) in India, and CERT-In (https://www.cert-in.gov.in) for technical incidents. Also report to the online service/provider (email provider, social platform).
- If threatened or harassed, save all communications, block the offender, and escalate to the police for immediate action.
What to include in a complaint: incident date/time, a clear description of what happened, screenshots and URLs, sender/receiver details, transaction IDs if relevant, contact details of the complainant, and steps already taken.
Prevention best practices
- Use strong, unique passwords and 2FA; update software and OS regularly
- Be cautious with email attachments and links (phishing awareness)
- Back up important data offline or to a secure cloud
- Limit sharing of personal information online
- Use reputable antivirus and avoid installing unknown apps
Role of schools, parents and students: teach digital citizenship, report harassment, follow school acceptable-use policies, respect copyright and privacy, and seek help from adults for threatening or criminal incidents.
Summary: Cyber ethics guide safe and fair online behaviour. Cyber laws define offences and penalties; reporting promptly to police, CERT-In or national portals and preserving evidence are essential to stop harm and enable legal action.
- Phishing email: A student receives an email pretending to be from the school asking to "verify" bank details; the link leads to a fake site. Action: Do not click, report to the school admin and local cyber cell, and inform the bank.
- Cyberbullying: A classmate posts private photos with insulting captions. Action: Save screenshots, report the content to the platform, block the user, and involve parents/police if threats continue.
- Identity theft: Someone uses another person’s photos and details to create a fake social profile to defraud others. Action: Report to the platform, collect evidence, and file a complaint with cybercrime portal and police.
- Malware/ransomware: A computer shows a ransom message after opening an unknown attachment. Action: Disconnect from network, do not pay ransom immediately, report to CERT-In/cyber police, restore from backups if available.
- Copyright violation: Uploading a pirated movie or copying school assignment content without attribution. Action: Remove infringing content, cite sources, and understand copyright rules to avoid penalties.
- Fake news: A forwarded message claims harmful misinformation about exams or safety. Action: Verify with trusted sources, do not forward, and report the message to platform moderators.
- \[CIA triad (security goals): Confidentiality + Integrity + Availability = Secure information systems (conceptual\]\[not numeric).\]
- \[Risk (conceptual) = Threat × Vulnerability × Impact (used qualitatively to prioritize risks).\]
- \[Password entropy (bits) = length × log2(character_set_size)\]\[Example: 8-character password from [A–Z,a–z,0–9] (62 chars) entropy ≈ 8 × log2(62) ≈ 8 × 5.95 ≈ 47.6 bits.\]
- \[Two-factor authentication principle: Authentication = Something you know (password) + Something you have (phone/OTP) or Something you are (biometrics).\]
Emerging Concepts and Trends
Emerging Concepts and Trends
Key Point: Encryption (general): Ciphertext C = E(Key, Plaintext P)
What this topic covers
"Emerging Concepts and Trends" looks at new technologies, design patterns and security ideas that are changing how web applications are built, delivered and protected. These trends affect performance, user experience, scalability and the kinds of risks developers and users must manage.
Major trends (short explanations)
- Cloud computing: Delivery of computing services (storage, servers, databases, networking) over the internet. Models include SaaS (software), PaaS (platform) and IaaS (infrastructure). Cloud enables easy scaling and remote access.
- Mobile-first & Responsive Design: Building web apps so they work well on phones and tablets first, then on larger screens. Ensures consistent user experience across devices.
- Progressive Web Apps (PWAs): Web apps that behave like native apps — fast, can work offline, installable — using service workers and caching techniques.
- APIs and Microservices: Breaking applications into small, independent services that communicate via APIs (Application Programming Interfaces). Improves maintainability and allows independent updates.
- Internet of Things (IoT): Everyday devices (sensors, appliances, wearables) connected to the web. IoT data integrates with web applications for automation and analytics.
- Artificial Intelligence & Machine Learning (AI/ML): Using algorithms to analyse data, automate tasks, provide recommendations, and enable features like chatbots, image recognition and personalized content.
- Big Data & Analytics: Collecting and analysing large volumes of user and system data to derive insights, improve services and make data-driven decisions.
- Edge Computing: Processing data closer to where it is generated (e.g., on a device or local server) to reduce latency and bandwidth use — important for IoT and real-time apps.
- Blockchain: A distributed ledger technology used for secure, tamper-evident records. Uses include cryptocurrencies, supply-chain tracking and identity verification.
- 5G and Faster Networks: Higher network speeds and lower latency enable richer mobile experiences, AR/VR and faster cloud interactions.
- AR/VR: Augmented and virtual reality are moving into web experiences, especially in education, retail and gaming.
- DevOps & CI/CD: Practices that combine development and operations to automate testing and deployment, enabling faster releases and more reliable updates.
- Security trends: Zero Trust architecture (never trust, always verify), passwordless authentication, multi-factor authentication (MFA), end-to-end encryption, and stronger privacy laws (e.g., GDPR-like principles) shape how apps secure user data.
Why these matter for web applications
Emerging trends change how apps are designed (microservices, APIs), where they run (cloud or edge), how fast they respond (5G, edge), and how they are kept secure (encryption, zero trust). They directly affect user experience, business models and security posture.
Security implications
- More connected devices (IoT) increase attack surface; insecure devices can be entry points.
- APIs and microservices mean more interfaces to protect; authentication and rate-limiting are important.
- Cloud centralizes data; misconfigured cloud storage is a common source of data leaks.
- AI can help detect attacks (anomaly detection) but also be used by attackers (automated phishing).
- Privacy regulations require careful handling of personal data — consent, minimization and secure storage.
How students should approach learning this topic
- Understand basic definitions and examples of each trend rather than deep internals.
- Relate trends to real applications you use (cloud storage, chatbots, smart home devices).
- Learn basic security practices: use HTTPS, strong passwords/MFA, keep software updated and be careful with personal data.
- Cloud storage: Google Drive or Microsoft OneDrive (SaaS) — files stored on cloud servers, accessible from multiple devices.
- Progressive Web App: Twitter Lite — behaves like an app, loads fast and can work offline.
- IoT smart home: Philips Hue smart bulbs controlled via a web/mobile app; thermostat (e.g., Nest) adjusting temperature based on sensors.
- AI/ML in web apps: E-commerce product recommendations or chatbots for customer support (example: Amazon suggestions, virtual assistants).
- Microservices/API example: Netflix uses many microservices to stream video and scale independently.
- Blockchain use-case: Supply-chain tracking where each transaction is recorded on a tamper-evident ledger.
- \[Encryption (general): Ciphertext C = E(Key\]\[Plaintext P)\]
- \[Decryption (general): Plaintext P = D(Key\]\[Ciphertext C)\]
- \[Hashing: Hash H = h(Message M) — produces fixed-length digest\]\[even small change to M gives different H\]
- \[Digital signature (concept): Signature S = Encrypt_privateKey( h(Message) )\]\[Verify by Decrypt_publicKey(S) == h(Message)\]
- \[Bandwidth (simple): Bandwidth (bits/s) = Data size (bits) / Time (s)\]
- \[Response time (approx): Response Time ≈ Latency + Processing Time + Transmission Time\]
Key Concepts
- Web Application
- A software application that runs on a web server and is accessed through a web browser over the internet.
- HTTP
- HyperText Transfer Protocol — the basic protocol used for exchanging web pages and resources over the internet.
- HTTPS
- HTTP Secure — HTTP combined with SSL/TLS encryption to protect data exchanged between browser and server.
- URL
- Uniform Resource Locator — the address used to find a resource on the web (includes protocol, domain, and path).
- Domain Name
- A human-readable name that identifies a website (maps to an IP address via DNS).
- Web Server
- Software and hardware that store, process and deliver web pages to clients over the internet.
- Web Browser
- A client application used to request, receive and display web pages and resources from web servers.
- HTML
- HyperText Markup Language — the standard language for creating and structuring content on the web.
- JavaScript
- A programming language used in web pages to create interactive features and dynamic content.
- SSL/TLS
- Security protocols (SSL and its successor TLS) that encrypt data sent between a browser and a web server.
- Encryption
- The process of converting readable data (plaintext) into unreadable form (ciphertext) to protect it from unauthorized access.
- Decryption
- The process of converting encrypted data (ciphertext) back into its original readable form (plaintext).
- Cookie
- A small piece of data stored by a web browser on the user's device to remember information about the user or session.
- Session
- Temporary server-side storage that tracks a user's interactions with a web application during a visit.
- Authentication
- The process of verifying the identity of a user or system (e.g., via password or biometrics).
- Authorization
- The process of granting or denying access to resources based on an authenticated user's permissions or roles.
- Firewall
- A network security device or software that monitors and controls incoming and outgoing network traffic based on rules.
- Phishing
- A cyber-attack that uses deceptive emails or websites to trick users into revealing sensitive information like passwords.
- Malware
- Malicious software designed to harm, exploit or gain unauthorized access to computers and data.
- Two-factor Authentication (2FA)
- A security method that requires two different forms of identification (something you know and something you have) to log in.
Practice Questions
-
Define a web application and state one key difference between it and a desktop application. / वेब एप्लिकेशन को परिभाषित करें और इसके तथा डेस्कटॉप एप्लिकेशन के बीच एक मुख्य अंतर बताएं।
Show answer
A web application is software that runs on web servers and is accessed by users through a web browser over the Internet or intranet. Unlike a desktop application, a web app does not need to be installed on the user's computer. / वेब एप्लिकेशन एक सॉफ्टवेयर है जो वेब सर्वर पर चलता है और उपयोगकर्ता इसे इंटरनेट या इंट्रानेट पर वेब ब्राउज़र के माध्यम से एक्सेस करते हैं। डेस्कटॉप एप्लिकेशन के विपरीत, वेब एप्लिकेशन को उपयोगकर्ता के कंप्यूटर पर इंस्टॉल करने की आवश्यकता नहीं होती।
-
Explain the request-response cycle in client-server architecture for a web page. / वेब पेज के लिए क्लाइंट-सर्वर आर्किटेक्चर में रिक्वेस्ट-रिस्पॉन्स चक्र समझाएं।
Show answer
The client (browser) sends an HTTP request (e.g., GET) to the server's IP and port; the network routes it; the server processes it, may query a database, builds a response (HTML/JSON, status code) and returns it to the client, which renders the result. / क्लाइंट (ब्राउज़र) सर्वर के IP और पोर्ट पर एक HTTP रिक्वेस्ट (जैसे GET) भेजता है; नेटवर्क इसे रूट करता है; सर्वर इसे प्रोसेस करता है, डेटाबेस को क्वेरी कर सकता है, एक रिस्पॉन्स (HTML/JSON, स्टेटस कोड) बनाता है और इसे क्लाइंट को लौटाता है, जो परिणाम को रेंडर करता है।
-
What are the three main security properties provided by HTTPS, and which protocol underlies it? / HTTPS द्वारा प्रदान की जाने वाली तीन मुख्य सुरक्षा विशेषताएँ क्या हैं, और इसके अंतर्गत कौन सा प्रोटोकॉल है?
Show answer
HTTPS provides Confidentiality (encrypts data so eavesdroppers cannot read it), Integrity (detects tampering of messages) and Authentication (verifies the server's identity via a CA-issued digital certificate). It is HTTP layered over the TLS/SSL cryptographic protocol. / HTTPS कॉन्फिडेंशियलिटी (डेटा एन्क्रिप्ट करता है ताकि छिपकर सुनने वाले न पढ़ सकें), इंटीग्रिटी (संदेशों में छेड़छाड़ का पता लगाता है) और ऑथेंटिकेशन (CA द्वारा जारी डिजिटल प्रमाणपत्र से सर्वर की पहचान सत्यापित करता है) प्रदान करता है। यह TLS/SSL क्रिप्टोग्राफिक प्रोटोकॉल पर आधारित HTTP है।
-
Why is server-side validation considered mandatory even when client-side validation is present? / क्लाइंट-साइड वैलिडेशन मौजूद होने पर भी सर्वर-साइड वैलिडेशन अनिवार्य क्यों माना जाता है?
Show answer
Client-side validation (HTML5/JavaScript) improves user experience and reduces invalid requests but can be bypassed by a malicious user, so it cannot be trusted. Server-side validation is mandatory for security because the server must never trust incoming client data. / क्लाइंट-साइड वैलिडेशन (HTML5/JavaScript) उपयोगकर्ता अनुभव सुधारता है और अमान्य रिक्वेस्ट कम करता है पर इसे दुर्भावनापूर्ण उपयोगकर्ता द्वारा बायपास किया जा सकता है, इसलिए इस पर भरोसा नहीं किया जा सकता। सुरक्षा के लिए सर्वर-साइड वैलिडेशन अनिवार्य है क्योंकि सर्वर को आने वाले क्लाइंट डेटा पर कभी भरोसा नहीं करना चाहिए।
-
Differentiate between a session cookie and a persistent cookie. / सेशन कुकी और पर्सिस्टेंट कुकी के बीच अंतर बताएं।
Show answer
A session cookie lives only for the browser session and is deleted when the browser closes (it has no Expires/Max-Age). A persistent cookie is stored until a set expiry time because it carries an Expires or Max-Age attribute. / सेशन कुकी केवल ब्राउज़र सेशन तक रहती है और ब्राउज़र बंद होने पर हटा दी जाती है (इसमें कोई Expires/Max-Age नहीं होता)। पर्सिस्टेंट कुकी एक निर्धारित समाप्ति समय तक संग्रहीत रहती है क्योंकि इसमें Expires या Max-Age विशेषता होती है।
-
Trace what happens, step by step, when a user types https://www.example.com/page into a browser. / जब कोई उपयोगकर्ता ब्राउज़र में https://www.example.com/page टाइप करता है तो चरण-दर-चरण क्या होता है, बताएं।
Show answer
The browser asks the DNS resolver to translate the domain to an IP address; DNS returns the IP (e.g., 93.184.216.34); the browser opens a connection (TLS handshake for HTTPS) and sends an HTTP GET request; the server responds with the resource; the browser renders the page. / ब्राउज़र DNS रिज़ॉल्वर से डोमेन को IP पते में बदलने को कहता है; DNS IP लौटाता है (जैसे 93.184.216.34); ब्राउज़र कनेक्शन खोलता है (HTTPS के लिए TLS हैंडशेक) और HTTP GET रिक्वेस्ट भेजता है; सर्वर संसाधन के साथ जवाब देता है; ब्राउज़र पेज रेंडर करता है।
-
Name two ways developers can prevent SQL injection in web forms and explain why one of them works. / डेवलपर वेब फॉर्म में SQL इंजेक्शन रोकने के दो तरीके बताएं और समझाएं कि उनमें से एक क्यों काम करता है।
Show answer
Two ways are using parameterized queries/prepared statements and validating/sanitizing all input on the server. Prepared statements work because user input is bound as data values, not concatenated into the SQL command, so it cannot be executed as malicious code. / दो तरीके हैं पैरामीटराइज़्ड क्वेरी/प्रिपेयर्ड स्टेटमेंट का उपयोग और सर्वर पर सभी इनपुट को वैलिडेट/सैनिटाइज़ करना। प्रिपेयर्ड स्टेटमेंट इसलिए काम करते हैं क्योंकि उपयोगकर्ता इनपुट को डेटा मान के रूप में बांधा जाता है, SQL कमांड में जोड़ा नहीं जाता, इसलिए इसे दुर्भावनापूर्ण कोड के रूप में निष्पादित नहीं किया जा सकता।
-
Using usable_hosts = 2^(32-n) - 2, calculate the number of usable host addresses in the subnet 192.168.1.0/24. / usable_hosts = 2^(32-n) - 2 का उपयोग करके सबनेट 192.168.1.0/24 में उपयोग योग्य होस्ट पतों की संख्या की गणना करें।
Show answer
Here n = 24, so host bits = 32 - 24 = 8; usable_hosts = 2^8 - 2 = 256 - 2 = 254. We subtract 2 for the network and broadcast addresses, giving 254 usable hosts. / यहाँ n = 24, अतः होस्ट बिट = 32 - 24 = 8; usable_hosts = 2^8 - 2 = 256 - 2 = 254। नेटवर्क और ब्रॉडकास्ट पतों के लिए 2 घटाते हैं, जिससे 254 उपयोग योग्य होस्ट मिलते हैं।
Related Laws & Principles
Explore allFoundational laws & principles connected to this chapter — tap to open in the Laws Explorer.