Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views20 pages

Koushikcrypto5lab Compressed

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Assessment No.

5
Experiments 8, 9 & 10

Name :- KATTA KOUSHIK REDDY

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:

1. SSL Certificate Setup:


o Generate SSL certificates for the server using tools like OpenSSL.
o Create a certificate authority (CA) for signing the server's certificate.
o Distribute the server's public certificate to clients.
2. Server Implementation:
o Develop a server application listening on a specific port.
o Load the server's SSL certificate and private key.
o Accept SSL connections from clients, process requests, and send responses.
3. Client Implementation:
o Create a client application to establish an SSL connection with the server.
o Load the server's public certificate for verification.
o Initiate an SSL handshake with the server to establish a secure connection.
4. Testing and Debugging:
o Test the client-server interaction locally or on a test environment.
o Ensure successful SSL connections and proper request-response handling.
5. Deployment:
o Deploy the server on a hosting platform and distribute the client application to users.
o Configure network settings for client-server communication.
6. Security Considerations:
o Regularly update SSL certificates and follow secure coding practices to prevent
vulnerabilities.
o Monitor for security incidents and promptly address them.
7. Scalability and Performance:
o Implement load balancing and optimize server-side code for scalability and
performance.

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;

method = SSLv23_client_method(); // Use SSLv23_client_method() for better


compatibility
ctx = SSL_CTX_new(method);
if (!ctx) {
perror("Unable to create SSL context");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

return ctx;
}

