본문 바로가기
Programming

ipsec 정리

by homecafe 2009. 10. 16.


Read: 3  
  ipsec 정리  
Author: 이윤수    
Date: 2002-03-05 오전 11:32:47 from '211.38.3.65' of '211.38.3.65'

IPSec - 무결성 (AH) : 50
- 비밀성 (ESP) : 51
AH
- 전송데이터의 무결성
- 출발지 주소 인증
- antireplay

ESP
- data의 비밀성
- antireplay
- data 무결성(확장기능)

mode - 보호영역의 차이
- tunnel_mode :IP datagram 전체 / 둘중 하나라도 IPSec을 지원하지 않을때 사용
- transport_mode : IP 상위레이어를 보호 / end-to-end가 IPSec을 처리

접속형태
gw - gw (lan - lan)
client - gw
client - client (end-to-end)

selector (IP주소, port, 사용자)

SPI
SPD - 어떤 traffice을 어떻게 처리할것인가
( selector) (action)

SA - packet을 processing 하기위한 (IPSec Processing)에 필요한 정보
(encryption algorithm,
key(암호, 인증), 터널의 peer, lifetime(시간, data량),
seq number, SPI)
IPSec SA의 특성
1. 양단간에 같은 SA가 존재 (A key = B key , A SPI = B SPI)
2. 주기적으로 변경됨
3. 단방향 < Inbound > 가 pair로 존재함.
< Outbound >
----------------
  IPSec 7. IKE  
Author: 이윤수    
Date: 2002-02-26 오후 6:54:24 from '211.237.240.191' of '211.237.240.191'

Chapter 7 IKE

RFC2409. IKE is a hybrid protocol. based on ISAKMP(RFC 2408) and implements parts of two key management
protocols(Oakley and SKEME).
Oakley - free-form protocol allows each party to advance the state of the protocol at its own speed.
IKE borrowed the idea of different modes, each producing a similar result (an authenticated key exchange)
through the exchange of information at different speeds. Oakley는 어떤 메세지를 교환해야 된다는 정의는
없음. mode는 Oakley가 secure key exchange를 수행하는데 활용되는 방법의 예이다. IKE는 modes를 exchange로
codify. Oakley의 유연성을 줄이기 위해 IKE는 Oakley가 well-defined한 방법으로 multiple mode를 제공하는
가능성을 제한함.
SKEME - define a type of authenticated key exchange in which th eparties use public key encryption to
authenticate each other and share components of the exchange.
Each side encrypts a random number in the public key of the peer and both random numbers contribute to the
ultimate key. One can optionally DH exchange alog with the SKEME share technique for PFS, 혹은
use another rapid exchange (refresh an existing key 하는것같은 public key operations을 필요로 하지 않는것등)
IKE는 authentication method(authentication with public key encryption) and also borrows the notion of
rapid key refreshment without PFS.

ISAKMP -

IKE - use foundation of ISAKMP, mode of Oakley, share and rekeying technique of SKEME
to define its own unique way of deriving authenticated keying material and negotiating shared policy.

- ISAKMP

define how two peers communicate, how the message they use to communicate are constructed,
and define the state transitions they go through to secure their communication.
provides the means to authenticate a peer, to exchange information for a key exchange, and to negotiate
security services.
not define how a particular authenticated key exchange is done, nor define the attributes necessary
for establishment of security associations. -> key exchange document와 Domain of Interpretation에 정의됨.

.Messages and Payloads
ISAKMP based key manangement protocol에서 Message exchanged는 ISAKMP payloads를 ISAKMP header를 chaining
하여 구성.
initiator cookie and responder cookie는 각 peer에서 생성되고 message ID에 따라 ISAKMP exchange를 정의하는
state를 identify하는데 사용.
next payload field는 헤더 다음에오는 다양한 ISAKMP payload를 가리킴. ISAKMP version은 major/minor 번호
exchange field에 의해 ISAKME exchange의 타입이 identify.
ISAKMP message의 전체길이는 header자체의 길이를 포함해서 message length field에 denote됨.
flag field gives recipient additional information pertinent to the message.
flag는 option의 존재에 따라 bit mask로 셋팅. 3개 flag로 정의됨(8bit에). 1. encryption (header다음에 나오는
payload가 encrypt되었는지를 알려줌), 2. comit flag (peer가 exchange completion을 알려주도록 함)
3. authentication-only (ISAKMP에 key recovery를 추가하고자 하는 사람에의해 사용됨)

13개의 distict payload가 있음.
current payload뒤에 오는 ISAKMP payload의 타입은 next payload field에 의해 denote됨. ISAKMP payload
의 전체 길이는 header를 포함해서 payload length에 의해 denote. reserved field는 0으로 set하고 사용하지 않음.

some payload는 서로 dependent. 예를들어 transform payload는 항상 proposal payload에의해 encapsulated된다.
차례로 security association payload와 encapsulated됨. 몇몇 payload는 타입에 따라 specific한 attribute를
정의한다. 예를들어 payload define certificate종류를 define, X.509냐 CRL이냐, PKCS#7 wrapped certificate등등

ISAKMP define paloads to express certain construct during an exchange. 몇몇은 generic, (hash digest나 pseudo-
random nonce처럼) 혹은 specific(certificate나 SA처럼).
generic payload 는 모두 동일하다 payload identifier(next payload field)만 다름.
generic payload includes
.hash payload - 특정한 hash function의 digest output을 포함함.
.a signature payload - contains digital signature.
.a nonce payload - contains pseudo-random information necessary for the exchange.
.vender ID payload - opaque blob. vender가 define하고, network에서 자신의 implementation을 identify.
.key exchange payload - information necessary to perform a key exchange. (ex DH public value)

specific payload include (모두 독립적으로 define)
.SA payload - define a SA (ISAKMP SA 와 IPSec같은 다른 security protocol중에 하나)
.certificate payload
.certificate request payload
.identification payload

종속적이고, SA payload에 의해 encapsulated되고 혼자나타나지않는 2개의 다른 payload가 있다.
proposal payload - describe a single proposal of a SA,
transform payload - a single transform for a proposal, contains a set of attributes that apply to the
transform. attribute are flexible and complicated, type/value pair (ex encryption
algorithm, CAST) IANA에서 할당된 숫자로 표현, type은 16bit word value는 variable
length나 16bit word. high order bit(15번째 bit) denote sigle word인지 variable
precision integer인지 VPI attribute인지 (16비트 word length field와 variable length
field를 포함하는). 나머지 attribute type field는 실제 numuric definition of the type.
basic attribute value는 attribute type에 바로 다음에 오고 VPI attribute는 length
field다음에 온다.
Attribute payload?
첫번째 bit는 A/F field, is attribute format flag (low order two byte가 attribute인지를
나타냄) SA lifetime같은 16bit word에 나타낼수 없는 value를 표현하기 위해
variable length attribute를 사용

other payload are define to enable notification data (error condition tobe passed to a peer and delete
message to be passed instructing a peer to delete a specific SA)
(notify payload, delete payload)

특정 payload를 지정하는 attribute를 define
certificate payload - has certificate type field that used to specify what type of certificate is
conveyed in the payload

ISAKMP specification has a complete description of payload format and payload-specific attribute
payload are chained together in a message using next payload field.
ISAKMP header describe first payload following th eheader, and each payload describe which payload
comes next. last payload in the message is zero. ISAKMP communication is done via UDP 500.

- Excahnges and Phases
ISAKMP describes two separate phases of negotiation.
first phase, peers establish an authenticated secure channel between themseleves.
second phase, is used to negotiate security services for a different protocol such as IPSec.

phase one exchange establishes an ISAKMP SA. SA - abstraction of security policy and a key
has similarity to an IPSec SA but defferent.
이 SA를 맺기위해 peer는 먼저 its term,그 것을 authenticate하는 method, establish
하기위한 parameter등을 nego해야 함. 이 SA는 다음 phase two exchange를 authenticate하는데 사용.
두 peer간에 share할수 있는 ISAKMP SA의 제한은없기만 보통 1개이다.

phase two exchange establsih SAs for other protocol. ISAKMP SA는 이미 authenticated되었으므로
phase two exchange에서의 모든 메세지는 source authentication, integrity, confidentiality를 제공
받는다. phase two exchange에서 ISAKMP process에서 관련된 state를 종료하면 destroyed but
ISAKMP SA는 secure한 다음 phase two exchange에서 살수 있다. phase two exchange의 개수에는 제한이 없다.
일반적으로 single key exchange로부터 얻어진 secret을 사용하도록 제한하기를 원한다.

ISAKMP describe five exchanges. phase one이나 two에 strict한것은 아니나 보통 ISAKMP가 SA를 nego할때 사용하는
방법과 key exchange를 authenticate를 수행하는 것이 일반적인 예다.
full excahnges는 없지만 authentication의 방법은 서술되지 않고, authentication data는 exchanged되나 이
데이터의 generation과 processing은 서술되지 않는다. 각 exchange는 다른 목표를가지고 다른 수의 step으로
수행된다. 예를들어 identity protection exchange는 peer간의 identity를 도청자들로부터 숨기는목적으로
six message로 수행된다. authentication only exchnage는 peer를 authenticate하는데 관련되고 shared secret을
establish하는데는 관련되지 않는다. 3개의 메세지를 사용하고 key exchange를 포함하지 않는다.

any exchange의 첫 step은 cookie의 exchange이다. 8byte의 pseudo-random number가 각 ISAKMP entity에의해
generate되고 각 remote peer에 의해 assign된다. 각 cookie는 remote peer에게 unique하고, define된 특별한
exchange에또한 unique하다. cookie의 목적은 exchange에게 liveliness를 제공 (uniqueness를 제공하고
new stream에서 old packet의 replay를 방지) 하고 anticlogging protection을 제공)
cookie generation에대한 method는 ISAKMP에서 제한하지 않고 preferred method이다.
cookie는 a unique identifier (address, port, protocol)와 generator로 알려진 secret과 timestamp, 을
hashing한 결과이다.
이러한 방법으로 각 cookie는 remote peer에 bound되고 peer에게 제공된 cookie를 누가 다른사람에게 주는것을
check하는것은 간단하다. cookie는 ISAKMP header에 존재한다.

cookie로 부터 대부분 anticlogging protection을 수행하기 위해 exchange는 일반적으로 delay가 expensive하고
intensive operation이다. (exponention for a DH exchange) cookie가 바뀔때까지. 이러한 방법으로 근본적인
DOS대 대한 protection이 가능하다. 예를 들어 수천의 잘못된 return address를 가진 bogus ISAKMP message를
generate하는 attacke가 중요한 적을 하는 target을 발생시키지 못할것이다. 왜냐면 잘못된 address를 가진
unique한 cookie를 가지는 second message를 received하지 않기 때문이다.

cookie exchange는 처음 두메세지 교환에서 일어난다. 첫 메세지는 initiator 에서 responder로의 메세지이다.
initiator는 responder와 시작하기를 원하는 exchange에 unique한 cookie를 생성하고, ISAKMP header에
initiator cookie부분을 삽입한다. responder cookie가 없는 첫 메세지이기 때문에 이 필드는 0으로 초기화됨.
message를 받은 후에 responder는 initiator와 exchange에 unique한 cookie를 생성하므로써 응답을 처리한다.
header에 responder cookie를 복사하고, initiator 에서 제공된 cookie를 initiator cookie field로 복사함.
responder는 잠재적인 ISAKMP SA를 생성할수 있고 initiator에게 message를 보낸다. this receipt of the
response the initiator checks the validit of the initiator cookie field(anticlogging check) and
provided the check passes, is able to create the larval SA and the exchange continues.
anticlogging check is accomplished by initiator generating a temporary cookie for
the remote peer in the same fashion in which it created the initiator cookie in the first place.
only he now cookie의 성분, secret known only to the generator, only he can recreate it.

