Network Programming and Security - 3

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

Network Programming and Security

Noureddine Boujnah
Dublin City University, Ireland
Faculty of Sciences of Gabes
Introduction
• Data exchanges require a basic understanding of network architectures and protocols
• The network includes personal computers, routers, switches, servers, RJ45 cable, crossover cable,
optical fiber, small form-factor pluggable(SFP),…
• Protocols were designed to support various services such as audio, voice, video, image-sensitive
data, emails…
• Protocols are used for data transmission, scheduling, resource reservation, frame and packet
formatting, and synchronization.
• Programming languages such as: C, C++, Python, and Java were upgraded to support network
communication such as real-time chat, data exchange
• Different level of security is required to protect data from hackers, Man-In-the –Middle(MIM) and
different types of attacks
• At the end of this course, students will understand and be familiar with:
• Network communication protocols: UDP and TCP
• Socket principle
• Installation of Java environment and IDE and first test of client/server socket
• Network security
Network Programming and Security

Chapter I
Network Fundamentals
Layered Architecture
1.Physical Layer: At the bottom of the OSI model, the Physical Layer offers the actual
hardware components and physical transmission of facts. It encompasses aspects including
cable sorts, connectors, signalling, and the modulation of alerts. Ethernet cables, fibre optics,
and Wi-Fi indicators all fall underneath this residue.
2.Data Link Layer: Above the Physical Layer, the Data Link Layer specialises in setting up a
reliable hyperlink between two immediately linked nodes. It regularly employs MAC addresses
for device identification and consists of mistake detection and correction mechanisms. Ethernet
and Wi-Fi protocols operate at this residue.
3.Network Layer: The Network Layer is liable for routing facts among networks. It manages
logical addressing (along with IP addresses), determines the most excellent path for information
packets, and handles the routing of packets through routers. IP (Internet Protocol) is a
distinguished Network Layer protocol.
Layered Architecture
4. Transport Layer: Above the Network Layer, the Transport Layer guarantees reliable facts transfer
between two hosts. It gives offerings including segmentation of facts, error detection, and go-with-
the-flow management. TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are
key Transport Layer protocols.
5. Session Layer: The Session Layer offers consultation control among packages. It establishes,
keeps, and terminates classes, ensuring that statistics trade among packages is coordinated and
reliable. This layer is much less common in modern networking but became extra relevant in earlier
networking models.
7. Presentation Layer: Situated above the Session Layer, the Presentation Layer focuses on facts
translation and encryption. It ensures that records exchanged among extraordinary systems are in a
layout they can understand. Encryption and decryption, information compression, and character
encoding are a part of this layer's functions.
Application Layer: The topmost layer, the Application Layer, interfaces with end-consumer
programs without delay. It presents many network offerings and protocols, such as HTTP for net
surfing, SMTP for e-mail, and FTP for file transfer. It's the layer in which users interact with the
community.
Applications

1.Web Browsing
2.E-mail Communication
3.VoIP Calls
4.Cloud Computing
5.Internet of Things (IoT)
6.Internet Protocol Suite (TCP/IP)
7.Wireless Communication
8.Ethernet
9.Data Centres
10.Video Streaming
11.Blockchain Networks.
Smart Objects protocol stack in IoT
Communication
Single hop communication
Tasks in Networking:
• Flow control: of data transmission at
Link: cable/wireless link the source should be the same at the
Source Destination
destination
• Addressing and routing: each
machine/device has an identity, its
Networking: interconnected machines and devices data can follow a path
exchange data and signals • Data recovery: if an interruption
happens, the system should be able to
recover
• Message formatting: a message
between elements of the network
should be formatted in a standard
shape
• Security of communication: measures to
protect data during their transmission
Network Layer: IP address

Class A 1.0.0.0 to 126.255.255.255, inclusive. About 16 million IP addresses in a class A


domain.

Class B 128.1.0.0 to 191.254.255.255, inclusive. About 64 thousand IP addresses in a


class B domain.

Class C 192.0.1.0 to 223.255.254.255, inclusive. 256 IP addresses in a class C domain.


Class D 224.0.0.1 to 239.255.255.255, inclusive, denote multicast groups.

Class E 240.0.0.0 to 254.255.255.255, inclusive. Reserved for future use.

The IP address 127.0.0.1 is special and is reserved to represent the loopback or "localhost" address.
Evolution from IPv4 to IPv6
• Addressing using internet protocols is
required to connect machines to the
network
• Exhaustion of IPv4 addresses limited to
232
• Version IPv6 with less fields in the header,
more addresses(2128 )
• Shortage of addresses in IPv4 due to
emergence of new technologies such as
IoT and 5G
• IPv6 network can support new services
and traffic flows
IPv6 and beyond will support a plethora of services, traffic flows and
connectivity. New research opportunities can be:
• Reducing industrial network OPEX/CAPEX while using IPv6 using All
IP solution, adaptations layers
• Improving QoS metrics of IPv6 and beyond to support ultra-high
data14/11/2022
rate and ultra-low delay 10
Internet address and port number manipulation in Java

 Internet addresses are manipulated in Java by the use of the InetAddress class.