void configure_context(SSL_CTX* ctx) {


// Load client certificate
if (SSL_CTX_use_certificate_file(ctx, "client/certificate-client.pem",
SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

// Load client private key


if (SSL_CTX_use_PrivateKey_file(ctx, "client/private-key-client.pem",
SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

// 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();

// Configure the SSL context


configure_context(ctx);

// Create BIO connection


bio = BIO_new_ssl_connect(ctx);
BIO_set_conn_hostname(bio, "127.0.0.1:8333");

// Attempt to connect
if (BIO_do_connect(bio) <= 0) {
perror("Error connecting to server");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

// Check if the certificate is valid


if (SSL_get_verify_result(SSL_get_SSL_CTX(ssl)) != X509_V_OK) {
fprintf(stderr, "Certificate verification error\n");
exit(EXIT_FAILURE);
}

ssl = BIO_get_ssl(bio, nullptr);


if (!ssl) {
perror("Error SSL connection");
exit(EXIT_FAILURE);
}

// Perform SSL handshake


if (SSL_do_handshake(ssl) <= 0) {
perror("Error SSL handshake");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

std::cout << "Connected to server." << std::endl;

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;

if (std::string(buf, bytes) == "Bye.")


break;

std::cout << "Client: ";


std::cin.getline(buf, sizeof(buf));
BIO_write(bio, buf, strlen(buf));
}

// Clean up
BIO_free_all(bio);
SSL_CTX_free(ctx);

return 0;
}
SSL Server:
#include <iostream>
#include <openssl/ssl.h>
#include <openssl/err.h>

#define CERT_FILE "server/certificate-server.pem"


#define KEY_FILE "server/private-key-server.pem"

SSL_CTX* InitServerCTX(void) {
const SSL_METHOD *method;
SSL_CTX *ctx;

OpenSSL_add_all_algorithms(); // Load cryptos, et.al.


SSL_load_error_strings(); // Bring in and register error messages
method = TLS_server_method(); // Create new server-method instance
ctx = SSL_CTX_new(method); // Create new context from method
if (ctx == NULL) {
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}

void LoadCertificates(SSL_CTX* ctx, const char* CertFile, const char* KeyFile) {


// Load certificates into the SSL_CTX* SSL context
if (SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
abort();
}
if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
abort();
}
if (!SSL_CTX_check_private_key(ctx)) {
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}

int main() {
SSL_CTX *ctx;
int server;

SSL_library_init();
ctx = InitServerCTX(); // Initialize SSL
LoadCertificates(ctx, CERT_FILE, KEY_FILE); // Load certs and key

// Create a socket and listen for connections


struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8333);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

server = socket(AF_INET, SOCK_STREAM, 0);


bind(server, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
listen(server, 5);

// Accept incoming connections


struct sockaddr_in clientAddr;
socklen_t clientLen = sizeof(clientAddr);
int client = accept(server, (struct sockaddr *)&clientAddr, &clientLen);

// Wrap the socket with SSL


SSL *ssl;
ssl = SSL_new(ctx);
SSL_set_fd(ssl, client);

// Perform SSL handshake


if (SSL_accept(ssl) <= 0) {
ERR_print_errors_fp(stderr);
} else {
// Handle SSL connection
char buf[1024];
int bytes;

// Receive data from client


bytes = SSL_read(ssl, buf, sizeof(buf));
if (bytes > 0) {
// Process data and send response
SSL_write(ssl, buf, bytes);
}
}

// 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;

method = SSLv23_server_method(); // Use SSLv23_server_method() for better


compatibility
ctx = SSL_CTX_new(method);
if (!ctx) {
perror("Unable to create SSL context");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

return ctx;
}

void configure_context(SSL_CTX* ctx) {


// Load server certificate
if (SSL_CTX_use_certificate_file(ctx, "server/certificate-server.pem",
SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

// Load server private key


if (SSL_CTX_use_PrivateKey_file(ctx, "server/private-key-server.pem",
SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}

// Set up client authentication


SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
nullptr);
SSL_CTX_set_verify_depth(ctx, 4);
}

int main() {
init_openssl();
SSL_CTX *ctx = create_context();

// Configure the SSL context


configure_context(ctx);

int server_fd, new_socket;


struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}

// Forcefully attaching socket to the port 8333


if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,
sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8333);

// Forcefully attaching socket to the port 8333


if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))
== 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr )&address,
(socklen_t)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}

Knock Knock Protocol:

Knock Knock Protocol:

#include <iostream>
#include <openssl/ssl.h>
#include <openssl/err.h>

#define CERT_FILE "server/certificate-server.pem"


#define KEY_FILE "server/private-key-server.pem"

SSL_CTX* InitServerCTX(void) {
const SSL_METHOD *method;
SSL_CTX *ctx;

OpenSSL_add_all_algorithms(); // Load cryptos, et.al.


SSL_load_error_strings(); // Bring in and register error messages
method = TLS_server_method(); // Create new server-method instance
ctx = SSL_CTX_new(method); // Create new context from method
if (ctx == NULL) {
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}

void LoadCertificates(SSL_CTX* ctx, const char* CertFile, const char* KeyFile) {


// Load certificates into the SSL_CTX* SSL context
if (SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
abort();
}
if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
abort();
}
if (!SSL_CTX_check_private_key(ctx)) {
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}

int main() {
SSL_CTX *ctx;
int server;

SSL_library_init();
ctx = InitServerCTX(); // Initialize SSL
LoadCertificates(ctx, CERT_FILE, KEY_FILE); // Load certs and key

// Create a socket and listen for connections


struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8333);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

server = socket(AF_INET, SOCK_STREAM, 0);


bind(server, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
listen(server, 5);

// Accept incoming connections


struct sockaddr_in clientAddr;
socklen_t clientLen = sizeof(clientAddr);
int client = accept(server, (struct sockaddr *)&clientAddr, &clientLen);

// Wrap the socket with SSL


SSL *ssl;
ssl = SSL_new(ctx);
SSL_set_fd(ssl, client);

// Perform SSL handshake


if (SSL_accept(ssl) <= 0) {
ERR_print_errors_fp(stderr);
} else {
// Handle SSL connection
char buf[1024];
int bytes;

// Receive data from client


bytes = SSL_read(ssl, buf, sizeof(buf));
if (bytes > 0) {
// Process data and send response
SSL_write(ssl, buf, bytes);
}
}

// 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>

void error(const char *msg) {


perror(msg);
exit(1);
}

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);
}

bzero((char *) &serv_addr, sizeof(serv_addr));


serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);

if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)


error("ERROR connecting");

std::cout << "Connected to server." << std::endl;

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;

std::cout << "Client: ";


std::getline(std::cin, fromUser);
n = write(sockfd, fromUser.c_str(), fromUser.length());
if (n < 0)
error("ERROR writing to socket");
}

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:

Packet Capture with Wireshark/Tshark:

Packet capture involves intercepting network traffic between devices.

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:

Start Wireshark or use Tshark to capture packets.

Select the network interface for packet capture.

Begin capturing to monitor network traffic.

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.

Each packet can be expanded to view protocol-specific details.

Filtering:

Use Wireshark filters to focus on specific packet types or traffic.

Filters can target criteria like IP addresses, protocols, ports, or packet contents.

Protocol Decoding:

Wireshark decodes various network protocols, presenting packet information in human-readable


form.

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.

1. Access any university website and download the files or materials

2. Get the information of university website using IP address of


destination.
3. Get the information of university website using TCP or UDP’s

4. Get the information of university website using DNS of destination.


5. Get the information of university website using string matching.

6. Get the information of university website using Port value, IP address


and TCP connection.
Experiment 10: Develop a web application that implements JSON web token

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.

You might also like