first message를 보내기 전에 initiator는 some state를 만들어야 한다. 최소한 this state는 peer가 보냈던 메세지
와 그가 생성한 cookie를 포함해야 한다. responder의 cookie를 알기전에 메세지를 보내기때문에 자신의 cookie에
대한 상태를 identify하는것을 마련해야한다. responder의 첫 메세지를 받은후에 responder의 쿠키를 포함하는
상태를 update할수 있다.

cookie exchange후에 두 cookie를 결함은 IPSec SA를 identify하는 SPI와 같은방법으로 SA를 identify한다.
cookie는 ISAKMP header의 일부로 지나가므로 메세지 수신에 따라 message (ISAKMP SA)와 관련된 state를
lookup하는 entity는 straightforward하다. 메세지가 처리된후에 ISAKMP SA의 상태는 update되고, 필요하면
response를 보내줌. 이런 방법으로 ISAKMP SA가 complete될때까지 exchange가 진행된다.

- Policy Negotiation

shared SA를 establsih하는것은 security policy의 nego를 수반함.
policy 는 complex하고, flexible, SA, proposal, transform payload의 parsing을 flexible은 차례로
construction과 complex policy가 제공하는 처리를 허용해야만 함. ISAKMP는 SA, proposal, transform payload를
가지고 이를 수행. single SA는 하나이상의 proposal을 가지고 single proposal은 하나이상의 transform을 가진다.

SA payload의 DOI필드는 payload가 적용되는 DOI를 정의한다. DOI값이 0은 ISAKMP자신에 사용되고 각기 다른 security
service에 사용되는 DOI value들이있는데 RFC2407에 DOI of IPSec이 있고 DOI값 1을 사용한다.
SA payload의 situation field에는 nego동안에 policy decision을 하는 recipient가 allow하는데 필요한 infomation
을 포함하고 DOI-specific하다. SA payload당 multiple proposal payload가 가능하기때문에 proposal payload는
proposal number를 가진다. 각 proposal은 SA로 끝날수 있고, 그러므로 SPI, SPI size, SA의 프로토콜을 가진다.
following proposal payload는 하나이상의 transform payloads이고 proposal payload는 얼마나 많은 transform
payload가 오는지 denote하는데 사용되는 field를 포함한다.
transform payload - transform number, transform id(transform type을 가리킴).
following transform은 attribute(encode using the attribute payload) specific.

single SA payload 는 multiple proposal payload를 갖는다. proposal number는 logical OR, AND를 표현하기
위해 사용. proposal number와 매칭되면 logical AND 다르면 logical OR. 예를 들어 IPSec policy가 AH와 ESP
가 필요하면 각 protocoal마다의 proposal payload는 동일한 proposal number를 가진다. AH or ESP이면 당근 다름.
만약 IP payload compression prootocol을 포함하면 'authenticate everything and if possible also encrypt it,
and if possible also compress it' 제공되는 수에서 preference의 순서때문에
[AH-1, ESP-2 or (ESP-3 and PCP-3)] 여기서 protocol-n is a proposal for protocl with proposal number n.

각 proposal은 multiple transform을 제공함.
proposal마다 multiple transformd르 추가할수 있음 3DES over DES, SHA over MD5, LZS over Deflate(for PCP) and
offer would be:
P110참고
SA payload construction과 parsing은 complex. because security policy is complex. 다른 payload는 복잡하지않음.

- IKE

ISAKMP는 key exchange를 define하지 않음. IPSec defined key exchange is IKE. IKE uses the language of ISAKMP
to define a key exchange and a way to negotiate security services. IKE define a number of exchanges and options
thant can be applied to the exchanges. The end result of an IKE exchange is authenticated key and agreed-upon
security services. (IPSec SA). IKE is not only for IPSec. (RIPv2, OSPF)

IKE use two phase of ISAKMP. phase 1 establish IKE SA and phase 2 use SA to nego SA for IPSec. ISAKMP와
다르게 IKE define attribute of its SA. left up to DOI.
DOI define optional and required attributes that IKE will negotiate in a phase two exchange. IKE doesn't
define its own DOI but it define the terms and conditions surrounding the use of its SA.
IKE define two phase one exchange. one phase two exchange, and two extra exchange for maintanance of SA.
phase 1 exchanges에서 IKE는 base ISAKMP document로부터 protect exchange와 aggressive exchange를 identity
하는데 사용하고, main mode와 aggressive mode라 부른다. ISAKMP exchange와 다르게 IKE는 fully defined exchange
를 가진다. (모든 payload의 content와 이를 처리하는 step). phase2 에서는 IKE는 quick mode exchange를 define.
IKE이외의 프로토콜에 대한 security service를 nego. (주로 IPSec). IKE는 quick mode exchange가 필요한
security service를 establish하기에 충분하다. two other exchanges IKE defines are informational exchange와
IKE peer가 error와 상태정보를 서로 통신하고 그들사이에 IKE peer가 새로운 DH group을 nego하도록 new group exchange.

two phase one exchange - main mode and aggressive mode - 각각은 같은것을 수행 (
secure하고 authenticated된 communication channel (IKE SA)를 생성하고,
confidentiality를 위한 auth key와 message integrity, 두 peer간에 IKE 통신을 위한 message source authentication.
IKE에서 define된 모든 다른 exchange는 IKE가 authenticated IKE SA를 가지는것을 전제조건으로 한다. 그러므로
main모드이건 aggressive모드이건 다른 exchange전에 반드시 수행되어야 한다.

IKE SA는 두 peer간에 nego에 의해 합의되는 다양한 parameter를 가진다. 어떤 IKE message는
enccrypted되고 auth되기에 peer는 message를 encrypt하고 auth하는 방법에 동의해야 한다.
two peer는 서로 identity를 auth해야 하기 때문에 그들은 이를 하는 방법에 동의 해야 한다.
모든 nego된 파라미터에 대해서 IKE는 attribute와 이들 attribute가 가질수있는 value의 범위를
정한다.
parameter (encryption algorithm, hash algorithm, authentication method, DH group, ) 은 protection suite라 한다.
Protection suite는 ISAKMP SA payload를 exchange하는 unit으로 nego됨. protection suite의 attribute는 transform
payload에 포함된다. mandatory attribute뿐아니라 protectin suite의 일부로 nego되는 optional attribute도 있다.
(ex lifetime) lifetime attribute은 IKE SA가 얼마나 오래 존재할것인지를 결정하는것이다.
IKE SA가 오래 존재할수록 key의 유출에대한 위험은 커지므로 구현에서 peer에게 제공되는
protection suite에서 lifetime을 포함하는것이 장려됨.

hash algorithm은 protection suite의 일부로 nego된다. HMAC form으로 사용됨. IKE는 PRF가 random bitstream을
generate하는데 hash algorithm의 HMAC버전을 사용함. IKE로 다른 PRF function을 nego가 가능하지만 hash algorithm
을 네고하는데 HMAC이 사용됨.
encryption algorithm과 hash algorith attribute는 straightfoward. encryption과 authentication 메세지에 어떤
알고리즘이 사용될것인가를 결정.
DH group은 peer가 DH exchange를 수행할때 사용할 parameter를 결정.
group number는 그냥 값이지만 IKE에서 5개의 그룹을 unique한 값으로 할당해놓았기때문에 양 peer
는 group의 parameter를 알기때문에 양 peer가 DH exchage에 참여할수 있다.
3개의 traditional exponentiation over a prime modulus (MODP) type과 2개의 elliptic curve one
over G[P](ECP) and another over G[2^N] (EC2N) type.
1. MODP group with 768 modulus (mandatory to implement)
2. MODP 1024
3. EC2N 155
4. EC2N 185
5. MODP 1680
more group can easily defined and New Group Exchange 를 사용해서 two peer가 자신의것을 define할수 있음.

IKE exchange에서 가장 impact한 attribute는 authentication method이다. other attribute는 payload의 content를
결정하고, message를 보호하는 방법을 결정하나 authentication method는 exchange할때 어느 payload가 exchange될
것인지를 결정. IKE exchange는 두 peer간에 nego되는 authentication method에 따라 달라짐.
1) preshared key 2) digital signature using DSA 3) digital signature usign RSA 4) encrypted nonce의 교환을
통한 두개의 유사한 인증방법.
이들 attribute는 peer간에 그들이 교환하는 첫메세지의 일부로서 nego된다. 이들은 IKE SA의 external , visible
특성이다. 그러나 observer가 볼수 없는 secret information도 maintain한다. 인증되는 정보, IKE메세지를 보호하는데
사용되는 정보, 다른 security service를 위해서 derive 된 key. 4개의 secret을 생성한다.
SKEYID (인증 방법에 따라다름), SKEYID_d, SKEYID_a, SKEYID_e (나머지 3개는 인증방법과 관계없이 동일하게생성됨)

각 side는 cookie, a nonce to SKEYID state generation을 contribute한다.
initiator는 cookie와 , CKY-I, his nonce(Ni)를 contribue, responder는 CKY-R, Nr. 이들은 liveliness를 증명하기
위해사용. 각 side가 상대방의 nonce와 cookie를 가졌다는것을 서로 알려주고 Memorex가 아니라 live이다.
상대에게 freshness를 제공한다. DH exchange의 결과로 DH shared secret을 share함. (SKEYID generation에 사용됨)
preshared key : SKEYID=PRF(preshared-key, Ni | Nr)
signature : SKYID=PRF(Ni | Nr , g^xy)
nonce authentication: SKYID= PRF(hash(Ni | Nr), CKY-I, CKY-R)

SKEYID_d = PRF (SKEYID, g^xy | CKY-I | CKY-R | 0)
SKEYID_a = PRF (SKEYID, SKYID_d | g^xy | CKY-I | CKY-R | 1)
SKEYID_e = PRF (SKEYID, SKYID_a | g^xy | CKY-I | CKY-R | 2)
block size는 SKEYID 상태의 결과 size에 따라달라짐. 따라서 bit수가 모자라면 concatenation technique로
SKEYID_e 에서 PRF는 encryption에 사용되기에는 너무 작으므로 expanded

phase 1 exchange는 오직 그들만이 아는 hash값으로 authenticate함. hash function의 단방향 특성으로
인하여 이를 invert하는것은 어렵다. hash digest는 자체가 secret은 아니며 in the clear로
passing하는것은 security breech가 아니다. 왜냐하면 hash function의 output으로 input을 결정하는
게 어렵기 때문이다. 같은 input은 같은 output을 낼것이고, 적절한 digest생성은 peer를 인증한다.
hash의 계산은 auth 방법에 관계없이 동일하다. 그러나 initiator와 responder는 다르게 계산한다
HASH-I = PRF(SKEYID, g^i | g^r | CKY-I | CKY-R | SA-offer | ID-I)
HASH-R = PRF(SKEYID, g^r | g^i | CKY-R | CKY-I | SA-offer | ID-R)

