Wednesday, February 23, 2011

IPSEC 1

Cryptographic Terms and Techniques

One-way functions

방향으로 계산하는 방법그러나 역으로 계산하는 것이 불가능하거나 상당히 어렵다.

Trapdoors

비밀 문장 같은 것을 이용해 암호화를 침투하는 방법.

Confidentiality

암호와 알고리즘을 이용해 문을 암호문으로 바꾸고 다시 원래의 데이터로 복귀 가능하게 하는 기밀성.

Symmetric Ciphers

1.       특정 입력 값에 대해 암호화를 수행한다.
2.       하나의 키로 암호화 복호화를 수행한다.
3.       가지 타입의 입력이 있다.

    Block Cipher

    1.       블록단위로 연산을 수행한다.
    2.       IPSec에서 독점적으로 사용하는 방법이다.
    Ex) DES, CAST, Blowfish
    Various Mode in Block Cipher
    블록들은 체인을 구성하는데 먼저 연산된 블록은 다음 연산될 블록에 추가되어 연산된다.
            Electronic Code Book (ECB)
             평문형태의 블록은 암호화 형태의 블록으로 암호와 된다. 평문블록과 암호화 
            블록은 동일한 키로 암호화 호화가 가능하기 때문에 code book 생성이 가능하다.                
          즉 특정블록에 대한 키를 code book에서 찾아 암호화 호화가 가능하다.
            Padding
            입력블록이 여러 개일 경우 마지막 블록의 사이즈를 같게 하기 위해 마지막 블록에  
            추가된다.
            Cipher Block Chaining (CBC)
            1.       블록과 다음블록을 XOR 연산을 수행한다.
            2.       번째 블록은 Initialization Vector (IV) XOR연산을 수행한다.
            3.       IPSec CBC 모드의 Block Cipher 연산을 수행한다.
            Cipher Feedback Mode (CFB)
            Output Feedback Mode (OFB)


     Stream Cipher
    한 비트단위로 연산을 수행한다.

Asymmetric Ciphers

공개키 알고리즘으로 알려져 있으며 공개 키와 비밀키 개를 갖는다. 비밀키로 암호화된 문은 공개키로 복호화 되고 공개키로 암호화된 문은 비밀키로 복호화한다.
Ex)
RSA: 가장 많이 사용하는 공개키 알고리즘이다.
El-Gamal

Authentication And Message Integrity

Confidentiality 비밀을 보장하는데 중요하다. 그러나 Authentication 보장이 된다면 현재 누구와 비밀을 공유하고 있는지 수가 없으며 받은 데이터에 대한 Integrity 보장할 수가 없다.
Message Authentication Codes (MACs)
Authentication 정보를 검증하고 생성하기 위해 개의 키를 사용한다.



TCP/IP Overview




Reference : IPSec, The New Security Standard for the Internet, Intranets, and Virtual Private Networks

Thursday, February 3, 2011

IPC (Inter Process Communication) - English

IPC Introduction

Introduction

IPC means communication among processes, traditionally it used various types of method to transfer messages, but lately new methods are introduced such as shared memory. So following sections will describe various types of synchronization among processes.

For the past 30 years, transferring message in Unix O/S has been changed as below.
1.       Pipes
were the first widely used form of IPC, available both within programs and from the shell. The problem with pipes is that they are usable only between processes that have a common ancestor.
2.       System V message queues
were added to System V kernels in the early 1980s. These can be used between related or unrelated processes on a given host.
3.       Posix message queues
were added by Posix realtime standard.
4.       Remote Procedure Calls
were introduced in mid 80s. It is being used to call remote function call between heterogeneous systems.

Processes, Threads, and the Sharing of Information

The information among Unix processes can be shared as below diagram.
Different Data Sharing

Threads
For long time, Unix used process method. The concept of thread was introduced lately. Posix. 1 thread standard is accepted in 1995. Since threads are sharing information by global variable, there are several methods to synchronize shared data.

Persistence of IPC Objects

1.       Process-persistent IPC
It exists till the last process, which owns the IPC object, closes the IPC object. 
2.       Kernel-persistent IPC
It exists till kernel is rebooted or IPC object is removed forcefully.
3.       Filesystem-persistent IPC
It exists till it is deleted forcefully.