InetAddress takes care of the Domain Name System (DNS) look-up and reverse
look-up; IP addresses can be specified by either the host name or the raw IP
address. InetAddress provides methods to getByName(), getAllByName(),
getLocalHost(), getAddress(), etc.
 The port number field of an IP packet is specified as a 16-bit unsigned integer. This
means that valid port numbers range from 1 through 65535. (Port number 0 is
reserved and can't be used).
 Port numbers 1 through 255 are reserved by IP for well-known services
Transport layer: TCP/IP protocols

TCP/IP defines how information flow from sender to receiver


Application programs send messages or streams to :
• User Datagram Protocol(UDP)
• Transport Control Protocol(TCP)
TCP and UDP belong to the Transport layer, messages are encapsulated into packets and
sent to the Network layer.
Characteristics

TCP UDP
Reliable: TCP is a reliable protocol as it follows Connectionless
the flow and error control mechanism. It also he UDP is a connectionless protocol as it
supports the acknowledgment mechanism, does not create a virtual path to transfer the
which checks the state and sound arrival of data. It does not use the virtual path, so
the data. In the acknowledgment mechanism, packets are sent in different paths between
the receiver sends either positive or negative the sender and the receiver, which leads to
acknowledgment to the sender so that the the loss of packets or received out of order.
sender can get to know whether the data
packet has been received or needs to resend.
Order of the data is maintained: Ordered delivery of data is not guaranteed
This protocol ensures that the data reaches In the case of UDP, the datagrams are sent in
the intended receiver in the same order in some order will be received in the same order
which it is sent. It orders and numbers each is not guaranteed as the datagrams are not
segment so that the TCP layer on the numbered.
destination side can reassemble them based
Characteristics

TCP UDP
Ports: Ports:
the range of port numbers is 0 to 65535 The UDP protocol uses different port numbers
The range from 0 to 1023 port numbers are so that the data can be sent to the correct
reserved for the standard protocols, and the destination. The port numbers are defined
other port numbers are user-defined. between 0 and 1023.
retransmission : is a mechanism used by Fatser transmission:
protocols such as TCP to provide reliable UDP enables faster transmission as it is a
communication. Here, reliable communication connectionless protocol, i.e., no virtual path is
means that the protocol guarantees packet's required to transfer the data. But there is a
delivery even if the data packet has been lost chance that the individual packet is lost,
or damaged. which affects the transmission quality. On the
other hand, if the packet is lost in TCP
connection, that packet will be resent, so it
guarantees the delivery of the data packets.
Physical Network: cabling
Network cabling

Optical Fiber
SFP
Network Cabling
Cabling crossover
Drivers and network interfaces

• The Network Interface Card connects computer to the


network
• NIC is equivalent to data link layer and physical layer
• Wireless NIC Antenna operating @MW , connexion or
female RJ45 socket for Wired NIC
• Wireless: WI-FI, Bluetooth, 4G/5G
• For each hardware driver

Example of Line coding(LC)


Lab session

 Open the doc file in LAB folder


 A group consists of 1,2 or 3 students
 Part1 is described and consists of 5 tasks, deadline to submit report for the first
phase is 30/04/2024

 Questions?
Networking commands( add ? To see help and try examples)
and tools
tools
commands

 netsh  Wireshark
 nslookup  Tshark
 tracert  Iperf
 pathping  Netperf
 netstat  netCPS
 route  netcat (linux)
 mstsc ( hit ENTER)
to understand well protocols, you need Wireshark
Using iperf3

 After setting up both machines, now each machine can be identified by its IP address
 First test using ping test
 Install IPERF3 tool in the first machine as server and the second machine as a client
 It works on UNIX and Windows, it can be installed locally, however it has no big practical utility
 Start first test for TCP and UDP
 The test requires to launch the server side to “listen” stream or datagrams coming from the
client
 Both the transport and the network layer are involved in this test
 Iperf3 tests are a good start to understand sockets
 In parallel, Tshark or Wireshark can be launched
 Example : iperf3 -c 172.16.0.1 -u -b 0.5m -t 20
Client server model
 A program sends a request and awaits for a response
 In the server side a different program that listens to a given channel or ‘port’
 The model can be deployed locally or in a network
 It involves 1 machine, 2 or more
 Client/server model in TCP/IP:
Using Remote Procedure Call(RPC)

 The remote procedure call (RPC) is a communication protocol between processes that allows a
machine to execute specific procedures using parameters from another machine across a
network. Implemented to ensure communication between two machines physically separated
 RPC uses sockets to provide communication
 Call parameters are embedded and adapted to programs and network, transmitted
to the callee (from the caller) and executed afte scheduled, finally return back
results to the client
 RPC Uses dedicated bandwidth and other networking requirements for
communication to guarantee the QoS
 Example: gRPC

https://grpc.io/docs/what-is-grpc
Network Programming and Security

Chapter II
Java Network Programming
Essentials
Java for Networking

• It aims at availing resources for data sharing between two distant machines
• The java.net package supports two communication protocols:
• TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol called TCP/IP.
• UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packets of data to be transferred along two or more nodes
Terminology

• IP Address
• Protocol
• Port number
• MAC address
• Connexion-oriented and connectionless
communication
• Sockets
Classes for java.net
•Authenticator •MulticastSocket •ProxySelector •URLClassLoader
•CacheRequest •InetSocketAddress •ResponseCache •URLConnection
•CacheResponse •InetAddress •SecureCacheResponse •URLDecoder
•ContentHandler •Inet4Address •ServerSocket •URLEncoder
•CookieHandler •Inet6Address •Socket •URLStreamHandler
•CookieManager •IDN •SocketAddress
•DatagramPacket •HttpURLConnection •SocketImpl
•DatagramSocket •HttpCookie •SocketPermission
•DatagramSocketImp •NetPermission •StandardSocketOptions
l •NetworkInterface •URI
•InterfaceAddress •PasswordAuthentication •URL
•JarURLConnection •Proxy •URLClassLoader

Please take the time to discovers java.net classes and associated methods
Interfaces for java.net
•ContentHandlerFactory • What is file handling?
•CookiePolicy How to express it in java: if you
•CookieStore have previous knowledge in
•DatagramSocketImplFactory python, you need just to use a
•FileNameMap proper syntax
•SocketOption<T> • What is cookies? How to deal
•SocketOptions with cookies in java
•SocketImplFactory
•URLStreamHandlerFactory
•ProtocolFamily
Related packages

import java.io.*;
import java.net.*;
import java.util.Scanner;
Network Programming and Security

Chapter III
Java Network Programming
Essentials
UDP Datagram and TCP segment

* UDP: non reliable and fast


No sequence number
No ack required
Less overhead than TCP segment
* TCP reliable and slow
Sequence number to segments
Connection required before
transmission
Sockets
introduced in the early 1980s for 2 types of Socket
interprocess communication
using IP, the Internet Pro
Stream Socket(TCP Datagram
Sockets are a means of using IP Socket) Socket(UDP Socket)
to communicate between
machines, so sockets are one Reliable and Error Unreliable and best
major feature that allows Java to free service effort service
interoperate with legacy systems Sequential packet Datagram may arrive
by simply talking to existing delivered out of order
servers using their pre-defined
protocol.tocol Telnet/SSH, HTTP, Live streaming
HTTPS audio/video
UDP server
1. Create DatagramSocket: The UDP server creates a DatagramSocket on port 1234, indicating that it's
ready to listen for incoming datagrams.

int port = 1234;

DatagramSocket socket = new DatagramSocket(port);

2. Start Listening Loop: The server enters an infinite loop where it continuously listens for incoming
datagrams.

3. Receive DatagramPacket: The receive method of the DatagramSocket waits until a datagram packet is
received. The received data is stored in the receiveData byte array, messages assumed not to be higher
than 2024 bytes

byte[] buffer = new byte[1024];

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);


