Koushikcrypto5lab Compressed
Koushikcrypto5lab Compressed
Koushikcrypto5lab Compressed
5
Experiments 8, 9 & 10
Req : 21BCE2070
Experiment 8: Develop a simple client and server application using SSL socket communication:
Concept:
• Overview:
o A simple client-server application involves one program, the client, requesting
services from another program, the server, over a network.
o SSL (Secure Socket Layer) protocol is employed for secure communication, ensuring
data confidentiality and integrity.
• Client-Server Model:
o The client initiates connection requests to the server, which listens for and accepts
them.
o Upon establishing a connection, data exchange between client and server is
facilitated.
• SSL (Secure Socket Layer):
o SSL is a cryptographic protocol ensuring secure communication over networks.
o It encrypts data transmission, preventing eavesdropping and tampering, and verifies
server identity to prevent impersonation.
• Socket Communication:
o Sockets facilitate communication between machines over a network.
o SSL sockets ensure secure connections by encrypting transmitted data.
• Functionality:
o The client sends requests to the server, which processes them and responds
accordingly.
o All communication is encrypted using SSL.
Algorithm:
SSL Client:
SSL Client:
#include <iostream>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <unistd.h>
void init_openssl() {
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
SSL_CTX* create_context() {
const SSL_METHOD *method;
SSL_CTX *ctx;
return ctx;
}
// Load CA certificate
if (!SSL_CTX_load_verify_locations(ctx, "server/certificate-server.pem",
nullptr)) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
int main() {
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
init_openssl();
ctx = create_context();
// Attempt to connect
if (BIO_do_connect(bio) <= 0) {
perror("Error connecting to server");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
char buf[1024];
int bytes;
while (true) {
bytes = BIO_read(bio, buf, sizeof(buf));
if (bytes <= 0) {
break;
}
std::cout << "Server: " << std::string(buf, bytes) << std::endl;
// Clean up
BIO_free_all(bio);
SSL_CTX_free(ctx);
return 0;
}
SSL Server:
#include <iostream>
#include <openssl/ssl.h>
#include <openssl/err.h>
SSL_CTX* InitServerCTX(void) {
const SSL_METHOD *method;
SSL_CTX *ctx;
int main() {
SSL_CTX *ctx;
int server;
SSL_library_init();
ctx = InitServerCTX(); // Initialize SSL
LoadCertificates(ctx, CERT_FILE, KEY_FILE); // Load certs and key
// Clean up
close(client);
close(server);
SSL_free(ssl);
SSL_CTX_free(ctx);
return 0;
}
Simple Server:
Simple Server:
#include <iostream>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <unistd.h>
void init_openssl() {
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
SSL_CTX* create_context() {
const SSL_METHOD *method;
SSL_CTX *ctx;
return ctx;
}
int main() {
init_openssl();
SSL_CTX *ctx = create_context();
#include <iostream>
#include <openssl/ssl.h>
#include <openssl/err.h>
SSL_CTX* InitServerCTX(void) {
const SSL_METHOD *method;
SSL_CTX *ctx;
int main() {
SSL_CTX *ctx;
int server;
SSL_library_init();
ctx = InitServerCTX(); // Initialize SSL
LoadCertificates(ctx, CERT_FILE, KEY_FILE); // Load certs and key
// Clean up
close(client);
close(server);
SSL_free(ssl);
SSL_CTX_free(ctx);
return 0;
}
Simple Client: -
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main() {
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
std::string fromServer, fromUser;
portno = 8443;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname("127.0.0.1");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
while (true) {
bzero(buffer, 256);
n = read(sockfd, buffer, 255);
if (n < 0)
error("ERROR reading from socket");
fromServer = std::string(buffer);
std::cout << "Server: " << fromServer << std::endl;
if (fromServer == "Bye.")
break;
close(sockfd);
return 0;
}
Output
Experiment 9: Develop a simple client server model using telnet and capture the packets
transmitted with tshark Analyze the pcap file and get the transmitted data (plain text) using any
packet capturing library.
Implement the above scenario using SSH and observe the data
Concept:
Wireshark is a widely-used network protocol analyzer for real-time packet capture and analysis.
Tshark is a command-line version of Wireshark suitable for scripting and automated tasks.
Capturing Packets:
Packet Analysis:
Wireshark provides detailed packet analysis, displaying packet contents and metadata.
Analyze packets to understand network behavior, diagnose issues, and identify security threats.
Packet Display:
Captured packets are displayed in tabular format showing source, destination, protocol, length, and
timestamp.
Filtering:
Filters can target criteria like IP addresses, protocols, ports, or packet contents.
Protocol Decoding:
Packet Reconstruction:
Wireshark can reconstruct higher-level protocols (e.g., HTTP, FTP), showing web page content or file
transfers.
Statistical Analysis:
Wireshark offers statistical tools to analyze traffic, including endpoint statistics, protocol distribution,
and round-trip time calculations.
Exporting Data:
Save captured packets or analysis results in various formats like plaintext, CSV, or pcap for further
examination or sharing.
Advanced Features:
Wireshark provides advanced features such as packet coloring rules, annotations, and expert analysis
information to highlight important packets and flag potential issues.
By following these steps, you can create a client-server setup, capture packets using Wireshark or
Tshark, analyze the captured data, and extract transmitted plaintext information using packet
capturing libraries.
Concept:
• Overview of JSON Web Token (JWT):
o JWT is a compact and self-contained way of transmitting information between parties
as a JSON object.
o Commonly used for authentication and authorization in web applications and APIs.
• Structure of JWT:
o Consists of three parts: header, payload, and signature.
o Header: Metadata about the token type and hashing algorithm.
o Payload: Claims, statements about an entity (e.g., user), and additional data.
o Signature: Verifies token integrity and prevents tampering.
• Working Principle:
o Server creates JWT after successful user authentication.
o JWT is sent to the client and stored (e.g., local storage, cookies).
o Client includes JWT in subsequent requests.
o Server verifies JWT signature and decodes payload for user information or
permissions.
• Features of JWT:
o Stateless: Eliminates the need for server-side session storage.
o Compact: Easily transmitted over networks.
o Self-contained: Contains all necessary information within the token.
• Use Cases:
o Authentication: Grants access to protected resources after login.
o Authorization: Conveys user roles, permissions, or scopes.
o Information Exchange: Securely exchanges data between systems or services.
• Security Considerations:
o Transmit over HTTPS to prevent interception.
o Avoid sensitive information in payload.
o Use strong encryption algorithms and manage keys securely.
o Implement token expiration and refresh mechanisms.
• Libraries and Frameworks:
o Various libraries and frameworks support JWT authentication and token management.
o Handle JWT generation, verification, and token refreshing.
• Scalability and Performance:
o Improve scalability by reducing server-side session storage.
o Manage token usage to avoid increased network traffic.
• Best Practices:
o Follow JWT implementation best practices, including token expiration and secure key
storage.
o Regularly audit JWT usage to identify security risks.
Conclusion: JWTs provide a flexible and secure method for authentication and authorization in web
applications and APIs, offering benefits such as statelessness, compactness, and self-containment.
Following best practices ensures secure JWT implementation and enhances applicationsecurity.
Output:
Login page of my website
Cookies
Algorithm:
• Here's a step-by-step algorithm for developing a web application that implements
JSON Web Token (JWT) authentication:
• Install Necessary Libraries: Install the required libraries for your web framework to
handle JWT authentication. For example, for Python with Flask framework, you can
use PyJWT library.
• Set Up Web Framework: Create a new web application project using your chosen web
framework (e.g., Flask, Django).
• Create User Authentication System: Implement a user authentication system where
users can register, login, and logout. Store user credentials securely, such as hashed
passwords.
• Generate JWT upon Authentication:
• When a user successfully logs in, generate a JWT containing the user's identity (e.g.,
user ID, username) and any additional information.
• Use a secret key known only to the server to sign the JWT.
• Return JWT to Client: Upon successful authentication, return the JWT to the client as
part of the response.
• Secure Endpoints with JWT: Define endpoints that require authentication and
authorization. These endpoints can only be accessed with a valid JWT.
• Extract the JWT from the request header or other secure means.
• Verify the JWT signature using the server's secret key.
• Ensure the JWT is not expired and contains valid user information.
• Grant access to the protected resource if the JWT is valid.
• Refresh JWT: Optionally, implement a mechanism to refresh JWT tokens to extend
their validity without requiring the user to log in again.
• Handle Logout: Implement a logout mechanism that invalidates JWT tokens on the
server side. This could involve blacklisting or revoking tokens.
• Testing: Test the JWT authentication by making requests to protected endpoints with
valid and invalid JWT tokens. Ensure that unauthorized access attempts are properly
handled.
• Error Handling: Implement error handling mechanisms to handle various scenarios,
such as invalid JWT, expired JWT, and unauthorized access.
• Deployment: Deploy the web application to a production environment, ensuring that
proper security measures are in place, such as HTTPS encryption and secure storage
of secret keys.
• Monitoring and Maintenance: Monitor the application for any security vulnerabilities
and regularly update dependencies to mitigate risks. Keep abreast of any updates or
changes to JWT specifications and best practices.