g: DH-public number
SA-offer ? SA payload with all protection suite
ID : identity of initiator or responder
전체 SA payload를 보내는것은 man-in-the-middle attack을 방지하는데 중요하다.
phase one과 상관없이 initiator가 protection suite를 첫메세지에 실어서 responder에게 주는것은
unauthenticated하므로 attacker가 약한 protection suite로 수정할수 있다.
SA payload를 auth hash에 보냄으로써 이러한 attack을 방지할수 있다.

IKE SA는 양방향. ISAKMP header에서 cookie는 phase one에서 initiator가 responder가 되었다 하더라도 바뀌지않음
외내면 cookie pair는 IKE SADB에서 SA를 identify하는데 사용되기때문.
CBC모드를 사용하기 때문에 IV가 필요함.

- Main Mode Exchange
6 message. three step (SA nego, DH exchange, nonce exchange, authentication of peer)
id protection, full ISAKMP nego.authentication method는 payload의 composition과 message의 placement에 영향을
주지만 message의 intent와 purpose는 상관없다.

Hdr, SA ->
<- Hdr, SA
Hdr, KE(DH의 g^i), Nonce^i ->
<- Hdr, KE(DH의 g^r), Nonce^r
Hdr^*, ID^i, [hash or sig] ->
<- Hdr^*, ID^r, [Hash or sig]

첫메세지에서는 IKE SA의 parameter를 nego함. 첫 메세지에 또한 cookie를 교환.
두번째 메세지에서는 DH public value와 pseudo-random nonce를 교환.
마지막으로 자신을 identify하는 exchange와 authentcating hash digest exchange를 교환. 마지막은 SKEYID_e로
encryption됨. preshared key는 IP address에 근거하므로 Main MOde에서 preshared key의 한계가 있다.
public key signature로 인증될수 있다. DSS, RSA.
public key는 certificate와 certificate가 exchange되도록
허용된 IKE와 peer가 요청한 certificate 등에서 얻어진다? digital signature is nonrepudiable.
Provided each side retain the state associated with the IKE session, they can prove, undeniably, that they
were talking to a particular peer.

encrypted nonce의 exchange를 사용하는 두가지 인증방법이 있는데 (standard public key encryption과 public
key encryption의 revised 방법이있다) revised method는 standard method가 2개의 분리된, expensive한 public key
encryption을 요구하는 standardㅇ method에 대한 criticism으로 생겼고, single public key encryption를 요구하고
symmetric cipher로 다른 payload를 encrypt하는것만 요구한다. IPSec과 IKE standard의 개발동안 standard mode의
제거가 논의 되었으나 이미 구현된것때문에 추가되어다.

두 method모두 repudiable. 즉 양 side는 모든 메세지와 IKE session과 관련된 state가 저장되어있다 하더라도
deny될수 있음을 말한다. 누군가가 알지못하기를 원하는 어떤것을 하려면 이들을 IPSec SA를 맺을때
사용하면 안된다. 왜냐면 nonce는 peer의 public key로 encrypt됙때문이다. initiator의 nonce는
responser의 public key로 encrypt되고 그 역또한 마찬가지다. peer가 key를 decrypt한다고
인증된 digest를 재조립한다는것은 peer가 private key를 가지고 있다는 것을 말한다. 그러므로
identity가 보장된다. cookie를 통해 liveness를 증명하고 message digest를 통해 identity를
증명하고, 어느쪽이라도 나중에 thrid party에서온 exchange를 deny할수 있다.
왜냐면 둘다 public key encryption을 사용하기 때문이고 DSS를 이런 용도로 사용하는것은 불가능ㅎ
다.

RSA public key를 사용해서 public key를 encrypt하는것이 일반적인 방법임
DH- public key

standard method of public key encryption

Hdr, SA ->
<- Hdr, sA
Hdr, KE, {Idi} pub_r, {Ni} pub_r ->
<- Hdr, KE, {Idr} pub_I, {Nr} pub_i (책에 r인데 i가 아닐까)
Hdr, Hash* ->
<- Hdr, Hash*

{}pub_x 는 x의 public key로 encrypt함을 의미
ID payload의 교환은 두번째 message에서 이뤄짐.
main mode에서의 ID proctection은 public key로 peer의 id를 encrypt함으로써 각 peer를 확인할수 있다.

two public key encryption의 단점이 있어서 다른 method는 certificate를 request하거나 exchange하지 않는다.
certificate의 exchange는 main mode에서 ID protection을 잃을수도 있다. initiator는 이 exchange의
initiation전에 responder의 identity를 알아야 한다. 이것은 initator가 가야할 network과 talk할
대상을 알기때문에 일반적으로 issue는 아니다. 이러한 인증 method에서 certificate를 전달할방법
이 없기 때문에 LDAP같은 certificate를 얻는 다른 method의 지원이 필요하다.

왜 두 payload를 함께 encrypt하지 않는가? 두개를 같이 encrypt하면 nonce payload의 헤더가 함께
encrypt되므로 hide됨. message를 적절히 parsing하기위해서 ID payload의 길이는 encrypted nonce
payload에 포함해야한다. 이러한 behavior는 packet을 받는 쪽에서는 detrimental impact가
될수도 있다. nonce payload의 generic header가 correct한지 check할수 잇는 방법이 없기때문에
받은 message의 온전성을 check하는것은 불가능할지도 모른다. 또한 ID payload의 실제 길이를
정할수 없다. receiver는 ID payload의 끝과 nonce의 generic header의 시작을 추측해야만한다.
그래서 two public key encryption이 필요하다.

revised method는 initiator가 responder에게 certificate를 제공하므로 한개의 public key operation
만 요구된다. initiator는 responder의 certificate를 얻기위한 IKE의 외부수단을 사용해야만한다.

revised method of authentication with public key encryption

그림 참조
{}ke_x 는 key Ne_x와 symmetric key encryption을 가리킴
symmetric cipher를 위한 key와 알고리즘은 어딨나?
algorithm은 IKE SA에서 사용되는것과 같고 SA payload 교환에서 nego된다.
key는
Ne_i = PRF(Ni, CKY-I)
Ne_r = PRF(Nr, CKY-R)
nonce의 decription을 사용하므로 symmetric key를 적절하게 계산하고 payload의 나머지를 decrypt
하는것이 가능하다.

Aggressive Mode Exchange

목적은 main mode와 동일 (인증된 SA와 IKE가 다른 프로토콜을 위해 SA를 맺을때 사용할 key의 establish)
주 차이는 main mode와 메세지 수가 절반, nego의 power와 id protection을 제공하지 못함.