UDP server
4. Display Message with Log Header: The server displays the received message along with a log header that
includes a timestamp, client IP address, and port.

5. Extract Client Details: The DatagramPacket contains the client's IP address and port. These details are
extracted using the getAddress() and getPort() methods.

// Block on receive()

socket.receive(packet);

// Find out where packet came from so we can reply to the same host/port
InetAddress remoteHost = packet.getAddress();

int remotePort = packet.getPort(); // Extract the packet data

byte[] data = packet.getData();


UDP server

6. Convert Bytes to String: The received data is converted from bytes to a string using
the String constructor.
UDP client

1. First allocate space to hold the data we are sending and create an instance of DatagramPacket to hold the
data.

byte[] buffer = new byte[1024];

int port = 1234;

InetAddress host = InetAddress.getByName("127.0.0.1");

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, host, port);

2. Create DatagramPacket and byte array: A DatagramPacket is a container that holds data to be sent or received
over a UDP connection. A byte array named sendData is created to hold the message to be sent.

3. Create DatagramSocket: A DatagramSocket is established for the client. It acts as the endpoint for sending and
receiving datagrams (packets) on a UDP connection.
UDP client

1. Start User Input Loop: The code enters an infinite loop where the user can input messages to be sent to the
server. If the user inputs “QUIT,” the client socket is closed, and the program exits.