System V IPC

Introduction

Three types of IPCs are as below.
·         System V message queues
·         System V semaphores
·         System V shared  memory

Following is api lists which can control each IPC object.


Message queues
Semaphores
Shared memory
Header
sys/msg.h
sys/sem.h
sys/shm.h
Function to create or open
msgget
semget
shmget
Function for control operations
msgctl
semctl
shmctl
Functions for IPC operations
msgsnd
msgrcv
semop
shmat
shmdt











 Summary of System V IPC functions.

key_t Keys and ftok Function

key_t type might be defined 32bit integer in sys/types.h. ftok function accepts integer type id and pathname and returns key_t type.

#include
key_t ftok(const char *pathname, int id);
                                      returns: IPC key if OK, -1 or error
It will generate IPC key combining low-order 8bit of pathname and id.

ipc_perm Structure

Kernal manages IPC object same like file and the structure is as below.
struct ipc_perm
{
   uid_t  uid;      // owner’s user id
   gid_t  gid;      // owner’s group id
   uid_t  cuid;  // creator’s user id
   gid_t  cgid;  // creator’s group id
   mode_t mode;  // read-write permissions
   ulong_t   seq;      // slot usage sequence number
   key_t  key;      // IPC key
};

Creating and Opening IPC Channels

Three get_xxx functions can be used to create or open IPC object and all functions get integer identifier using IPC key value.
There are two ways to pass function argument.
1. Calls ftok function using pathname and id.
2. Specify Key as IPC_PRIVATE then new IPC object will be uniquely created.
Generating IPC identifiers from IPC keys

All get_xxx functions have read-write permissions.
1. If key is IPC_PRIVATE, it guarantees creating unique IPC object.
2. If oflag is set as IPC_CREATE, it will create new entry to specific key if entry doesn't exist, otherwise it will return existing entry.
3. if oflag is set IPC_CREATE and IPC_EXCL, it only create new entry when there is no entry otherwise it will return EEXIST.

Following is summery as diagram.

Logic for creating or opening an IPC object

Shared Memory

Shared Memory Introduction

Shared memory is most fast among IPC since it doesn't need kernel help. You may understand easily with following diagram.
Flow of file data from server to client
Copying file data from server to client using shared memory

System V Shared Memory

Introduction

All shared memory segment has shmid_ds struct which is defined in sys/shm.h.
struct shmid_ds
{
   struct ipc_perm  shm_perm; // operation permission struct
   size_t        shm_segsz; // segment size
   pid_t         shm_lpid; // pid of last operation
   pid_t         shm_cpid; // creator pid
   shmatt_t         shm_nattch;   // current # attached
   shmat_t          shm_cnattch;  // in-core # attached
   time_t        shm_atime; // last attach time
   time_t        shm_dtime; // last detach time
   time_t        shm_ctime; // last change time of this structure
}

shmget Function

Creates shared memory or accesses existing shared memory.
#include
int shmget(key_t key, size_t size, int oflag);
                     returns: shared memory identifier if OK, -1 on error
Return value would be shared memory identifier and will be used to access shared memory by other three shm_xxx functions.
Size is size of shared memory segment. Oflag means permission for read-write.

shmat  Function

shmat function can access shared memory after it is opened or created.
#include
void *shmat(int shmid, const void *shmaddr, int flag);
              returns: starting address of mapped region if OK, -1 on error
shmid is return value from shmget. The return value of shmat is shared memory starting address.

shmdt Function

Detaches from shared memory when the process finishes.
#include
int shmdt(const void *shmaddr);
                                         returns: 0 if OK, -1 on error
Calling shmdt doesn't mean that it removes shared memory segment.

shmctl Function

Provides various functions related shared memory.
#include
int shmctl(int shmid, int cmd, struct shmid_ds *buff);
                                         returns: 0 if OK, -1 on error


IPC_RMID
Remove the shared memory segment identified by shmid from the system and destroy the shared memory segment
        IPC_SET
