Chatter - Sogang University Computer Security and Forensics Lab
Download
Report
Transcript Chatter - Sogang University Computer Security and Forensics Lab
JAVA Programming Language
Chapter 10. Networking with Java.net
Juho Kim
Department of Computer Science and Engineering
Sogang University
10 - 1
Networking program with java
TCP/IP Networking Concept
Internet Address and URL
TCP Socket
Java Code Security
10-2
TCP/IP Internet Layering Model
– Application layer ; support user application
– Transport layer ; transmission control protocol (TCP) provides reliability
of exchanging data, flow control, and packets
– Internet layer ; internet protocol (IP) provides routing function across
multiple networks. Encapsulating packet in an IP datagram (fills header
and uses routing alg.)
– Network access layer ; circuit switching, packet switching (e.g., X.25),
local area network (Ethernet)
– Physical layer ; physical interface between devices and a transmission
medium or network
10-3
Internet address and URL
– InetAddress class
java.lang.Object
|
+ -- java.net.InetAddress
public final class InetAddress
extends Object
implements Serializable
This class represents an Internet Protocol (IP) address.
Applications should use the methods getLocalHost, getByName, or
getAllByName to create a new InetAddress instance.
10-4
10-5
AddressTest.java
import java.net.*;
class AddressTest
{ public static void main(String args[])
throws UnknownHostException
{ InetAddress Address = InetAddress.getLocalHost();
System.out.println("Local Host Name : " + Address.getHostName());
System.out.println("Local Host IP Address : " + Address.getHostAddress());
Address = InetAddress.getByName("sogang.ac.kr");
System.out.println("sogang.ac.kr's computer name and IP Address : " + Address);
InetAddress sw[] = InetAddress.getAllByName("www.ibm.com");
for (int i = 0; i < sw.length; i++)
System.out.println(sw[i]);
}
}
10-6
URL class
– Class URL represents a Uniform Resource Locator, a pointer to a
"resource" on the World Wide Web. A resource can be something as
simple as a file or a directory, or it can be a reference to a more
complicated object, such as a query to a database or to a search engine.
More information on the types of URLs and their formats can be found at:
http://www.ncsa.uiuc.edu/demoweb/url-primer.html
– In general, a URL can be broken into several parts. The previous
example of a URL indicates that the protocol to use is http (HyperText
Transport Protocol) and that the information resides on a host machine
named www.ncsa.uiuc.edu. The information on that host machine is
named demoweb/url-primer.html. The exact meaning of this name on
the host machine is both protocol dependent and host dependent. The
information normally resides in a file, but it could be generated on the fly.
This component of the URL is called the file component, even though the
information is not necessarily in a file.
10-7
– A URL can optionally specify a "port", which is the port number to which the TCP
connection is made on the remote host machine. If the port is not specified, the
default port for the protocol is used instead. For example, the default port for http
is 80. An alternative port could be specified as:
http://www.ncsa.uiuc.edu:8080/demoweb/url-primer.html
– A URL may have appended to it an "anchor", also known as a "ref" or a
"reference". The anchor is indicated by the sharp sign character "#" followed by
more characters. For example, http://java.sun.com/index.html#chapter1 This
anchor is not technically part of the URL. Rather, it indicates that after the
specified resource is retrieved, the application is specifically interested in that part
of the document that has the tag chapter1 attached to it. The meaning of a tag is
resource specific.
– An application can also specify a "relative URL", which contains only enough
information to reach the resource relative to another URL. Relative URLs are
frequently used within HTML pages. For example, if the contents of the URL:
http://java.sun.com/index.html contained within it the relative URL: FAQ.html it
would be a shorthand for: http://java.sun.com/FAQ.html The relative URL need
not specify all the components of a URL. If the protocol, host name, or port
number is missing, the value is inherited from the fully specified URL. The file
component must be specified. The optional anchor is not inherited.
10-8
10-9
Methods summary
10-10
urlTest.java
import java.net.*;
class urlTest
{ public static void main(String args[]) throws MalformedURLException
{
URL location = new URL("http://sogang.ac.kr");
System.out.println("protocol : " + location.getProtocol());
System.out.println("port : " + location.getPort());
System.out.println("host : " + location.getHost());
System.out.println("file : " + location.getFile());
System.out.println("URL " + location.toExternalForm());
}
}
10-11
–
– URLConnection class
• The abstract class URLConnection is the superclass of all classes that
represent a communications link between the application and a URL.
Instances of this class can be used both to read from and to write to the
resource referenced by the URL.
• The following methods are used to access the header fields and the contents
after the connection is made to the remote object:
getContent
getHeaderField
getInputStream
getOutputStream
– Certain header fields are accessed frequently. The methods:
getContentEncoding
getContentLength
getContentType
getDate
getExpiration
getLastModifed
provide convenient access to these fields. The getContentType method is used by the
getContent method to determine the type of the remote object; subclasses may find it
convenient to override the getContentType method.
10-12
urlConnectionTest.java
import java.util.Date;
class urlConnectionTest
{ public static void main(String args[]) throws Exception
{ int c;
URL addr = new URL("http://www.sogang.ac.kr/wwwnew/index2.html");
URLConnection addrConnection = addr.openConnection();
System.out.println("Document Type : " + addrConnection.getContentType());
System.out.println("Last Modified : " +
new
Date(addrConnection.getLastModified()));
int len = addrConnection.getContentLength();
System.out.println("Document Length : " + len + "byte");
if (len > 0)
{ System.out.println(" ===== Contents ======= ");
InputStream input = addrConnection.getInputStream();
int i = len;
while (((c = input.read()) != -1) && (--i > 0))
{ System.out.print((char) c); }
input.close(); }
else
{ System.out.println("No Contents"); }
}}
10 -13
Ports
– To identify different applications, tag each datagram with a port number.
– The UDP(or TCP) decides which application should receive the datagram
by comparing the port number with ports currently in use.
– Each application program negotiates to obtain a protocol field and
associated port number before it sends a UDP(TCP) datagram.
– Usually the port number points to an internal queue created by the
Operating System
– Application as client should know in advance the port number for the
particular application in the server.
– Application as a server can obtain the port number of the client on
receiving the first request.
10 -14
Socket interface
Client
Server
Net
Input Stream
Socket
Socket
10 -15
Ouput Stream
Socket interface
–
–
–
–
–
Interface between application programs and TCP/IP protocols.
Interface depends on operating systems.
Socket is not considered as protocols (just an application, not standard).
Used for network I/O: similar to file descriptor for file I/O in UNIX
File I/O in UNIX: Open-Read-Write-Close paradigm
• Open returns an integer file descriptor --> user process uses the
number for accessing the file
• Read transfers data into user process.
• Write transfers data from the user process to the file or device.
• Close is called by the user process to terminate the process.
– With file access application programs request the operating system to
create a socket
• The system returns a small integer that the application program uses
to reference the newly created socket.
10 -16
10 -17
10 -18
– ServerSocket class
ServerSocket(int port)
Creates a server socket on a specified port.
ServerSocket(int port, int backlog)
Creates a server socket and binds it to the specified local port
number.
ServerSocket(int port, int backlog, IntAddress bindAddr)
Create a server with the specified port, listen backlog, and local IP
address to bind to.
10 -19
ServerSide.java
import java.io.*;
import java.net.*;
class ServerSide
{ public static void main(String args[])
{ try
{ int port = Integer.parseInt(args[0]);
ServerSocket ss = new ServerSocket(port);
while(true)
{ Socket s = ss.accept();
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
for (int i = 1; i <= 10; i++)
dos.writeInt(i);
s.close();
}}
catch(Exception e)
{ System.out.println("Exception: " + e);
}}}
10 -20
ClientSide.java
import java.io.*;
import java.net.*;
class ClientSide
{ public static void main(String args[])
{ try
{ String server = args[0];
int port = Integer.parseInt(args[1]);
Socket c = new Socket(server, port);
InputStream is = c.getInputStream();
DataInputStream dis = new DataInputStream(is);
for (int i = 1; i <= 10; i++)
{ int j = dis.readInt();
System.out.println("data from server " + j);
}
c.close();}
catch(Exception e)
{ System.out.println("Exception: " + e);
}}}
10 -21
Java Networking – Chatting program
ChatServer
ChatClient
ChatManager
ChaterManager
ChatRoomManager
Socket
readSocketThread
ChatRoom
writeSocketThread
Socket
Chatter
Chatter
N
e
t
ChaterManager
readSocketThread
writeSocketThread
Chatter
10 - 22
Java Networking – Chatting program
ChatServer: server chatting program
– ChatManager: port assignment and socket creation, waiting for reply from
client’s socket
– ChatRoomManager: ChatRoom(initially one) creation and managing chatter
connection
– ChatRoom: chatter managing with Vector
– Chatter: wating for message and forward messages to chatters in ChatRoom
ChatClient: client chatting program
– ChatterManager: server address, port number assignment, socket creation
and connection
– readSocketThread: getting messages from socket and sending to console
– writeSocketThread: getting messages from keyboard and sending to socket
* KSC5601:Korean complete code
10 - 23
import java.io.*;
import java.net.*;
import java.util.*;
class Chatter{
private
private
private
private
private
ChatServer.java
Socket clientSocket;
BufferedReader br;
PrintWriter pw;
ChatRoom chatRoom;
String chatterID;
Chatter (ChatRoom chatRoom, Socket clientSocket, String chatterID) {
System.out.println ("Chatter gets created : " + chatterID);
try
{
}
this.chatRoom = chatRoom;
this.clientSocket = clientSocket;
this.chatterID = chatterID;
br = new BufferedReader (new InputStreamReader
(clientSocket.getInputStream()));
pw= new PrintWriter(new BufferedWriter(new
OutputStreamWriter(clientSocket.getOutputStream())));
(new readSocketThread()).start();
} catch (Exception e) { System.out.println(e.toString()); }
10 - 24
ChatServer.java
public void sendMessage(String message) {
pw.println(message);
pw.flush();
}
class readSocketThread extends Thread {
String inputString = null;
public void run() {
try {
while (true) {
inputString = br.readLine();
chatRoom.chatEveryChatter(inputString);
}
} catch ( Exception e ) { System.out.println(e.toString()); }
}
}
}
10 - 25
ChatServer.java
class ChatRoom {
private String roomName;
private Vector joinChatters = new Vector();
private Chatter roomMaker;
}
ChatRoom(String roomName) {
System.out.println("room is ready. : " + roomName);
this.roomName = roomName;
this.roomMaker = null;
}
public synchronized void joinChatter( Chatter chatter ) {
joinChatters.add(chatter);
}
public synchronized String getName() {
return roomName;
}
public synchronized void chatEveryChatter(String message ) {
for ( int i = 0 ; i < joinChatters.size() ; i++) {
((Chatter)joinChatters.get(i)).sendMessage(message);
}}
public int size() {
return joinChatters.size() ;
}
10 -26
class ChatRoomManager {
private Vector chatRooms = new Vector();
ChatServer.java
ChatRoomManager() {
System.out.println("ChatRoomManager Starting. ");
chatRooms.add(new ChatRoom("waiting room"));
}
}
public void makeRoom(String roomName) {
}
public void deleteRoom(String roomName) {
}
public void enterRoom(String roomName, Socket clientSocket) {
Chatter chatter = null;
ChatRoom tempRoom = null;
boolean exitFor = false;
for ( int i = 0; exitFor == false && i < chatRooms.size(); i++ ) {
tempRoom = (ChatRoom)chatRooms.get(i);
if (tempRoom.getName().equals(roomName)) {
chatter = new Chatter(tempRoom, clientSocket,
String.valueOf(tempRoom.size() + 1));
tempRoom.joinChatter(chatter);
exitFor = true;
}
}
}
public void exitRoom(Chatter chatter) { }
10 -27
class ChatManager {
private int serverPort;
ChatServer.java
private ServerSocket serverSocket;
private ChatRoomManager chatRoomManager;
ChatManager(int serverPort ) {
System.out.println("Chatting Manager Starting");
try {
this.serverPort = serverPort;
chatRoomManager = new ChatRoomManager();
serverSocket = new ServerSocket(serverPort);
new listenerThread().start();
} catch (Exception e) {
System.out.println(e.toString()); }
}
class listenerThread extends Thread {
private boolean stopListener = false;
Socket clientSocket = null;
public void run() {
try { while ( !stopListener ) {
System.out.println("Waiting Client.");
clientSocket = serverSocket.accept();
chatRoomManager.enterRoom("waiting room",clientSocket);
System.out.println("Connection Established form : " +
clientSocket.getInetAddress().getHostAddress());
}
} catch (Exception e ) { System.out.println(e.toString()); }
}
}
}
10 -28
ChatServer.java
public class ChatServer {
public static void main(String [] args) {
if (args.length < 1 ) {
System.out.println("Usage : Java ChatServer port:#");
return;
}
System.out.println("Chatt;ng Server Starting. ");
ChatManager cm = new ChatManager(Integer.parseInt(args[0]));
}
}
10 -29
ChatClient.java
import java.io.*;C
import java.net.*;
class ChatterManager {
private String serverIP;
private int serverPort;
private Socket clientSocket;
private BufferedReader br;
private PrintWriter pw;
private BufferedReader keyboard;
ChatterManager(String serverIP, int serverPort) {
try {this.serverIP = serverIP;
this.serverPort = serverPort;
clientSocket = new Socket(serverIP, serverPort);
br = new BufferedReader( new InputStreamReader( clientSocket.getInputStream()));
pw = new PrintWriter(new BufferedWriter( new
OutputStreamWriter(clientSocket.getOutputStream())));
keyboard = new BufferedReader(new InputStreamReader(System.in, "KSC5601"));
(new readSocketThread()).start();
(new writeSocketThread()).start();
} catch (Exception e) {
System.out.println(e.toString());
}
}
10 -30
ChatClient.java
class readSocketThread extends Thread {
public void run() {
try { while(true) { System.out.println(br.readLine()); }
}catch (Exception e) { System.out.println(e.toString()); }
}
}
class writeSocketThread extends Thread {
String inputString = null;
public void run() {
try{
while ( (inputString = keyboard.readLine()) != null) {
pw.println(inputString);
pw.flush(); }
} catch (Exception e ) { System.out.println(e.toString()); }
}
}
}
public class ChatClient {
public static void main (String [] args) {
if (args.length < 2 ) {
System.out.println("Usage : java ChatServer ip port#");
return;
}
ChatterManager cm = new ChatterManager(args[0], Integer.parseInt(args[1]));
}
}
10 -31
Security Problem in Networking
DoS(Denial of Service) : Attack by increasing simultaneously
connected user or increasing load beyond server’s capability
DDoS: DoS in many places at short period of time
Sniffing: tapping information between client and server
Spoofing: Fooling server by false information using IP address, host
name, and MAC address
ChatClient
Hacker
Chatter
Thread
Socket
Thread
Net
Socket
Thread
10 - 32
Security Problem in Networking
Attack using Applet
– Inserting trojan-horse to applet and illegal resource access
– Making backdoor to steal server’s information
– Code change during applet code transmission
Source
Code
Web Server
Compiler
Byte
Code
Internet
External Control over
System Resources
10 - 33
Web Browser
JVM
Local System
Resources
Overview of Java Security features
Java Technology uses three mechanisms to ensure safety
– Language design features(bounds checking on array, legal type
conversions etc)
– An access control mechanism that controls what the code can do
(file access, network access etc)
– Code signing: code authors can use standard cryptographic algorithms
to authenticate java programming language code. Users of the code
can determine who created the code and whether the code is altered
or not after it was signed
10- 34
Java 2 Security Architecture
Bootstrap
class files
System
class files
1st Stage:
Verify user classes
2st
Stage:
Loading Classes
User class
files
Bytecode Verifier
Bootstrap
ClassLoader
JVM
Policy Database
System
ClassLoader
ClassLoader
Permissions
3st Stage:
Running Application
Security Manager
Protection Domains
AccessController
Keystore
Operating System
10 - 35
Stage 1: Verify User Classes
By default
– Only built-in code (Core API) is trusted
Applet
Class
File
– Local, remote code (Applet) is untrusted
Bytecode Verifier: performs checks on untrusted class file
for validity
– Goal is to prevent access to underlying machine
– Code only has valid instructions & register use
– Code does not overflow/underflow stack
– Does not convert data types illegally or forge pointers
– Accesses objects as correct type
– Method calls use correct number & types of arguments
– References to other classes use legal names
10 - 36
Bytecode
Verifier
JVM
Class
Loader
Stage 2: Loading Classes
Class Loader: uses dynamic linking to load classes at
runtime
– classes loaded by a class loader instance belong to the
same name space
– since classes with the same name may exist on different
Web sites, different Web sites are handled by different
instances of the applet class loader
– a class in one name space cannot access a class in
another name space (classes from different Web sites
cannot access each other)
– establish the protection domain (set of permissions) for
a loaded untrusted class (sandbox)
– It works in conjunction with the security manager and
access controller to enforce security rules.
trusted
local.class
sandbox
Valuable Resource
10 - 37
Applet
Class
File
Bytecode
Verifier
JVM
Class
Loader
untrusted
Remote.class
Stage 3: Running Application
Security Manager
JAVA
Class
– Core component for implementing a custom Policy
– Queried by the JVM each time untrusted code
attempts to access a system resource
– Uses Access Controller to see if queries are
permitted, throws a generic Security Exception
otherwise
JVM
Security
Manager
Access Controller
– Invoked by the Security Manager
– Decide whether access to a critical system resource
should be allowed or denied, based on the security
policy currently in effect.
10 - 38
System
Resource
Stage 3: Running Application
Permission (Policy Class)
– Manages class permissions to system resources
– Policy assigns each class to a Protection Domain
– Protection Domains: can associate one or more classes with a set of
permissions
Keystore
– Keystore is a password-protected database that holds private keys and
certificates used for code signing (in next slide)
10 - 39
Code signing
Code signing
– code authors can use standard cryptographic algorithms of JCA to
authenticate java programming language code.
– Users of the code can determine who created the code and whether the
code is altered or not after it was signed
Java Cryptography Architecture (JCA)
–
–
–
–
–
–
–
Provides many different security services
digital signatures
message digests: MD5, SHA-1
certificates and certificate validation
symmetric/asymmetric block/stream ciphers encryption: DSA, RSA
key generation and management
secure random number generation
10 - 40
Code signing
Ex: Code signing with JCA
– Hash and asymmetric encryption algorithm can be used to verify code
integrity and validity of source
Web Server
Byte
Code
Internet
Byte Code
+ Signature(
certificate)
JVM
Compare
Signature
Generate
Signature with
Public key
Code Digest
Hash Algorithm
Generate
Signature with
Private key
Web Browser
Asymmetric Key
Crypto Algorithm
10 - 41
Code Digest
Byte
Code