2. Convert String to Bytes: The user input message (cmd) is converted to bytes using the getBytes() method.

3. Create DatagramPacket: A new DatagramPacket is created with the message bytes, destination IP address
("127.0.0.1"), and port number (5001).

4. Send DatagramPacket: The send method of the client socket is used to send the datagram packet to the server.
TCP server

To create a TCP server, do the following:


1. Create a ServerSocket attached to a port number.
ServerSocket server = new ServerSocket(port);
2. Wait for connections from clients requesting connections to that port.
// Block on accept()
Socket channel = server.accept();
You'll get a Socket object as a result of the connection.
3. Get input and output streams associated with the socket.

out = new PrintWriter (channel.getOutputStream());


reader = new InputStreamReader (channel.getInputStream());
in = new BufferedReader (reader);

Now you can read and write to the socket, thus, communicating with the client.
String data = in.readLine(); out.println("Hey! I heard you over this socket!");

When a server invokes the accept() method of the ServerSocket instance, the main server thread blocks until
a client connects to the server; it is then prevented from accepting further client connections until the server
has processed the client's request. This is known as an iterative server, since the main server method handles
TCP client
To create a TCP client, do the following:
1. Create a Socket object attached to a remote host, port.
Socket client = new Socket(host, port);
2. . Get input and output streams associated with the socket.
out = new PrintWriter (client.getOutputStream());
reader = new InputStreamReader (client.getInputStream());
in = new BufferedReader (reader);
3. Now you can read and write to the socket, thus, communicating with the server.
out.println(“Hello!" + “My friend);
String data = in.readLine();
Multicasting in Network programming
MulticastSocket is a subclass of DatagramSocket that represents a UDP socket with
capabilities for joining multicast groups on the Internet.
• Communicating with a multicast group
1. Construct a multicast socket
2. Join a multicast group (for receiving)
3. Send/receive data to/from the multicast group
4. Leave the group
Secure communication protocols

Secure Socket Layer (SSL)


SSL is a communication protocol that creates secure connexion between two devices or
applications in a network

Transport Layer Security(TLS):


The upgrade version of SSL
It enables encryption and authentication
Main characteristics of SSL and TLS protocols

SSL/TLS handshakes
Authentication process to check SSL/TLS certificates
After successful authentication, both communication parties exchange security keys
Alert messages:
Two alert messages for SSL and additional alerts for TLS, for TLS messages are encrypted
Message authentication
SSL and TLS use message authentication codes (MACs), a cryptographic technique for verifying the authenticity and
integrity of messages. By using a secret key, the record protocol generates the MAC as a fixed-length code and attaches it to
the original message.
The SSL protocol uses the MD5 algorithm—which is now outdated—for MAC generation. TLS uses Hash-Based Message
Authentication Code (HMAC) for more complex cryptography and security.
Cipher suites
A cipher suite is a collection of algorithms that create keys to encrypt information between a browser and a server. Typically,
a cipher suite includes a key exchange algorithm, a validation algorithm, a bulk encryption algorithm, and a MAC
algorithm. Several algorithms in TLS were upgraded from SSL due to security concerns.
Main characteristics of SSL and TLS protocols: Cypher
suite for TLS1.0

Key exchange Authentification Block/Stream Cypher Msg authentification


agreement
DH DH RC4 Hash based MD5
RSA RSA Triple DES Secure Hash Algorithm
Elliptic-curve Diffie– Elliptic Curve Digital Advanced Encryption
Hellman(ECDH) Signature Standard (AES)
Secure Remote Algorithm (ECDSA) International Data
Password Encryption
protocol (SRP) Algorithm (IDEA)
Data Encryption
Standard (DES)
JSSE (Java Secure Socket Extension)
A set of Java packages that enable secure Internet communications.
– Implements a Java version of SSL (Secure Sockets Layer) and TLS (Transport Layer Security)
protocols
– Includes functionality for data encryption, server authentication, message integrity, and optional
client authentication.

Examples of packages:
– javax.net.ssl : Package that provides classes for the secure socket,
SSLSocket: This class extends ServerSocket s and provides secure server sockets using protocols
such as the Secure Sockets Layer (SSL) or Transport Layer Security (TLS)
– java.security.cert : It contains support for X.509 v3 certificates and X.509 v2 CRLs

JSSE on the Web:


http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136007.ht ml
http://download.oracle.com/javase/8/docs/technotes/guides/security/
Network Programming and Security

Chapter IV
Security
Network Programming and Security

Chapter V
Additional Considerations

You might also like