Set the following three members of the shmid_ds structure for the shared memory segment from the corresponding members in the structure pointed to by the buff argument: shm_perm.uid, shm_perm.gid, and shm_perm.mode. The shm_ctime value is also replaced with the current time.
        IPC_STAT
Return to the caller(through the buff argument) the current shmid_ds structure for the specified shared memory segment

* referenced by
Unix Network Programming (Interprocess Communications) by W. Richard Stevens

IPC (Inter Process Communication) - Korean

IPC Introduction

Introduction

IPC 프로세스간의 통신을 의미하며 전통적으로는 서로 다른 프로세스간의 여러 가지 메시지 전송 방법을 의미하였지만 최근에는 공유메모리 같은 새로운 방법이 도입되어 동기화 여러 가지 방법을 소개한다.
최근 30년간 유닉스 운영체제의 진화과정에서 메시지 전송방식은 아래와 같이 변화되어왔다.
1.       Pipes
IPC에서 가장 널리 쓰이며 특히 프로그램이나 셀에서 가장 많이 쓰는 방식이며 프로세스는 동일한 조상 프로세스(부모-자식 프로세스 관계) 가지고 있어야 하는 단점이 있다.
2.       System V message queues
80년도 System V 커널에 도입되었으며 특정 호스트 내에서는 프로세스간의 관계가 없어도 메시지 전송이 가능하다.
3.       Posix message queues
Posix realtime standard 의해서 추가되었다.
4.       Remote Procedure Calls
80년대 중반에 소개되었으며 기종간의 함수호출에 사용되어진다.

Processes, Threads, and the Sharing of Information

유닉스 프로세스간의 정보 공유는 아래와 같이 여러 가지 방법으로 공유되어질 있다.
Different Data Sharing

Threads
오랫동안 유닉스 시스템은 프로세스 방식을 사용해왔으며 쓰레드 개념이 나온지는 최근이다. Posix.1 쓰레드 표준이 승인된 것이 1995년이다. 주어진 프로세스내의 쓰레드는 전역변수를 공유하므로 변수 공유 동기화 문제가 발생한다. 공유데이터 동기화 하는 여러 가지 방법이 제공된다.

Persistence of IPC Objects

IPC 객체의 생성 소멸기간은 다음과 같이 세가지로 분류되어진다.
1.       Process-persistent IPC
Open IPC 객체를 소유한 마지막 프로세스가 IPC 객체를 close 때까지 존재한다.
2.       Kernel-persistent IPC
커널이 재부팅 되거나 강제로 IPC 객체를 지울 때까지 존재한다.
3.       Filesystem-persistent IPC
강제로 IPC 객체를 지울 까지 존재한다.

System V IPC

Introduction

세가지의 IPC 아래와 같다.
·         System V message queues
·         System V semaphores
·         System V shared  memory

각각의 함수는 다음과 같다.


Message queues
Semaphores
Shared memory
Header
sys/msg.h
sys/sem.hsys/shm.h
Function to create or open
msgget
semget
shmget
Function for control operations
msgctl
semctl
shmctl
Functions for IPC operations
msgsnd
msgrcv
semop
shmat
shmdt











 Summary of System V IPC functions.

key_t Keys and ftok Function

sys/types.h 에서 key_t type 정의하는데 보통 32bit 정수형으로 정의된다. ftok 함수는 pathname 정수형 id 입력받아 key_t type 값을 리턴한다.

#include
key_t ftok(const char *pathname, int id);
                                      returns: IPC key if OK, -1 or error
함수는 pathname id low-order 8bit 조합으로 정수형 IPC 키를 생성한다.

ipc_perm Structure

커널은 파일을 관리하는 것처럼 IPC 객체에 대한 정보도 관리하는데 아래와 같은 구조체로 되어있다.
struct ipc_perm
{
   uid_t  uid;      // owner’s user id
   gid_t  gid;      // owner’s group id
   uid_t  cuid;  // creator’s user id
   gid_t  cgid;  // creator’s group id
   mode_t mode;  // read-write permissions
   ulong_t   seq;      // slot usage sequence number
   key_t  key;      // IPC key
};

Creating and Opening IPC Channels