initiator가 protection suite의 리스트, DH public value, nonce, ID,를 첫 메세지에서 보냄.
responder가 selected protection suite와, DH public value, nonnce, ID, authentication payload(
for shared key 와 encrypted nonce authencation (hash payload), for signature based authentication
initiator는 마지막 메세지에 authentication payload를 보냄.

aggressive mode에서는 nego capabiliby를 제한. DH public value와 nonce를 first message에 보내기때문
different protection suite에서 다른 DH group을 제공할수 없다. encrypted nonce에 기반한
authentication을 제공하기위해서는 his offer여야한다 왜냐면 nonce는 such an exchange에서 encrypted
해야만 하기때문에. encrypted nonce의 수정된방법을 사용하여 authentication을 하기 원하면
differing encryption이나 hash algorithm option을 가진 multiple protection suite를 제공할수 없다.

aggressive mode는 제한적이지만 언제 사용할까?
initiator의 주소를 responder가 알수 없는 remote access 환경에서 양쪽이 preshared key 인증을
사용하고자 할때 는 이것이 IKE SA를 맺을수 있는 유일한 exchange이다.
또한 initiator가 responder의 policy를 알고 있을때 혹은 IKE SA를 더 빨리 생성하기위해서 이 exchange
를 사용한다. 만약 사원이 자기네 회사의 resource를 remote로 접근하기를 원할때 그는
접근이 허용된 policy(예를 들어 3DES로 encryption, SHA로 hashing, CA에 의해 RSA signautre certificates signed된
로 인증)을 알고 있을것이고 full power IKE nego가 필요하지 않다.

Quick Mode Exchange

IKE SA가 맺어지면 IPSec같은 프로토콜의 SA를 맺어야 한다. 이러한 SA는 Quick Mode에 의해 이루어짐
Quick Mode exchange는 IKE SA의 수립의 보호하에 이뤄진다. many Quick Mode는 single Main mode혹은
aggresive mode로 될수 있다. 하나의 IKE SA의 prection하에 동시적으로 quick mode가 수행될수 있다.

two peer는 characteristics와 generate key, IPSec SA를 nego한다. IKE SA가 message를 encrypt하고
auth함으로 보호한다. 이메세지는 PRF function으로 인증되고, 대부분 nego된 hash function의 HMAC버전이다.
IKE SA state로 부터 SKEYID_a값은 quick mode exchange의 전체 message를 인증하는 key로사용된다.
이 인증은 data source auth뿐아니라 data integrity protection도 제공한다. 인증된 peer로부터
온 메세지임을 알기에 message는 중간에 변경되지 않는다. SKEYID_e for encryption provide confidentiality

multiple quick mode exchange가 동시에 수행되므로 IKE message를 multiplex하고 message가 어느
exchange를 참조하는지를 결정하는 방법이 있어야 한다. ISAKMP header의 messageID가 이 목적으로
사용된다. 각 quick mode exchange는 ISAKMP header에서 특수한 message
를 참조하는 상태를 identify하도록 사용되던 cookie와 함께 사용된 unique한 message ID이다.
또한 모든 quick mode SA는 IKE SA에 의해 보호되므로 encryption과 decription(상대가 encryption한
것을 decript하는게 아니라 sync로부터 두 IKE peer를 보호하기위한)을 위한 IV를
coordinate하는 방법이 있어야 한다. messageID는 이런 용도로 사용된다. 각 quick mode exchange는
phase 1 exchange에서 끝난 IV로부터 얻어진 uniquie한 ID와
phase 2 exchange에서 얻어진 message ID로 얻어진 uniquie한 IV로 시작한다.
초기 IV는 deterministic algorithm으로부터 얻어지고 다음 IV는 마지막메세지의
last ciphertext block으로 정의된다. quick mode exchange가 끝나면 IPSec SA가 생성되고, state(
the running IV), nonce, DH value(이들 exchange를 다루기위해서 생성된), 는 삭제된다.

Quick mode는 SKEYID_d 상태로부터 IPSec SA를 위한 key를 얻는다. 이 key는 IPSec SA가 제공하는
nonce exchange, protocol, SPI와함께 PRF fucntion에사용된다. 각 SA를 위한 unique key를
guarantee한다. inbound SA는 different SPI를 가지므로 outbound SA와 다른 key를 갖게될것이다.
모든 IPSec key는 같은 source로부터 derived되고 그러므로 모두 관련이 있다. 만약
attacker가 SKEYID_d를 IKE SA로부터 결정할수 있다면 SKEYID_d로부터 얻어진 모든 IPSec SA의
모든 key와 앞으로 얻어질모든 key를 쉽게 결정할수 있다. 이것은 문제가된다. 어느 key도 PFS를
가지지 않았음. Quick mode는 안전을 위해 PFS를 option으로 가지고 있다.
quick mode exchange에대한 PFS를 제공하기위해 부가적인 DH exchange가 수행되고
resulting shared secret이 IPSec을 위한 key생성에 사용된다. 명백히 이 secret은 한번 exchange가
끝나면 retain되지 않는다. 끝나는 즉시 기억된 memory는 0으로 초기화되고 free된다. DH group의
nego는 aggressive mode 교환에서처럼 같은방법으로 quick mode에서는 가능하지 않다. initiator
는 그가 제공하는 group으로부터 얻어진 DH public value를 제공해야만 한다. 만약 그가 multiple
group을 제공한다면, responder는 적절한 public value를 sa에 제공하는데 어려움이있을것이다.

SA를 제공하는것과 더불어, nonce, optional DH puglic value(if PFS가 요구되면), identity
infomation등이 양 party에 의해 교환될수 있다. 양쪽은 phase one에서 identity를 auth하였는데
또 모가 필요한가? 이들은 selector information을 교환하는데 사용되고, SA payload가 establish
되어야하는 목적을 기술한다. IPSec DOI는 ISAKMP ID payload의 identity type과 port, protoco field
를 define한다. DOI는 phase two에서 다뤄지므로 특히 IPSec SA를 establish하는 방법을 다루므로
이들 정의는 come into effect.
이들 identity는 simple address, address의 범위나 subnet이 될수 있다. "132.239.4.0/255.255.255.0
로가는 모든 telnet traffic" IPSec에서 valid policy. 퀵모드에서 ID payload를 사용하여, IKE peer에 이러한 policy를 표현하는것이
가능하다. ID payload의 형식에서 Selector information은 SA가 responder에 제공하는 것에따라
quick mode의 initiator에 의해 전달된다. responder는 자신의 policy를 check하기위해 이 정보를
사용하고, initiator가 이러한 목적으로 SA를 맺는것을 허용하는지를 결정한다.
만약 policy가 pass를 check하면 selector information은 ID payload로부터 얻어진 selector
information은 SA specific한 IPSec SADB를 제공받아야만 한다. 이들 정보는 IPSec SA를 제한한다.
SA는 오직 ID payload에 의해 구분되는 traffic에만 사용된다. 만약 phase 2 identity가 특정 호스트로가는
telnet에 대한 nego를 가리킨다면, 결과 SA는 어떤 traffic에 대해서도 사용될수 없다.
passing selector information, derived from the phase 2 identities, to the SADB allows the
IPSec processing to determine whether the traffic protected by the particular SA is allowed.
물론 이러한 결정은 datagram의 decryption후에만 이뤄진다.
simple request/response exchange로서 quick mode를 describe했고, 이외에 더 많은것이 있다.
initiator는 resonder가 online이라는 liveness proof가 필요하고 initial quick mode message에서
처리된다. 이를 수행하기위해 responder는initiator의 nonce와 authenticating hash payload에
exchange의 message ID를 포함한다. 이 digest는 message integrity와 source authentication
to the initiator뿐아니라 liveness proff도 제공한다.
responder또한 liveness proof가 필요하다. initiator로부터의 message는 adversary에의해 기존
메세지의 replay일수도 있다. adversary는 message의 content로 알수 없을지도 모르고
quick mode message였던 traffic analysis를 통해서 알수도 있다.
message replay는 불필요한 SA의 생성을 초래한다. 이는 DOS attack을 유발하므로, memory와 SA
management overhead때문에 responder는 이메세지에 불필요한 소비를 할수 도 있다.
이를 방지하기위해 quick mode exchange에 third message를 추가한다.
이 안에서 initiator는 auth hash payload에 nonce와 exchange message ID를 포함하고, responder에게
그가 이 exchange에서 실제 살아있는 active한 participant라는것을 증명한다. 이 시점에서
responder는 SA를 IPSec SADB에 추가할수도 있다.

Hdr, HASH, SA, Ni, [,KE] ->
<- Hdr, HASH2, SA, Nr, [,KE]
Hdr, HASH3 ->

HASH1 = PRF(SKEYID_a, M-ID | SA | Ni [|KE][|IDci|IDcr])
HASH2 = PRF(SKEYID_a, M-ID | Ni | SA | Nr [|KE][|IDci|IDcr])
HASH3 = PRF(SKEYID_a, 0 | M-ID | Ni | Nr)

어떻게 initiator가 responder가 하기전에 IPSec SA를 SADB에 넣는 모든 정보를 가지고 있는가?
initiator는 responder가 단지 메세지를 받은후에 그의제공으로 부터 responder가 받은것만을
알고 있을 뿐이다. 만약 exchange가 PFS를 가지고 있으면 , 그는 DH public value를 가지고,
liveness prof를 가진다. responder는 그가 준비되기 전에 initiator의 final message를
받을때까지 기다려야만 한다. 이때문에 initator는 IPSec-protected packet을 그의 마지막 message
를 받기 이전에 보내기 시작할수도 있다. 사실 initiator는 may choose to give IPSec processing
a higher priority to IKE processing, IPSec packets may even arrive at the responder
before the final IKE message does! 만약 이런일이 발생하면 마지막 IKE message가 처리될수 있을
때까지 모든 IPSec packet은 drop될것이다.
traffic에 따라서 이것은 문제가 될수도 안될수도 있다. 만약 traffic이 TCP-based protocol이라면
초기 message는 대부분 syn packet이될것이고 ack를 받을때까지 retransmitted될것이다.
UDP-based protocol은 lost될것이다. 이런 현상으로부터 막기위해서 IKE는 ISAKMP header로부터
하나의 메세지로 quick mode exchange를 확장하도록 commit bit를 사용한다.
어느쪽도 commit bit을 셋팅할수 있고 만약 셋팅하면 responder는 'connected' 메세지를 포함하는
notifiy payload에 의해 따라오는 authenticating hash payload로 구성된 마지막 메세지를
보내야 한다. 이경우 initiator는 "connected"메세지를 받기전까지 SA를 SADB에 추가하지 않는다.
이것은 첫 IPSec packet이 시작될때 responder가 그의 SA를 먼저 추가해서 ready상태가 되도록
해준다.
전에 언급한대로 IKE SA는 양방향이다. 어느쪽도 전에 main mode나 aggressive mode exchange
를 initiate했건간에 상관없이 quick mode exchange를 initiate할수 있다. 이것이 발생할때 phase2
에서의 역할은 바뀌나 phase1에서 role-specific 한 정보는 바뀌지 않는다. initiator cookie와
responder cookie는 IKE SA를 계속 identify하도록 순서대로 phase2에서의 역할에 상관없이 phase2
SA를 보호하는데 사용된다.

Other IKE Exchanges

SA를 생성하기위해 지금깢 IKE에서 모든 exchange를 기술했다. phase one exchange는 IKE SA를
생성하고 phase2 excange는 IPSec SA를 생성한다. IKE는 IKE SA의 maintanance를 제공하기위해 그리고
private DH group을 제공하기위해 두개의 다른 exchange를 정의한다.

IKE infomational exchange는 IKE peer가 status와 error message를 서로에게 보내는데 사용된다.
이는 exchange per se는 아니고, acknoledge가 아닌 single message이고, IKE의 UDP-based 특성때문에
arrive를 gurarantee하기위함이다. infomational exchange message의 unreliability대문에 이는
반드시 ㅂ내야 하는것은아니다. implementer는 이를 강하게 장려하고, 사용하지만, code에는
이를 expect하도록 design하면 안된다. informational exchange의 가장 주로 사용하는것은 peer에게
특정한 SA(IKE SA이건 IPSec SA이건)가 삭제되고 그것의 사용을 막으라고 말하기 위함이다.
Informational exchange는 그들이 모두 unique한 message ID를 가지고, message encrypt를 위한
unique한 IV를 생성한다는 점에서 quick mode message와 유사하다. 그들은 또한 hash payload로
key와 메세지 ID의 연결된것과 전체 notify나 delete payload로서 SKEYID_a를 가져와
keyed PRF functin의 결과인 hash payload로 인증한다. single이기때문에
메세지가 unacknowledge하므로 이 exchange와 관련된 state는 message를 보낸후에 free된다.

IKE가 정의하는 또다른 exchange는 new group exchange이다. IKE는 peer가 사용할수 있는 5개의
DH group을 정의한다. 3가지는 exponentiation over a prime modulus를 사용한그룹, 2가지는 elliptic curve를
사용한 그룹이다. new group exchange은 peer가 그들이 사용할 private group을 nego하도록 하고
group을 identify하기위해 다음에 오는 exchange에서 사용할수 있도록 group identifier를 define.
그러므로 new group exchange는 엄격하게 phase two exchange가 아니지만
phase1 exchange다음에 따라와야 하고 IKE SA에 의해 보호되어야만 한다. quick mode와 infomational
exchange는 유사하게, SKEYID_e를 encryption 형식을 가지고 SKEYID_a로 keyed된 authenticating hash
function을 사용한다.

new group exchange는 initiator가 proposed된 group의 특징과 private용으로 사용되기위해 reserv
된 number의 range로부터 identifier를 포함하는 SA payload를 보내는 request-response exchange이다.
예를 들어, exponentiation over prime modulus을 사용하는 new group의 제안하기위해
initiator는 primate number와 generator를 보낼것이다. responder는 group의 strength를 테스트하고
offer를 blindly하기 수용하지 않느것을 recommended한다. 예를들어
exponentiation over aprime mudulus를 사용하는 group의 제안에서, modulus는 primality를 체크받
아야만 한다. 만약 prime이 아니면, offer는 refuse된다.

- IPSec DOI

IKE는 security parameter를 nego하는 방법과 다른프로토콜을 위한 shared key를 establsih하는 방법을 정의하지만
무엇을 nego하는지는 정의 하지 않는데 이것은 DOI문서에 달려있다. DOI는 naming scheme, contents of the situation field
of ISAKMP SA payload, quick mode에서 IKE negotiate하는 attribute, IKE needs to convey하는 specific characteristics.
IPSec DOI는 ISAKMP ID payload에 새로운 field를 정의하고(in effect overload하고) , 가능한 identitiy의 새로운 값을 정의.
selector에게 nego된 IPSec SA를 constrain하는데 사용되는 정보를 전달하는데 필요하다.

IPSec DOI에 정의된 attributes는 IPSec SA의 부분이 될것을 요구한다. AH 와 ESP에 대한 분리된 attribute space
s는 필요하지 않음. ISAKMP에서 proposal과 transform payload는 이미 protocol의 분리된 spec으로됨.
DOI는 단순히 DOI에서 nego될수 잇는 다양한 프로토콜(IPSec에서는 Ah, ESP)과 필요한 attribute을 정의하는것
만 필요하다.IKE를 사용하는 DOI는 phase1에서 nego될때 attribute information에 대한 source로 IKE document를
desinate해야 한다. IPSec DOI는 차이가 없다.
AH 와 ESP사이의 차이는 cipher이다. 둘다 authenticator, lifetime이 필요해서 AH와 ESP를 위한
negotiagted attribute space는 하나다. AH는 cipher attribute 가 nego되지 않음. IPSec DOI를 가지고 SA를 nego
하는데 이상한것은 AH는 transform attribute와 authenticator attribute를 요구한다. 현재 정의된 transform은
AH_MD5와 AH_SHA이다. authenticator attribute는 HMAC-MD5,HMAC-SHA이다. Hence the confusion. 많은 first-time
reader, implementater는 authenticator가 extraneous하고 이를 보내지 않는다고 가정할것이고 그러므로 다른
implementation에서는 nego가 fail될것이다. AH에서 SHA를 사용하느것은 맞지만, HMAC-SA form으로 사용되고, 그러므로
both attribute는 repetitive하다 그러나 MD5는 not the case. HMAC-MD5를 위한 transform attribute가 있지만
KPDK가 또한 있다. deprecated된 AH spec임(RFC-1827). IPSec DOI는 완전성과 backwards compatibliity를 위해 deprecated된
IPSec transform을 nego할수 있고, 이것은 AH를 위한 방법이다 (ESP를 위해서 RFC2828에 specific한 cipher를 nego하고,
미래에, MAC으로서 MD5와 SHA 둘다 사용하는 새로운 방법이 될지도 모른다. 두 attribute를 요구하는것은
실제로 의미가 있다.

- Summary

이 chapter는 ISAKMP overview와 IKE, IPSec DOI,를 제공. 어떻게 동작하는지 모두 어떻게 연결되는지를 설명,
not substitute, reading을 위한 실제 spec. 남은것은 실제 payload format spec과 IKE 개발을 위한 필요한
attribute value definition이다.
관련 spec을 얻고, IPSec이 동작하는 key management방법에대한 지식을 사용하기를 권장.
--------------
  IPSec 6. AH  
Author: 이윤수    
Date: 2002-02-26 오후 6:49:32 from '211.237.240.191' of '211.237.240.191'

6. AH
RFC 2402
provides ESP provide except confidentiality.
AH defines the metohd of protection, the placement of the header, the authentication coverage, and input and
output processing rules, but does not define the authentication algorithm to use.

AH can be used to proctect an upper-layer protocol(transport mode) or entire IP datagram(tunnel mode)
diffenrence : protected datagram
AH header immediately follows IP header. AH is an IP protocol and AH-protected IP packet is another IP packet.
AH can be used alone or in conjunction with ESP. It can protect a tunneling protocol like L2TP or GRE or itself.
AH is a versatile security service for IP
data integrity tha AH provide differ from ESP. AH authenticates portions of the outer IP header.

- THE AH Header

AH is another IP protocol and assigned 51. IPv4 - 51 (AH) IPv6 depends on extension headers.
extension header가 없으면 IPv6 헤더의 next header field는 51이되고 있으면, AH의 extension header의 next
header팔드가 51로된다. IPv6에 AH header를 넣는것은 ESP와 비슷하다. AH and ESP가 같은 data를 보호하면 AH header는
ESP 헤더가 삽입된후에 삽입된다. AH header는 confidentiality를 제공하지 않으므로 ESP보다 단순하고 trailer도
없으니 padding관련 정보도 없고 IV도 없다.

next header field는 AH헤더의 다음 필드를 가리킴. transport mode일때는 상위프로토콜 tunnel mode일때는
4(IPv4) or 41(IPv6)

the payload length field 헤더자신의 길이를 가리킴. 32bit words 빼기2. AH is IPv6 extention header, and
RFC2460 에따라 길이는 64bit word 빼기1로 계산된다. but AH measured in 32-bit woards so 2개의 32bit word를
뺀다(1개의 64bit word), 남은 field는 0으로 셋팅.

SPI field는 outer IP header의 dst addr에 따라 이패킷을 authenticate하는데 사용되는 SA를 identify할수있는
SPI를 포함함.

sequence number - ESP와 동일

authentication data field - variable length, HMAC-SHA-95, HMAC-MD5-96이 mandatory-to-implement authenticator.
ESP와 동일하게 96bit로 truncate, public key authentication algorithm은 cost때문에 사용하지 않음.
bootstrapping이나 SNMP trap을 보낼때 AH is not used for bulk data protection and this limitation may not
apply. 이런 이유로 DSS의 사용을 define.

- AH Modes

AH는 outer IP header부분을 authenticates

.Transport Mode

.Tunnel Mode

internal - original address
outer - IPSec endpoints의 address

tunnel mode can be used as a replacement to transport mode for end-to-end security.

- AH Processing
When an outboudn packet matches an SPD entry denoting protection with AH, the SADB is queried to see
whether a suitable SA exists. if there is no SA, IKE create one dynamically. SA가 있으면
SPD entry에의해 지정되는 mode에 매칭되는 packet에 AH가 적용됨.
SPD bundle이 있으면 the order of application depends on the protocols involved. AH always protects ESP.

.Output Processing
manually 혹은 IKE에 의해 outbound SA가 생성될때 seq number 가 0으로 초기화됨. SA를 사용하는 AH header가
construction되기 이전에 couter가 증가된다. each AH header의 seq number는 unique, nonzero, monotonically
increasing number.

AH header의 나머지값은 적절히 채워짐. SA로부터 SPI를 할당받아서 SPI field를 채우고, next header field는
AH header의 다음에 오는 데이터의 타입으로 assign됨. payload 길이는 32bit word - 2값으로 채워짐. authentication
data field는 0으로 채워짐.

ESP와 다르게 AH extends its protection to immutable or predictable, fields of the outer IP header.
그러므로 ICV(Integrity Check Value)를 계산하기전에 0으로 채워야만한다. authenticating ICV에 포함되는 필드
- version, Payload length, total length, id, ip protocol, src ip, dst ip. 나머지는 mutable fields

IPv4 options이나 IPv6 extenstion header에서는 immutable하거나 predictable한것이면 ICV계산에 포함하고
그렇지 않으면 계산전에 0으로 채움.

padding은 alignment의 이유로 혹은 authenticator의 요구에 따리 필요할수 있다. Some MAC은 (예를 들어
DES-CBC MAC) MAC algorithm이 multiple of block sizes를 요구함. padding은 MAC의 사용에 따라 추가된다.
이 padding은 암시적으로 추가된다. 전체가 0으로 되어야 하고 이 사이즈는 payload length에 포함되지 않고
전송되지도 않는다.

AH header는 IPv4용으로는 32bit의 multiple이 되어야 하고 IPv6은 64의 multiple. MAC의 output이 이러한
요구가 없으면 AH header는 padded되어야 한다. pad값에 대한 requirement는 없으나 ICV 계산에 포함되어야 하고
pad size는 payload length를 반영해야 한다. mandatory-to-implement authenticator는 적절히 align되어야
하고 HMAC-MD5-96이나 HMAC-SHA-96은 padding이 필요없음.

ICV는 SA와 SA에서 authenticator로서 identify되는 algorithm에 대한 전체 IP packet(AH header를 포함함)
으로 부터 key passing에 의해 계산된다. mutable field는 zero로 채워져서 ICV에 포함되지 않음. ICV value
는 AH의 authentication data field에 복사되고, mutable field는 IP processing에 의해 적절히 채워진다.

AH processing이 이제 완성되고 AH-protected IP packet은 output이 될수 있다. packet size에 따라서,
on the wire placing 이전에 fragmented 될수도 있고, two IPSec peers 사이에서 router에 의해 fragmented될수
있다. 이는 문제가 되지 않고, input processing에 관계된다.

.Input Processing
만약 protected packet이 receipt되기전에 fragmented가 일어나면 AH input processing 이전에 reassembly가
요구된다. ICV가 generated된 같은 데이터가 아니면 ICV check는 fail을 낼것이다.
The Authentication Header document (RFC 2402) 는 현재 IPv4 spec은 reassembly된 후에 offset field가 0가
되도록 요구하거나 more fragment flag가 clear되는것을 요구하지 않는다. AH는 그러므로 inbound packet이
resembles the outbound packet the peer sent를 guarantee하도록 reassembly에대한 requirement를 부여한다.
fully-formed, AH-detected IP packet. fully formed, AH-protected IP packet은 AH input processing에 대해
pass될수 있다.

IPsec packet을 처리할때 젤먼저 할일은 그것을 보호할때 사용할 SA를 찾는것이고 AH는 이 관점에서 ESP와 다르
지 않다. SA(IP header의 목적지 주소, protocol( 여기서는 51번), AH header로부터 의 SPI에 의해 identify된다.
SA가 없으면 packet은 discard된다.

SA가 발견되면, seq number check가 수행된다. optional이고 antireplay check는 이 패킷이 새로운것인지 혹은
오랜후에 받은지를 결정한다. 이 check가 fail되면 discard됨.

now ICV가 check된다. 먼저, ICV value in the authentication data field of the AH header는 저장되고 zero로
된다. IP의 mutable field는 zero가 되고, authenticator algorithm and payload length이 implicit하게 data
authenticated up to the requirement of the algorithm, implicit padding is added. this implicit padding
must contain the value zero. The authenticator algorithm is then applied to the entire packet and
resulting digest is compared to the saved ICV value. 만약 match되면 IP packet은 authenticated, match
되지 않으면, packet은 discard된다.

ICV가 한번 verified되면, sliding received window seq number는 필요하면 advanced. 이것이AH processing
의결론. saved IP header는 restore될수 있고 , further processing을 막기 위해 mutable fields는 0으로 되고
전체 authenticated datagram은 IP processing에 pass될수 있다.

-----------
  IPSec 5. ESP  
Author: 이윤수    
Date: 2002-02-26 오후 6:48:48 from '211.237.240.191' of '211.237.240.191'

Chapter 5. ESP
provide confidentiality with an encryptor and data integrity with authenticator
provide optionally antireplay up to the recipient of the packet.
The ESP Header
IPv4에서 ESP header는 IP헤더 바로 다음에 따라옴 mode에 상관없이.
IPv6에서는 ESP header위치는 extension header의 여부에 따라 결정. ESP header는 목적지 route를 변경할수
있는 extension header바로 두에 옴. hop-by-hop ruting, fragment header를 포함함.
ESP header는 destination options를 보호하는것이 바람직하므로 destination options앞에 와야 함.
extension이 있으면 Extention header의 다음에 오는 ESP 헤더필드가 50이되고 그렇지 않으면
IPv6헤더의 다음 헤더필드가 50이 됨.

ESP header다음에는 upper layer protocol header(TCP 혹은 또다른 IP 헤더)가 오고 이것은 ESP header에
의해 결정됨.
confidentiality와 integrity를 제공하는데 두개의 ESP 패킷은 동일하지 않고 얼마나 많은 정보를 authenticate
할건지, 효율적인 처리를 할것인지에 달려있다.

SPI field - combined with dst addr, protocol in the preceding IP header, identify appropriate security
association to use in processing the packet.
SPI는 IKE excahnge시에 destination에서 select하도록 만든 값이다. authenticated되지만 encrypt안됨.
SPI가 encryption algorithm, key상태를 identify하는데 사용되기때문에.

sequence number - antireplay service를 제공.
authenticated but not encrypted because determin packet is a duplicate, 버릴 decrypt하는데 리소스를
잡아먹을 필요가 없음. confidentiality가 필요없음.

ESP에 의해 보호되는 실제 data는 payload data field에 있다. protected data field is used to contain
any initialization vector that describes how to use ESP with a particular algorithm must define
the location of the IV and address any alignment issues that may arise tue to the addition of the
IV in the payload data field.
mandatory-to-implement algorithm (DES-CBC), the IV is the first 8 octet of data in the
protected data field. not encrypted

Padding - maintain boundary. encryption algorithm의 input으로 multiple block size가 요구됨.
if confidentiality is not employed by the SA, padding is used to right-justify the pad length
and next header fields of the ESP header. 이미 payload data가 alignment가 제공된다면 padding이
필요없지만 크기가 255byte보다 작으면 padding으로 채워져야 한다. 이는 실제 데이터 크기를 숨기기
위해서도 사용됨. padding의 content는 confidentiality에 사용되는 encryption algorithm에 달려있다.
알고리즘에서 정의 되지 않으면 ESP는 pad의 첫바이트를 1로 채우고 나머지를 계속 1씩 증가시키면서 채운다.
pad값의 check는 receiver에서 decryption에 부가적인 check로 그리고 만약 인증이 수행되지 않으면 cut-
and-paste attack같은 부가적인 protection으로 check되어야 한다.
pad length 필드는 payload data의 실제길이를 restore하기위해서 사용할수 있다.
mandatory, no pad이면 pad length는 이를 가리켜야 한다.

next header field는 data field에 포함되어있는 data의 타입을 가리킨다. If ESP가 tunnel모드에 적용되면
4, (IP-in-IP), ESP가 transport모드에 적용되면 upper-level protocol의 타입 (예를들어 TCP면 6번)

authentication data field는 ESP packet의 data integrity check(주로 keyed hash function)의 결과를
보관하는데 사용. field의 길이는 SA에 의해 수행되는 authentication algorithm에 달려있음.
SA에 authenticator가 정해지지 않으면 이 필드는 없음.

- ESP modes

transport - tunnel

- ESP processing

ESP에서 IP packet의 처리는 mode에 따라 부분적으로 다르다. cipher text는 authenticated, authenticated plaintext
는 encrypted되지 않음. that means outbound packet은 encryption이 먼저 일어나고 inbound packet은 authentication
이 먼저 일어남.
DES-CBC with an explicit IV must-implement : RFC 2405
HMAC-MD5-96, HMAC-SHA-96 : RFC 2403, RFC 2404

.Outbound Processing

IPv4 - IP header의 protocol field는 ESP header의 next header field로 복사되고 ESP header의 나머지가 채워짐.
SPI field is assigned SPI from 이 패킷을 처리하는데 사용되는 paticular SA in the SADB,
sequence number는 sequence의 next value가 채워지고 pad, pad length 값이 사용됨.
IP header의 프로토콜 필드값은 50 (ESP)
IPv6 - header의 삽입만 빼고 비슷함. ESP header는 extension header후에 들어가는데 이헤더는 route를 수정할수
있음.

tunnel mode application, ESP header는 IP packet을 포함. ESP header의 next header field는 4 for IPv4
41 for IPv6 나머지는 transport모드와 같은 방법임. src addr은 ESP에 의해 적용받는 device 자체, dst addr
은 ESP를 적용할때 사용되는 SA로부터 받음, protocol은 50 (ESP), 나머지는 local IP processing에 따라 채워짐

mode에 상관없이 다음 step은 동일함. packet (payload data부터 next header field까지)은 적절한 SA에서
cipher를 사용하여 encrypted되고, ESP header에서 encrypted ciphertext를 포함하여 ESP trailer까지 적절한
SA에서 authenticator를 사용하여 authenticated됨. authenticator의 결과는 authentication data필드로 삽입됨.

ESP header를 붙일때 fragmentation check의 수행은 필요치 않음. 결과 packet이 MTU보다 크면, 단순히 fragment
됨. input processing에서 다뤄짐.

.Input Processing

ESP packet의 수신에서 receiver는 처리되기 전에 tunnel mode인지 transport mode인지 모른다.
packet처리에 사용되는 SA에 기반하여, 알수는 있지만, decrypted될때까지 ESP가 protecting하는것을 알수는없다

fragment된 IPSec packet이면, 모든 fragment된 패킷을 받을때까지 retained되어야한다. fragmented된 IPSec 패킷은
data integrity check등을 먼저 check하는데 fail을 내기때문에 처리될수없다.

ESP packet의 recipient의 첫번째 일은 이를 처리하는 SA가 존재하는가 하는것이다.
baseic IPSec requirement임. ESP에 특화된것이 아님. SA가 없으면 drop함. Input processing에서는 SA가 존재
해야만 시작할수 있음.

valid SA가 identify되면, packet이 처리됨. 1. sequence number(not duplicate, SA에 포함된 sequence number window의
오른쪽에 있지 않은지)를 먼저 check함. 2. ESP는 ciphertext를 authenticate하므로 다음일은 packet을 authenticate이다.
authentication data를 뺀 전체 ESP 패킷이 SA로 부터 authenticateor algorithm에 적절한 키로 pass됨. 만약
결과 digest가 authetication data field에 포함된 data와 매칭되면 packet은 authenticated된것임.
3. next step은 decryption. ESP packet(payload data부터 next header field까지)는 SA로 부터 key와
cipher algorithm에 의해 decrypted됨. decryption이 잘 되었는지는 pad의 내용으로 verify.

4. 그담에는 resulting packet의 preliminary validity check가 이루어짐. IF the SA used to process the packet dictates
that only ESP packets in a particular mode (transport or tunnel) can be processed, packet must be checkd
for compliance. if packet이 요구되는 mode에 적합하지 않으면 drop.

packet은 이제 ESP header없이 rebulit될수 있음. transport모드일때, upperlayer protocol header는 IP header와
syncd되고 ESP header의 다음 header필드는 IP의 protocol field로 복사됨, IP checksum다시계산하고;
터널모드의 경우는 outer IP header와 ESP header는 단순히 버리고, 필요한것은 decapsulated packet이다.
이시점에서 또다른 validity check를 해야 함. IPSec SA는 특정호스트에서만 처리되는 packet이 필요 (만약 tunnel
모드일때는 특정 포트와 프로토콜) 만약 packet이 SA가 가리키는 이러한 요구에 부응하지 않으면 drop

reconstructed and validated packet can now be forwarded for further. if transport mode packet, higher layer
protocol (TCP/UDP)에서 받음. tunnel mode이면 IP processing stream으로 reinsert되고 궁극의 목적지로 forward.

if reconstructed and validated packet이 fragment되면 모든 fragment이 received, reconstructed, validated and
reassembled될때까지 이 패킷을 가지고 있어야 함. if IPSec이 다른 host를 대신하여 network entity에 의해서
적용되면, tunnel mode에서 특정 port에서 허용되는 패킷을 처리하는데 사용되는 SA가 필요함.
어떤 fragments는 정보를 가지고 있지 않기때문에 fragments를 retain하고 목적지로가는 모든 fragments을
reassembling하는것이 필요함. 목적진s SA정보가 없기때문에 reconstructed packet이 valid한지 그렇지 않은지는
알수 없다. 처리속도상의 이유로, it is recommended that network entities applying IPSec to transient traffic
not retain decrypted and validated fragmented IPSec packets that must always be retained until a complete
IPSec packet can be reassembled.

-------

IPSec 4. IPSec Architecture

  IPSec 4. IPSec Architecture  
Author: 이윤수    
Date: 2002-02-26 오후 6:48:13 from '211.237.240.191' of '211.237.240.191'

4. IPSec Architecture

- The IPSec Roadmap
The IPSec protocol include AH, ESP, IKE, ISAKMP/Oakley, and transforms.
IPSec is a suite of protocols, important to understand how these protocols interact with each other and how
these protocols are tied together to implement the capabilities described by the IPSec architecture.

IPSec define the capabilities the hosts and gateways should provide. IPSec architecture requries the host
to privide confidentiality using ESP, and data integrity using either AH or ESP and antireplay protection.
however the architecture document does not specify the header formats for these protocols.

ESP and AH document define the protocol, payload header format, service they provide. packet processing rule.
they don't specify transforms that are used to provide these capabilities.
기존 algorithm이 insecure하다고 되어 새로운 algorithm이 define될수 있다.
does not mandate any change to the base protocols.

The trasform define the transformation applied to the data to secure it. This includes the algorithm, key
size, how they are derived, transformation process, any algorithmic-specific information. It is important
to be specific about the necessary information so that different implementations can interoperate.
DES-CBC transform is defind for ESP. If we do not specify how the IV is derived, two implementations ends up
deriving the IV in different ways. and they never be able to inter operate.

IKE generates keys for the IPSec Protocols. IKE is used to negotiate keys for other protocol that need keys.
other protocol require security service (OSPF)
IKE의 payload format은 generic. is achived by separating the parameter IKE negotiates from the protocol itself.
The parameter that are negotiated are documented in a separate document called IPSec DOI

policy is impotant component not yet a standard.
two entities can communicate with each other and what transforms to use.

issue with policy are representation and implementaion
representation deals with definition of policy, storage, retrieval.
implementation addresses the application of policy for actual communication.

- IPSec Implementation

IPSec can be implemented and deployed in the end hosts or in the gateways/router or in both.

.Host Implementation
advantage
provide security end to end
ability to implement all modes of IPSec security
provides security on a per flow basis
ability to maintain user context for authentication in establishing IPSec connection.
Host implementation can be classified into
Implementation integrated with OS
BITS(network/datalink layer 사이의 protocol stack)

.OS Integrated
ICMP와 같이 IPSec layer needs the service of IP layer to construct the IP header.
장점
.IPSec is tightly integrited into the network layer. it can avail the network service such as fragmentation,
PMTU, user context(sockets). efficient.
. easier to provide security services per flow as the key management, the base IPSec protocols, and
network layer can be integrated seamlessly.
. All IPSec mode are supported

.Bump in the Stack
OS integrated의 단점: OS vender에 의해 제공되어야 한다.
network/data link layer사이에 삽입
BITS의 장점은 complete solution을 제공하는 구현이 가능. OS vender로서 integrated solution을 제공.
all feature required to provide a complete solution을 가지지 않고

.Router Implementation
provides the ability to secure a packet over a part of a network.
advantage
. ability to secure packets flowing between two network over a public network
. ability to authenticate and authorize users entering the private network. many organization에서
telecommute over Internet할때 VPN이나 intranet을 구축시 사용. 전에는 dial-up user만 가능했음

Router implementaion two type
1. Native implementation. IPSec integrated router software.
2. BITW. IPSec is implemented in a device that is attached to the physical interface of the router.
어떤 routing algorithm도 수행하지 않고 secure packet만 사용함.

router는 가능한 빨리 packet forwarding을 하느것이 중요한데 IPSec때문에 security가 필요없는 packet
이 영향을 받으면 안됨. many implementation은 public key operation을 수행, random number generation,
encryption/decryption, calculating hashing을 하는 hardware를 이용함.
another issue is IPSec contexts. 메모리가 비싼데 거대한 routing table을 유지하는것이 issue.

- IPSec Modes
transport mode vs tunnel mode
AH vs ESP
AH and ESP header do not change between tunnel or transport mode. difference : protecting IP packet or IP payload

.transport mode
AH and ESP protect the transport header.
AH and ESP intercept the packets flowing from the transport layer into then network layer
종단간의 encrypt가 필요하면 transport mode of ESP
authenticate transport layer packet이 필요하면 transport mode of AH 가 사용
security in transport layer가 enable되면 transport layer packets flow into the IPSec component.
IPSec component add AH, ESP or both headers
라우터는 network layer header이상을 바꿀수 없지만
Insert transport mode IPSec header for packets flowing through a router is a villation of this rule.
AH and ESP둘다 transport mode에서 사용되면 ESP먼저 적용돼야 한다. 반댜의 경우는 data integrity가 오직 transport payload에 적용된다
많은 BITS implementation은 transport mode는 지원안하고 tunnel model만 지원할수 있다
.tunnel mode
inner - outer IP header
IPSec support nested tunnel

- SA
SA determine the IPSec protocols used for securing the packet, transforms, keys, key의 유효기간.
SADB maintains the SAs that the IPSec protocols use to secure packets.

SA는 one way, simplex, two host가 ESP로 통신중이면 host A 는 outbound에 대해서 SAout, inbound에 대해
SAin을 가진다. host B도 그에 대한 쌍으로 존재함. 같은 cryptographic parameter(key)를 공유하는 SA쌍을 가짐.
protocol specific. 만약 AH, ESP로 통신중이면 각 protocol당 SA를 가진다.

IPSec Architecture의 또다른 component SPD는 works in conjunction with SADB in processing packets.
policy define security communication characters between two entity and what protocol to use in what modes
adn transform to use and how the IP packet are treated.

.SPI

SPI is a 32bit entity used to uniquely identify an SA at the receiver.
mentioned before that the security context or SA is contract betwween two hosts communicating securely
and indeciates the parameter(key, algorithm).
for the source - selectors
destination - transport layer에 속하는 field때문에 selector가 모든필드에 접근이 불가능함.
solution - SPI that identify the SA on the destination is sent with every packet
destination use this value to index into the receiving SADB and fetch the SA.
uniqueness? receiver/destination guarantee uniqnessness. mainain a separate SPI domain for each protocol
IPSec architecture specify in the packet identify SA

the receiver allocates the SPI that is stored as port of the SA on the sender.
sender는 receiver가 SA를 identify할때 unique하게 사용할수 있다는 가정하에 패킷을 보내고 만약 uniqueness를
guarantee하지 못하면 packet은 invalid keys나 transform을 사용한것으로 간주하고 security check가 fail됨.

sending host는 SADB에서 unique하게 참조하기 위해 selector를 사용. lookup의 output은 SPI를 포함하는
all security parameter를 nego하는 SA임.
SPI는 의 매핑만 gurantee하면 SA가 expire되어도 재사용됨.
host가 multihomed일경우에 src addr이 사용됨. 이경우 는 ambiguity하므로 src가 사용됨.

SPI는 AH와 ESP header의 일부임. receiving host는 SA를 indentify할때 를 사용.
src를 사용할수도있지만 표준은 아니고 implementation specific.

.SA Management
creation , deletion
manual or through IKE

. Creation
two process - SA parameter negotiatin & update SADB with SA

manual keying is mandatory. these SA never expire.
IPSec이 사용되는 환경에서 SA는 IKE같은 Internet standard key management protocol을통해 생성된다.
connection이 secure하고 SA를 찾을수 없을때 IKEㄴㄴ IPSec kernel에 의해 수행된다.
IKE는 destination이나 intermediate host/router와 SA를 nego하고 policy에 따라 SA를 생성한다.
SA가 생성되면 SADB에 추가하고 두 host간에 secure packets이 start flowing된다.
nested나 chanined implementaion of IPSec에서 policy requrires establishment of multiple SAs
collection of SA를 SA bundle라 부른다.

. Deletion
lifetime expire
key compromised(손상)
SA를 이용한 encrypt/decrypted or authenticated 바이트 수가 policy에 의해 threshold를 초과
상대방에서 SA를 삭제하라는 요청

deleted by manual or trought IKE
IPSec은 key refresh를 제공하지 않고 SA를 삭제하고 새로운 SA를 nego/create할수 있음.
SA가 한번 삭제되어도 사용되던 SPI는 재사용될수 있음.
communication stalling문제를 해결하기위해 기존 SA를 expire하기전에 새로운 SA를 nego한다.
이동안 여러개의 SA가 존재할수 있지만 새 SA를 사용하는것이 바람직하다.

. Parameter
SA는 secure communication의 context를 유지. protocol-specific and generic field를 저장.
이 field는 IP packet을 처리하는데 사용됨. 어떤 필드는 SA가 packet을 처리하는데 사용될때 update됨.
1. sequence number
32bit. outbound processing. AH and ESP둘다 사용, replay attach을 detect할때 사용. 0가되면 보통
SA를 다시 맺음. 같은 key로 4G 이상 보내면 unsafe함.
2. sequence number overflow
outbound
3. Antireplay Window
inbound processing
4. Lifetime
SA 가 사용할수 없을경우와 관련
SA를 사용해서 secure된 byte수나 SA가 있었던 기간 혹은 둘다에 의해서 정해짐.
SA의 lifetime이 expire되면, 더이상 사용될수 없음.
soft lifetime - SA가 expire될것을 kernel에 경고하는데 사용
hard lifetime - expire되면 새 SA를 nego하도록 함.
5. Mode
tunnel / transport / wildcard
wild card일때 tunnel or transport mode가 될수 있고 이에 대한 정보는 socket같은 다른데서 가져옴.

6. Tunnel Destination
tunnel모드일때 목적지 - outer header의 IP주소
7. PMTU parameter
tunnel모드일때, packet이 fragment될수 있도록 PMTU정보를 유지.
SA는 PMTU와 aging filed를 유지.

. Security Policy
polciy in SPD. database is indexed by selector and info on the security service offered to an IP packet
policy는 inbound outbound따로 유지 된다 asymetric policy를 제공하기 위해서. 그러나 key management protocol
은 항상 양방향 SA로 nego한다. 실ㅈ로 tunneling and nesting은 symmetric이 될것이다.
outbound traffic에 대해서 SADB에서 SA lookup의 output은 SA의 pointer나 SA bundle의 pointer이다.
SA 혹은 SA bundle은 policy에서 정해진 ountbound packet을 처리할때 요청될것이다.
만약 SA가 맺어지지 않았으면 key management protocol 이 packet establish를 수행한다.
inbound traffic 에 대해서는 처음으로 security processing을 제공됨. SPD는 selecter가 packet에대한 policy
를 validate하는데 참조된다.
security policy는 polciy management를 add, delete, modify policy를 관리하는데 필요함.
SPD는 kernel에 저장되고 이에대한 interface가 제공된다. implementation specific하고 표준이 없음.

. Selectors
determine the security services affored to a packet. extracted from the network , transport layer headers
1. Soure Address
wild card/ address range/ network prefix/ specific host
2. Destination Address
used as a selector differ used to look up SA in the case of tunneled IP packet
(inner/ outer header 가 다르기때문에)
3. Name
is used to identify a policy tied to a valid user or system name. include a DNS name. Distinguished
Name, or other name types defind in the IPSec DOI. used as a selector only during the IKE nego,
nat during the packet processing as there is no way to tie an IP address to a name presently.
4. Protocol
specify transport protocol if access가 가능할때. 일반적으로 ESP는 trasport is not accessable.
5. Upper Layer ports
polciy is applicable할때 src, dst port가 제공됨. port가 inaccessible할때 wild card가 사용됨.

.IPSec Processing
outbound processing , inbound processing
Outbound
tcp->ip layer. IP layer consults the SPD to determine the security service afforded to this packet.
SPD의 input은 이전 section에서 defined된 selector output은 다음과같다.
1. Drop
2. Bypass
3. Apply
SA가 establish되어있으면 SA나 SA bundle의 pointer를 리턴. establish가 되어있지 않으면
IKE가 SA를 establish를 수행. 만약 정책의 output이 IPsec을 packet에 적용으로 되어잇으면 packet은
SA가 establish될때까지 전송되지 않는다.
SA가 맺어진 후에 AH와 ESP헤더가 적절하게 붙여서 처리된다.

예제 4.13
IKE가 총 4개의 SA를 establish. 2개는 inbound이므로 생략하고 outbound 2개에 대해서
SA1는 A와 gateway사이 SA2는 host와 destination 사이임. SA1을 먼저 적용후에 SA2를 적용하면 안됨.

Inbound
if packet이 any IPSec header를 포함하지 않으면, security layer check the policy to dettermine how to
process the packet. selector field를 이용하여 SPD를 참조함.
policy의 output은 discard/bypass/apply
policy가 apply이고 SA가 establish되어있지 않으면 dropped. 그렇지 않으면 packet이 다음 layer로 passing
if IP packet contains IPSec headers, packet is processed by the IPSec layer. IPSec layer extract
SPPI, source addr, dst addr, from IP datagram. SPI, dst, protocol을 이용하여 SADB에서 참조한다. (구현
에따라 source addr도 사용) protocol value is AH or ESP. protocol payload is processed한후에 policy
is consulted to validate the payload. selector are used to retrieve the policy. validation process는
SA가 적절하게 사용 되는지 checking으로 구성. 즉(src, dst in the SA corresponds to what the policy says
and the SA is protecting the transport layer protocol it was supposed to protect.)
tunneled packet의 경우 src dst selecter field는 inner header이지 outer header가 아님.
실제 src, dst가 tunnel의 end point가 아니기 때문에 SPD 는 outer src, dst에 기반하여 SPD를 참조하면
invalid result를 초래한다.
IPSec layer validate the policy, it strips off the IPSec header and passes the packet to the next layer.
(Transport or network layer)
Fragmentation
IPSec does not fragment or reassemble packet. IPSec add IPSec header, it impacts the PMTU length.
if IPSec participate in PMTU discovery, IP layer ends up fragmenting a packet as the addition of
the IPSec header increases the length of the IP datagram beyond the PMTU.

ICMP
IPSec이 tunnel모드일때 it impacts ICMP and the operation of the network.
the problem arises when tunnel header is added by intermediate gateway.
ICMP message are required to send only 64bits of original header.
tunneled header와 IPSec header가 gateway에서 붙으면 icmp error 메세지에 실제 소스가 존재하지 않게됨.
gateway는 적절하게 message를 forward할수 없음.
IPSec needs to maintain some state and perform extra processing.



---
IPSec 3. IP Security Overview

  IPSec 3. IP Security Overview  
Author: 이윤수    
Date: 2002-02-26 오후 6:47:30 from '211.237.240.191' of '211.237.240.191'

3. IP Security Overview

1. sender로부터 받은것인지
2. sender가 보낸 original data가 맞는지
3. 중간에 다른사람이 inspect하지 않았는지
를 guarantee하지 못함

IPSec은 IP datagram을 보호하는 방법

data origin authentication(데이터의 출발지 인증)
connectionless data integrity authentication, (데이터 무결성 인증)
data content confidentialitiy (데이터 내용의 보호)
anti-replay protection (replay attack 방지)
limited traffic flow confidentiality (약간의 traffic flow 보호)

method of specifying the traffic to protect
how that traffic is to be protected
to whom the traffic to sent

AH
proof-of-data origin, data integrity, antireplay protection

ESP
AH + optional data confidentiality and limited traffic flow confidentiality

- The Architecture

Transport mode - protect upper-layer protocol
tunnel mode -entire IP datagram

SA - unidirectional, typically exists in pairs, creatred manually or dynamically, reside in SADB(Security Association Database) identified by SPI(Security Parameter Index) in IPSec header, IPSec protocol value,
destination address to which the SA applies manually created SA has no lifetime until deleted dynamicaly created, SA may have a lifetime which is negotiated between IPSec peers by key management protocol

IPSec Architecture defines the granularity which user specify his policy

IPSec policy
ex1> local protected subnet - subnet of a remote peer : encrypted with DES and authenticatedwith HMAC-MD5
ex2> all telnet traffic - mail server from the remote subnet : encryption with 3DES and authentication with HMAC-SHA
ex3> All Web traffic - encryption with IDEA and authentication with HMAC-RIPEMD

IPSec policy is maintained in the SPD(Security Policy Database)
entry of the SPD define the traffic to be protected, how to protect it, and with whom the protection is shared
for each packet entering or leaving the IP stack, the SPD must be consulted for possible application of security
An SPD entry may define discard/bypass/apply

IP traffic is mapped to IPSec policy by selector
IPSec selector : DST IP, SRC IP, upperlayer protocol, sport, dport,
a data sensitivity level (if IPSec system provide flow security)

opaque?

SPD entry define apply as an action and does not point to any existing SAs in the SADB those SA will have to be created before any traffic may pass, if inbound traffic and SA does not exist -> drop
outbound traffic -> created dynamically using IKE

IPsec Architecture define the interaction of the SPD, the SADB with the IPSec processing functions - encapsulate
and decapsulate
and define how various IPSec implementations may exist.

IPSec protocols provide an antireplay service. service number, sliding recieve window
When a SA is created, the sequence number is initialized to zero and prior to IPSec output processing the value
is incremented, New SAs must be created prior to the sequence number wrapping around back to zero

key

- ESP

confidentiality, data integrity, data source authentication of IP packet, provide protect replay attack
RFC 2406
multiple algorithm defined in SA
cipher for confidentiality
authenticator for authentication
each ESP SA have at most one cipher and one authenticator
possible NULL but not both

ESP header - clear text
procedure
verify sequence number - clear text
verify integrity of the data -clear text
decrypt data

- AH

RFC 2402
RFC 2403 for HMAC-MD5-96
RFC 2404 for HMAC-SHA-96

- IKE
SA are used with IPSec to define the processing done on a specific IP packet.
An outbound packet produces a hit in the SPD and SPD entry points to one or more SA an SA bundle.
SPD로부터 policy를 instanciate하는 SA가 없으면 생성함. 여기서 IKE가 필요함.
IKE의 목적은 IPSec peer간에 SA(establish shared security parameter and authnticate key)를 맺는것.

ISAKMP define packet format, retransmission timer, message construction requirements, in effect, the language.
Oakley and SKEME define the step two peers must take to establsih a shared, authenticated key.
IKE uses the ISAKMP laguage to express these and other changes.

IKE - general-purpose security exchange protocol used for policy nego and establish of authenticated keying
material for (SNMPv3, OSPFv2..)
IKE에서 사용되는 spec은 DOI에 정의된다.
DOI for IPSec (RFC 2407) define how IKE nego IPSec SA

IKE SA vs IPSec SA
IKE SA는 두 peer가 통신하는 방법을 정의:IKE traffic을 encrypt하는 알고리즘,
remote peer를 인증하는 방법등.
IKE SA produce any number of IPSec SA action that IPSec implementation take when an SPD entry has a NULL SADB pointer / is to communicate the security requirements from the SPD to IKE and instruct it to establish IPSec SA.

IPSec SA는 IKE에 의해 optional하게 perfect foward secrecy를 가지는 key와
peer indentity를 establish할수 있다.
하나의 IKE exchange를 사용하여 하나이상의 IPSec SA를 생성하고, 하나의 IKE SA
에의해 여러개의 exchange가 수행될수 있다.
IKE options 이 풍부함은 extensible하지만 complex함.

IKE protocol은 IPSec이 수행될 양단에서 수행되고 IKE peer는 또한 IPSec peer이다.
protocol은 initiator와 responder가 있는 request-response 타입이다.
initiator는 IPSec에 의하여 SPD entry에 매칭되는 outbound packet의 결과로 SA가 생성되도록 지시하는 쪽이고, responder에게 protocol을 initiate한다.

IPSec의 SPD는 IKE에게 어떻게 맺을지가 아니라 무엇을 맺을지를 가리키는데 사용된다.
IKE가 IPSec SA를 맺는 방법은 policy setting에 기초한다. IKE는 protection suites라고 하는 policy를 정의한다. 각 protection suite는 최소한 encryption algorithm, hash algorithm, DH group, 인증에사용되는 method등을 정의해야만한다.
IKE의 policy DB는 preference의 순서로 가중치된 모든 protection suites의 리스트이다.
두 peer가 agree하는 특정 policy suite는 그들의 communication이 되는 나머지 방법을 기술하기때문에 이 nego가 two IKE사이에 하는것중 맨먼저이다.

두 peer가 shared secret을 establsih하는 여러방법이 있지만 IKE는 DH exchange를 사용한다.
DH excahnge를 하는것은 negotiable하지 않지만 parameter는 negotiable하다. IKE 는 Oakley document로 부터 5 group
을 가져왔는데 3개는 exponentiation modulo a large prime을 하는 traditional exchanges, 2개는 elliptic curve group
. DH exchange와 shared secret을 establish하는것은 IKE protocol의 second step이다.

DH exchange가 끝나면 two peer는 shared secret을 갖고 authenticated되지 않음. IKE는 communication을 protect하기
위해서 이 shared secret을 사용. IKE exchange에서 다음단계는 DH shared secret의 authentication즉 IKE SA의 authentication.
IKE에서 define하는 authentication메소드가 5개가 있음.
preshared key,
digital signature using the Digital Signature Standard,
digital signature using the RSA public key algorithm,
encrypted nonce exchange using RSA,
revised method of authntication with encrypted nonces that is subtly
different than the other encrypted nonce method.
(A nonce is merely a random number.)
IKE exchange에서 각 party 는 exchange의 state에 대한 nonce를 contribute한다.

IKE SA의 생성은 phase one으로 참조된다. phase one이 완성되면, phase two(IPSec SA의 생성)이 commence됨.
phase one에서 2 exchanges가 있는데 Main Mode exchange나 Agressive Mode exchange. Agressive mode is faster, but
main mode is flexible. single phase two exchange - Quick mode. phase one exchange로 부터 생성된 IKE SA의
보호하에 IPSec SA를 nego한다

IPSec SA에서 사용되는 key는 기본적으로 IKE secret state로부터 얻어진다. Pseudo-random nonce는 Quick mode에서
exchange되고 key를 generate하는것과 모든 SA가 unique한 key를 갖는것을 gurrentee하는 secrete state로 hashed
된다. all such keys 는 그들은 same root key(IKE shared secret)로부터
derived되므로 PFS의 property를 가지지 않음. PFS를 제공하기 위해 DH public value와 derived된 그룹은 nonce와
IPSec SA negotiatin parameter로 exchange된다. resultant secret PFS를 보장하기위한 은 IPSec SA key를 generate
하는데 사용된다.
IPSec SA를 적절하게 construct하기 위해 initiator of protocol must specify to IKE which selector from his SPD
matched the traffic. 이 정보는 Quick Mode에서 payload를 identity하는데 사용하고, 이러한
traffic이 SA에 의해 보호되는것을 constrain하는데 사용.
At the time of this writing the selector suites in the IPSec Architecture Document was richier than that
allowed by the IKE protocol. the IKE protocol can't express port range, nor express 'all except' construct
Quick mode exchange에서 selector indication의 specify는 possible selector의 full expression을 허용하도록 바뀔것이다.

Quick Mode의 종료까지 IKE SA는 quiescent state를 리턴하고, IPSec 이나 peer로부터의 further communication으로
부터 funther instruction을 기다린다. IKE SA는 lifetime이 expire되거나 external event(IKE SA의 database를
flush한다는 명령같은) 가 SA를 삭제하라는 event가올때까지 active상태이다.

phase one exchange(Main mode이건 aggressive mode이건)에서 처음 2메세지는 cookie교환이다. pseudo-random number
를 닮았으나 temporal, peer IP address에 bound됨. cookie creation은 unique secret과, peer identity,
time based counter을 함께 hashing해서 이루어짐. 보통 hash의 결과가 observer에게는 random number이지만 receipient
는 재빨리 hash를 reconstruct해서 cookie를 generate할것인지 아닌지를 결정해야 한다. 이는 peer에게 cookie를
bind하고 제한된 DOS protection을 제공한다 왜냐하면 the DH excahnge는 round trip이 끝나기전까지, cookie의
exchange가 이루어지기 전까지는 수행되지 않는다.

bogus IKE message를 만드는 루틴과 forged source address를 destination에 보내는 루틴을 write하는것은 간단하다.
responder는 진짜 IKE peer라고 말하는것과 attacker가 forging packet을 쉽게 overwhelem되지 않는다는 강한 믿음이
있기전에는 어떤작업을 수행하지 않는다. 그러므로 main mode에서 responder는 initiator로부터 second message를
받기 전에는 그리고 initiator에서 생성된 cookie를 포함하는 message를 검증하기 전에는 DH작업을 수행하지 않는다.

Agreesive mode 는 DOS에 대한 protection을 가지지 못한다. 각 party는 3 messages에서 exchange complete가 일어남
(Main mode가 6 messages) and 각 메세지에서는 more information을 pass
첫번째 aggressive mode 메세지를 받을때까지 responder는 DH exponentiation을 해야만 한다. 이것은 가가 받은
다음 메세지의 cookie르 체크하기 이전이다.
these cookie는 IKE SA를 identify하는데 사용한다. phase one exchange동안 IKE SA는 one state에서 받은 메세지를
처리하고 resonse를 보내는 처리까지하고 다음 state로 넘어간다. state advancement는 one way
phase two exchange는 자신에게 unique하다. phase one IKE SA에 의해 보호되나 자신의 own state를 가지고 있다.
그러므로, peer간에 동시에 nego되는 같은 IKE SA에 의해 보호되는 두개이상의 phase two exchange가 가능하다.
each phase two exchange는 그러므로 protocol의 진보에 따라 transient state machine을 생성할수 있다. exchange
가 끝나면 state는 버려진다. transient state machne의 각각이 같은 IKE SA에 의해 보호되므로 , exchange의 메세지
는 모두 같은 cookie pair를 가진다. identifier to each phase two exchane는 이러한 exchange를 single pipe로
multiplex라흔ㄴ데 사용된다. 이 identifier를 Message ID라 한다.

정기적으로 IKE process가 any exchange outside에 있는 그의 peer에게 message를 보내는것이 필요하다.
share하는 IPSec SA가 삭제될꺼라는것을 알려주는것, error를 report하는것이 있을수 있다. Notification Message와
delete message는 Informational Exchange로 불리는 unique한 exchange이다. one way message, no retransmission timer,
no response is expected, these informational exchange는 IKE SA에 의해 보호되는것이 phase two exchange와
비슷하지만, unique하고 자신 고유의 state machine을 가진다. 그러므로 Informational Exchange는
Quick Mode excange나, single IKE SA를 통해서 다른 Informational Exchange에서 multiplex될수 있도록 고유의
message ID를 가진다.

compilant IKE의 implementation은 3개의 document가 필요한데 ISAKMP spec(RFC2408), DOI of IPSec (RFC2407),
IKE spec (RFC 2409)