개의 get_XXX 함수는 IPC 객체를 생성하거나 열수 있는데 모두다 IPC key 값을 이용하여 정수형 identifier 얻는다. 함수의 인자로 값을 넣을 가지  방법이 있다.
1.       Pathname id 이용하여 ftok 함수를 호출한다.
2.       Key IPC_PRIVATE 명시한다. Key IPC_PRIVATE이면 IPC 객체가 새롭고 유일하게 생성된다.
Generating IPC identifiers from IPC keys

모든 get_XXX 함수들은 read-write permission  갖는다.
1.       Key IPC_PRIVATE이면 유일한 IPC 객체가 생성되는 것을 보장한다.
2.       oflag 비트를 IPC_CREATE 설정했을 엔트리가 존재하지 않으면 특정 키에 대한 새로운 엔트리를 생성하고 기존에 있다면 기존의 엔트리를 리턴한다.
3.       oflag 비트를 IPC_CREATE IPC_EXCL 설정했을 때는 기존에 엔트리가 존재하지 않을 때만 새로운 엔트리를 생성하고 존재한다면 오류상수 EEXIST 리턴한다.

요약하면 아래 그림과 같다.
Logic for creating or opening an IPC object

Shared Memory

Shared Memory Introduction

공유 메모리는 IPC중에서 가장 빠르다. 메모리가 프로세스 어드레스 스페이스에 한번 매핑만 되면 프로세스간의 데이터 전송 커널의 개입이 필요치 않다.
아래의 그림을 보면 이유가 설명이 것이다.
Flow of file data from server to client
Copying file data from server to client using shared memory

System V Shared Memory

Introduction

모든 공유메모리 세그먼트는 sys/shm.h 에서 정의된 shmid_ds 구조체를 가지고있다.
struct shmid_ds
{
   struct ipc_perm  shm_perm; // operation permission struct
   size_t        shm_segsz; // segment size
   pid_t         shm_lpid; // pid of last operation
   pid_t         shm_cpid; // creator pid
   shmatt_t         shm_nattch;   // current # attached
   shmat_t          shm_cnattch;  // in-core # attached
   time_t        shm_atime; // last attach time
   time_t        shm_dtime; // last detach time
   time_t        shm_ctime; // last change time of this structure
}

shmget Function

공유메모리를 생성하거나 기존의 공유메모리를 접근한다.
#include
int shmget(key_t key, size_t size, int oflag);
                     returns: shared memory identifier if OK, -1 on error
리턴값을 공유메모리 identifier 라고 하며 공유메모리를 접근하기위한 나머지 세개의 shm_XXX 의해 사용되어진다.
Size 바이트 단위의 공유메모리 세그먼트의 크기를 나타낸다. Oflag read-write 권한을 의미한다.

shmat  Function

공유메모리 세그먼트가 생성되거나 개방된후 shmat 함수 호출로 메모리 접근을 할수있다.
#include
void *shmat(int shmid, const void *shmaddr, int flag);
              returns: starting address of mapped region if OK, -1 on error
shmid shmget함수에서 린턴된 값이다. Shmat 리턴값은 공유메모리의 시작번지이다

shmdt Function

프로세스가 끝났을 공유메모리를 detatch 한다.
#include
int shmdt(const void *shmaddr);
                                         returns: 0 if OK, -1 on error
shmdt 함수 호출로 공유메모리 세그먼트가 지워지는 것은 아니다.

shmctl Function

공유메모리에 관계된 여러가지 기능을 제공한다.
#include
int shmctl(int shmid, int cmd, struct shmid_ds *buff);
                                         returns: 0 if OK, -1 on error

세게의 command 제공된다.
IPC_RMID
Remove the shared memory segment identified by shmid from the system and destroy the shared memory segment
        IPC_SET
Set the following three members of the shmid_ds structure for the shared memory segment from the corresponding members in the structure pointed to by the buff argument: shm_perm.uid, shm_perm.gid, and shm_perm.mode. The shm_ctime value is also replaced with the current time.
        IPC_STAT
Return to the caller(through the buff argument) the current shmid_ds structure for the specified shared memory segment

* referenced by
Unix Network Programming (Interprocess Communications) by W. Richard Stevens