1 // SoftEther VPN Source Code - Stable Edition Repository
2 // Cedar Communication Module
3 //
4 // SoftEther VPN Server, Client and Bridge are free software under the Apache License, Version 2.0.
5 //
6 // Copyright (c) Daiyuu Nobori.
7 // Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan.
8 // Copyright (c) SoftEther Corporation.
9 // Copyright (c) all contributors on SoftEther VPN project in GitHub.
10 //
11 // All Rights Reserved.
12 //
13 // http://www.softether.org/
14 //
15 // This stable branch is officially managed by Daiyuu Nobori, the owner of SoftEther VPN Project.
16 // Pull requests should be sent to the Developer Edition Master Repository on https://github.com/SoftEtherVPN/SoftEtherVPN
17 //
18 // License: The Apache License, Version 2.0
19 // https://www.apache.org/licenses/LICENSE-2.0
20 //
21 // DISCLAIMER
22 // ==========
23 //
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 // SOFTWARE.
31 //
32 // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER
33 // JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH,
34 // DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY
35 // JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS,
36 // AGAINST US (SOFTETHER PROJECT, SOFTETHER CORPORATION, DAIYUU NOBORI OR OTHER
37 // SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND
38 // OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING,
39 // AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
40 // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE
41 // JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE
42 // ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS.
43 // PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE
44 // LAW OR COURT RULE.
45 //
46 // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS YOU HAVE
47 // A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY CRIMINAL LAWS OR CIVIL
48 // RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS SOFTWARE IN OTHER COUNTRIES IS
49 // COMPLETELY AT YOUR OWN RISK. THE SOFTETHER VPN PROJECT HAS DEVELOPED AND
50 // DISTRIBUTED THIS SOFTWARE TO COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING
51 // CIVIL RIGHTS INCLUDING PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER
52 // COUNTRIES' LAWS OR CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES.
53 // WE HAVE NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR
54 // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ COUNTRIES
55 // AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE WORLD, WITH
56 // DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY COUNTRIES' LAWS, REGULATIONS
57 // AND CIVIL RIGHTS TO MAKE THE SOFTWARE COMPLY WITH ALL COUNTRIES' LAWS BY THE
58 // PROJECT. EVEN IF YOU WILL BE SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A
59 // PUBLIC SERVANT IN YOUR COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE
60 // LIABLE TO RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL
61 // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT JUST A
62 // STATEMENT FOR WARNING AND DISCLAIMER.
63 //
64 // READ AND UNDERSTAND THE 'WARNING.TXT' FILE BEFORE USING THIS SOFTWARE.
65 // SOME SOFTWARE PROGRAMS FROM THIRD PARTIES ARE INCLUDED ON THIS SOFTWARE WITH
66 // LICENSE CONDITIONS WHICH ARE DESCRIBED ON THE 'THIRD_PARTY.TXT' FILE.
67 //
68 //
69 // SOURCE CODE CONTRIBUTION
70 // ------------------------
71 //
72 // Your contribution to SoftEther VPN Project is much appreciated.
73 // Please send patches to us through GitHub.
74 // Read the SoftEther VPN Patch Acceptance Policy in advance:
75 // http://www.softether.org/5-download/src/9.patch
76 //
77 //
78 // DEAR SECURITY EXPERTS
79 // ---------------------
80 //
81 // If you find a bug or a security vulnerability please kindly inform us
82 // about the problem immediately so that we can fix the security problem
83 // to protect a lot of users around the world as soon as possible.
84 //
85 // Our e-mail address for security reports is:
86 // softether-vpn-security [at] softether.org
87 //
88 // Please note that the above e-mail address is not a technical support
89 // inquiry address. If you need technical assistance, please visit
90 // http://www.softether.org/ and ask your question on the users forum.
91 //
92 // Thank you for your cooperation.
93 //
94 //
95 // NO MEMORY OR RESOURCE LEAKS
96 // ---------------------------
97 //
98 // The memory-leaks and resource-leaks verification under the stress
99 // test has been passed before release this source code.
100 
101 
102 // IPsec_IKE.c
103 // IKE (ISAKMP) and ESP protocol stack
104 
105 #include "CedarPch.h"
106 
107 //#define	RAW_DEBUG
108 
109 // Processing of IKE received packet
ProcIKEPacketRecv(IKE_SERVER * ike,UDPPACKET * p)110 void ProcIKEPacketRecv(IKE_SERVER *ike, UDPPACKET *p)
111 {
112 	// Validate arguments
113 	if (ike == NULL || p == NULL)
114 	{
115 		return;
116 	}
117 
118 	if (p->Type == IKE_UDP_TYPE_ISAKMP)
119 	{
120 		// ISAKMP (IKE) packet
121 		IKE_PACKET *header;
122 
123 		header = ParseIKEPacketHeader(p);
124 		if (header == NULL)
125 		{
126 			return;
127 		}
128 
129 		//Debug("InitiatorCookie: %I64u, ResponderCookie: %I64u\n", header->InitiatorCookie, header->ResponderCookie);
130 
131 		switch (header->ExchangeType)
132 		{
133 		case IKE_EXCHANGE_TYPE_MAIN:	// Main mode
134 			ProcIkeMainModePacketRecv(ike, p, header);
135 			break;
136 
137 		case IKE_EXCHANGE_TYPE_AGGRESSIVE:	// Aggressive mode
138 			if (ike->Cedar->Server->DisableIPsecAggressiveMode == false)
139 			{
140 				ProcIkeAggressiveModePacketRecv(ike, p, header);
141 			}
142 			break;
143 
144 		case IKE_EXCHANGE_TYPE_QUICK:	// Quick mode
145 			ProcIkeQuickModePacketRecv(ike, p, header);
146 			break;
147 
148 		case IKE_EXCHANGE_TYPE_INFORMATION:	// Information exchange
149 			ProcIkeInformationalExchangePacketRecv(ike, p, header);
150 			break;
151 		}
152 
153 		IkeFree(header);
154 	}
155 	else if (p->Type == IKE_UDP_TYPE_ESP)
156 	{
157 		// ESP packet
158 		ProcIPsecEspPacketRecv(ike, p);
159 	}
160 }
161 
162 // Send a packet via IPsec
IPsecSendPacketByIPsecSa(IKE_SERVER * ike,IPSECSA * sa,UCHAR * data,UINT data_size,UCHAR protocol_id)163 void IPsecSendPacketByIPsecSa(IKE_SERVER *ike, IPSECSA *sa, UCHAR *data, UINT data_size, UCHAR protocol_id)
164 {
165 	bool is_tunnel_mode;
166 	IKE_CLIENT *c;
167 	// Validate arguments
168 	if (ike == NULL || sa == NULL || data == NULL || data_size == 0)
169 	{
170 		return;
171 	}
172 
173 	is_tunnel_mode = IsIPsecSaTunnelMode(sa);
174 
175 	c = sa->IkeClient;
176 
177 	if (c == NULL)
178 	{
179 		return;
180 	}
181 
182 	if (is_tunnel_mode)
183 	{
184 		// Add an IPv4 / IPv6 header in the case of tunnel mode
185 		if (IsZeroIP(&c->TunnelModeClientIP) == false || IsZeroIP(&c->TunnelModeServerIP) == false)
186 		{
187 			BUF *b;
188 			UCHAR esp_proto_id;
189 
190 			b = NewBuf();
191 
192 			if (IsIP4(&c->TunnelModeClientIP))
193 			{
194 				// IPv4 header
195 				IPV4_HEADER h;
196 
197 				h.VersionAndHeaderLength = 0;
198 				h.TypeOfService = 0;
199 				IPV4_SET_VERSION(&h, 4);
200 				IPV4_SET_HEADER_LEN(&h, sizeof(IPV4_HEADER) / 4);
201 				h.TotalLength = Endian16((USHORT)(data_size + sizeof(IPV4_HEADER)));
202 				h.Identification = Endian16(c->TunnelSendIpId++);
203 				h.FlagsAndFlagmentOffset[0] = h.FlagsAndFlagmentOffset[1] = 0;
204 				h.TimeToLive = DEFAULT_IP_TTL;
205 				h.Protocol = protocol_id;
206 				h.SrcIP = IPToUINT(&c->TunnelModeServerIP);
207 				h.DstIP = IPToUINT(&c->TunnelModeClientIP);
208 				h.Checksum = 0;
209 				h.Checksum = IpChecksum(&h, sizeof(IPV4_HEADER));
210 
211 				WriteBuf(b, &h, sizeof(IPV4_HEADER));
212 
213 				esp_proto_id = IKE_PROTOCOL_ID_IPV4;
214 			}
215 			else
216 			{
217 				// IPv6 header
218 				IPV6_HEADER h;
219 
220 				Zero(&h, sizeof(h));
221 				h.VersionAndTrafficClass1 = 0;
222 				IPV6_SET_VERSION(&h, 6);
223 				h.TrafficClass2AndFlowLabel1 = 0;
224 				h.FlowLabel2 = h.FlowLabel3 = 0;
225 				h.PayloadLength = Endian16(data_size);
226 				h.NextHeader = protocol_id;
227 				h.HopLimit = 64;
228 				Copy(h.SrcAddress.Value, c->TunnelModeServerIP.ipv6_addr, 16);
229 				Copy(h.DestAddress.Value, c->TunnelModeClientIP.ipv6_addr, 16);
230 
231 				WriteBuf(b, &h, sizeof(IPV6_HEADER));
232 
233 				esp_proto_id = IKE_PROTOCOL_ID_IPV6;
234 			}
235 
236 			WriteBuf(b, data, data_size);
237 
238 			IPsecSendPacketByIPsecSaInner(ike, sa, b->Buf, b->Size, esp_proto_id);
239 
240 			FreeBuf(b);
241 		}
242 	}
243 	else
244 	{
245 		// Send as it is in the case of transport mode
246 		IPsecSendPacketByIPsecSaInner(ike, sa, data, data_size, protocol_id);
247 	}
248 }
IPsecSendPacketByIPsecSaInner(IKE_SERVER * ike,IPSECSA * sa,UCHAR * data,UINT data_size,UCHAR protocol_id)249 void IPsecSendPacketByIPsecSaInner(IKE_SERVER *ike, IPSECSA *sa, UCHAR *data, UINT data_size, UCHAR protocol_id)
250 {
251 	UINT esp_size;
252 	UINT encrypted_payload_size;
253 	UCHAR *esp;
254 	UINT i;
255 	UINT size_of_padding;
256 	IKE_CRYPTO_PARAM cp;
257 	BUF *enc;
258 	IKE_CLIENT *c;
259 	// Validate arguments
260 	if (ike == NULL || sa == NULL || data == NULL || data_size == 0)
261 	{
262 		return;
263 	}
264 
265 	c = sa->IkeClient;
266 	if (c == NULL)
267 	{
268 		return;
269 	}
270 
271 	// Calculate the payload size after encryption
272 	encrypted_payload_size = data_size + 2;
273 	if ((encrypted_payload_size % sa->TransformSetting.Crypto->BlockSize) != 0)
274 	{
275 		encrypted_payload_size = ((encrypted_payload_size / sa->TransformSetting.Crypto->BlockSize) + 1) * sa->TransformSetting.Crypto->BlockSize;
276 	}
277 	size_of_padding = encrypted_payload_size - data_size - 2;
278 
279 	// Calculate the size of the ESP packet
280 	esp_size = sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size + IKE_ESP_HASH_SIZE;
281 
282 	// Build the ESP packet
283 	esp = Malloc(esp_size + IKE_MAX_HASH_SIZE);
284 
285 	// SPI
286 	WRITE_UINT(esp, sa->Spi);
287 
288 	// Sequence number
289 	sa->CurrentSeqNo++;
290 	WRITE_UINT(esp + sizeof(UINT), sa->CurrentSeqNo);
291 
292 	// IV
293 	Copy(esp + sizeof(UINT) * 2, sa->EspIv, sa->TransformSetting.Crypto->BlockSize);
294 
295 	// Payload data
296 	Copy(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, data, data_size);
297 
298 	// Padding
299 	for (i = 0;i < size_of_padding;i++)
300 	{
301 		esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + i] = (UCHAR)(i + 1);
302 	}
303 
304 	// Padding length
305 	esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + size_of_padding] = (UCHAR)size_of_padding;
306 
307 	// Next header number
308 	esp[sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + data_size + size_of_padding + 1] = protocol_id;
309 
310 	// Encryption
311 	Copy(cp.Iv, sa->EspIv, sa->TransformSetting.Crypto->BlockSize);
312 	cp.Key = sa->CryptoKey;
313 
314 	enc = IkeEncrypt(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, encrypted_payload_size, &cp);
315 	if (enc != NULL)
316 	{
317 		bool start_qm = false;
318 		UINT server_port = c->ServerPort;
319 		UINT client_port = c->ClientPort;
320 
321 		// Overwrite the encrypted result
322 		Copy(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize, enc->Buf, encrypted_payload_size);
323 
324 		FreeBuf(enc);
325 
326 		// Calculate the HMAC
327 		IkeHMac(sa->TransformSetting.Hash,
328 			esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size,
329 			sa->HashKey,
330 			sa->TransformSetting.Hash->HashSize,
331 			esp,
332 			sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size);
333 
334 		//*(UCHAR *)(esp + sizeof(UINT) * 2 + sa->TransformSetting.Crypto->BlockSize + encrypted_payload_size) = 0xff;
335 
336 		if (sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TRANSPORT ||
337 			sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL)
338 		{
339 			server_port = client_port = IPSEC_PORT_IPSEC_ESP_RAW;
340 		}
341 
342 		// Add the completed packet to the transmission list
343 		IkeSendUdpPacket(ike, IKE_UDP_TYPE_ESP, &c->ServerIP, server_port, &c->ClientIP, client_port,
344 			esp, esp_size);
345 
346 		// Feedback the IV
347 		Copy(sa->EspIv, cp.NextIv, sa->TransformSetting.Crypto->BlockSize);
348 
349 		sa->TotalSize += esp_size;
350 
351 		if (sa->CurrentSeqNo >= 0xf0000000)
352 		{
353 			start_qm = true;
354 		}
355 
356 		if (sa->TransformSetting.LifeKilobytes != 0)
357 		{
358 			UINT64 hard_size = (UINT64)sa->TransformSetting.LifeKilobytes * (UINT64)1000;
359 			UINT64 soft_size = hard_size * (UINT64)2 / (UINT64)3;
360 
361 			if (sa->TotalSize >= soft_size)
362 			{
363 				start_qm = true;
364 			}
365 		}
366 
367 		if (start_qm)
368 		{
369 			if (sa->StartQM_FlagSet == false)
370 			{
371 				sa->StartQM_FlagSet = true;
372 				c->StartQuickModeAsSoon = true;
373 			}
374 		}
375 	}
376 	else
377 	{
378 		// Encryption failure
379 		Free(esp);
380 	}
381 }
IPsecSendPacketByIkeClient(IKE_SERVER * ike,IKE_CLIENT * c,UCHAR * data,UINT data_size,UCHAR protocol_id)382 void IPsecSendPacketByIkeClient(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, UCHAR protocol_id)
383 {
384 	// Validate arguments
385 	if (ike == NULL || c == NULL || data == NULL || data_size == 0)
386 	{
387 		return;
388 	}
389 
390 	if (c->CurrentIpSecSaSend == NULL)
391 	{
392 		return;
393 	}
394 
395 	IPsecSendPacketByIPsecSa(ike, c->CurrentIpSecSaSend, data, data_size, protocol_id);
396 }
397 
398 // Send an UDP packet via IPsec
IPsecSendUdpPacket(IKE_SERVER * ike,IKE_CLIENT * c,UINT src_port,UINT dst_port,UCHAR * data,UINT data_size)399 void IPsecSendUdpPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT src_port, UINT dst_port, UCHAR *data, UINT data_size)
400 {
401 	UCHAR *udp;
402 	UINT udp_size;
403 	UDP_HEADER *u;
404 	UCHAR tmp1600[1600];
405 	bool no_free = false;
406 	// Validate arguments
407 	if (ike == NULL || c == NULL || data == NULL || data_size == 0)
408 	{
409 		return;
410 	}
411 
412 	// Build an UDP packet
413 	udp_size = sizeof(UDP_HEADER) + data_size;
414 
415 	if (udp_size > sizeof(tmp1600))
416 	{
417 		udp = Malloc(udp_size);
418 	}
419 	else
420 	{
421 		udp = tmp1600;
422 		no_free = true;
423 	}
424 
425 	// UDP header
426 	u = (UDP_HEADER *)udp;
427 	u->SrcPort = Endian16(src_port);
428 	u->DstPort = Endian16(dst_port);
429 	u->PacketLength = Endian16(udp_size);
430 	u->Checksum = 0;
431 
432 	//Debug("IPsec UDP Send: %u -> %u %u\n", src_port, dst_port, data_size);
433 #ifdef	RAW_DEBUG
434 	IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, data, data_size);
435 #endif	// RAW_DEBUG
436 
437 	// Payload
438 	Copy(udp + sizeof(UDP_HEADER), data, data_size);
439 
440 	if (IsIP6(&c->ClientIP))
441 	{
442 		if (IsIPsecSaTunnelMode(c->CurrentIpSecSaSend) == false)
443 		{
444 			u->Checksum = CalcChecksumForIPv6((IPV6_ADDR *)c->TransportModeServerIP.ipv6_addr,
445 				(IPV6_ADDR *)c->TransportModeClientIP.ipv6_addr,
446 				IP_PROTO_UDP,
447 				u,
448 				udp_size, 0);
449 		}
450 		else
451 		{
452 			u->Checksum = CalcChecksumForIPv6((IPV6_ADDR *)c->TunnelModeServerIP.ipv6_addr,
453 				(IPV6_ADDR *)c->TunnelModeClientIP.ipv6_addr,
454 				IP_PROTO_UDP,
455 				u,
456 				udp_size, 0);
457 		}
458 	}
459 
460 	IPsecSendPacketByIkeClient(ike, c, udp, udp_size, IP_PROTO_UDP);
461 
462 	if (no_free == false)
463 	{
464 		Free(udp);
465 	}
466 }
467 
468 // Get whether the specified IPsec SA is in tunnel mode
IsIPsecSaTunnelMode(IPSECSA * sa)469 bool IsIPsecSaTunnelMode(IPSECSA *sa)
470 {
471 	// Validate arguments
472 	if (sa == NULL)
473 	{
474 		return false;
475 	}
476 
477 	if (sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL ||
478 		sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_1 ||
479 		sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_2)
480 	{
481 		return true;
482 	}
483 
484 	return false;
485 }
486 
487 // Reception process of ESP packet
ProcIPsecEspPacketRecv(IKE_SERVER * ike,UDPPACKET * p)488 void ProcIPsecEspPacketRecv(IKE_SERVER *ike, UDPPACKET *p)
489 {
490 	UCHAR *src;
491 	UINT src_size;
492 	UINT spi;
493 	UINT seq;
494 	IPSECSA *ipsec_sa;
495 	IKE_CLIENT *c;
496 	UINT block_size;
497 	UINT hash_size;
498 	bool update_status = false;
499 	UCHAR *iv;
500 	UCHAR *hash;
501 	UCHAR *encrypted_payload_data;
502 	UINT size_of_payload_data;
503 	IKE_CRYPTO_PARAM cp;
504 	BUF *dec;
505 	UCHAR calced_hash[IKE_MAX_HASH_SIZE];
506 	bool is_tunnel_mode = false;
507 	// Validate arguments
508 	if (ike == NULL || p == NULL)
509 	{
510 		return;
511 	}
512 
513 	src = (UCHAR *)p->Data;
514 	src_size = p->Size;
515 
516 	if (p->DestPort == IPSEC_PORT_IPSEC_ESP_RAW)
517 	{
518 		if (IsIP4(&p->DstIP))
519 		{
520 			// Skip the IP header when received in Raw mode (only in the case of IPv4)
521 			UINT ip_header_size = GetIpHeaderSize(src, src_size);
522 
523 			src += ip_header_size;
524 			src_size -= ip_header_size;
525 		}
526 	}
527 
528 	// Get the SPI
529 	if (src_size < sizeof(UINT))
530 	{
531 		return;
532 	}
533 
534 	spi = READ_UINT(src + 0);
535 	if (spi == 0)
536 	{
537 		return;
538 	}
539 
540 	// Get the sequence number
541 	if (src_size < (sizeof(UINT) * 2))
542 	{
543 		return;
544 	}
545 	seq = READ_UINT(src + sizeof(UINT));
546 
547 	// Search and retrieve the IPsec SA from SPI
548 	ipsec_sa = SearchClientToServerIPsecSaBySpi(ike, spi);
549 	if (ipsec_sa == NULL)
550 	{
551 		// Invalid SPI
552 		UINT64 init_cookie = Rand64();
553 		UINT64 resp_cookie = 0;
554 		IKE_CLIENT *c = NULL;
555 		IKE_CLIENT t;
556 
557 
558 		Copy(&t.ClientIP, &p->SrcIP, sizeof(IP));
559 		t.ClientPort = p->SrcPort;
560 		Copy(&t.ServerIP, &p->DstIP, sizeof(IP));
561 		t.ServerPort = p->DestPort;
562 		t.CurrentIkeSa = NULL;
563 
564 		if (p->DestPort == IPSEC_PORT_IPSEC_ESP_RAW)
565 		{
566 			t.ClientPort = t.ServerPort = IPSEC_PORT_IPSEC_ISAKMP;
567 		}
568 
569 		c = Search(ike->ClientList, &t);
570 
571 		if (c != NULL && c->CurrentIkeSa != NULL)
572 		{
573 			init_cookie = c->CurrentIkeSa->InitiatorCookie;
574 			resp_cookie = c->CurrentIkeSa->ResponderCookie;
575 		}
576 
577 		SendInformationalExchangePacketEx(ike, (c == NULL ? &t : c), IkeNewNoticeErrorInvalidSpiPayload(spi), false,
578 			init_cookie, resp_cookie);
579 
580 		SendDeleteIPsecSaPacket(ike, (c == NULL ? &t : c), spi);
581 		return;
582 	}
583 
584 	is_tunnel_mode = IsIPsecSaTunnelMode(ipsec_sa);
585 
586 	c = ipsec_sa->IkeClient;
587 	if (c == NULL)
588 	{
589 		return;
590 	}
591 
592 	block_size = ipsec_sa->TransformSetting.Crypto->BlockSize;
593 	hash_size = IKE_ESP_HASH_SIZE;
594 
595 	// Get the IV
596 	if (src_size < (sizeof(UINT) * 2 + block_size + hash_size + block_size))
597 	{
598 		return;
599 	}
600 	iv = src + sizeof(UINT) * 2;
601 
602 	// Get the hash
603 	hash = src + src_size - hash_size;
604 
605 	// Inspect the HMAC
606 	IkeHMac(ipsec_sa->TransformSetting.Hash, calced_hash, ipsec_sa->HashKey,
607 		ipsec_sa->TransformSetting.Hash->HashSize, src, src_size - hash_size);
608 
609 	if (Cmp(calced_hash, hash, hash_size) != 0)
610 	{
611 		//Debug("IPsec SA 0x%X: Invalid HMAC Value.\n", ipsec_sa->Spi);
612 		return;
613 	}
614 
615 	// Get the payload data
616 	encrypted_payload_data = src + sizeof(UINT) * 2 + block_size;
617 	size_of_payload_data = src_size - hash_size - block_size - sizeof(UINT) * 2;
618 	if (size_of_payload_data == 0 || (size_of_payload_data % block_size) != 0)
619 	{
620 		// Payload data don't exist or is not a multiple of block size
621 		return;
622 	}
623 
624 	// Decrypt the payload data
625 	cp.Key = ipsec_sa->CryptoKey;
626 	Copy(&cp.Iv, iv, block_size);
627 
628 	dec = IkeDecrypt(encrypted_payload_data, size_of_payload_data, &cp);
629 	if (dec != NULL)
630 	{
631 		UCHAR *dec_data = dec->Buf;
632 		UINT dec_size = dec->Size;
633 		UCHAR size_of_padding = dec_data[dec_size - 2];
634 		UCHAR next_header = dec_data[dec_size - 1];
635 		if ((dec_size - 2) >= size_of_padding)
636 		{
637 			UINT orig_size = dec_size - 2 - size_of_padding;
638 
639 			ipsec_sa->TotalSize += dec_size;
640 
641 			if (is_tunnel_mode)
642 			{
643 				// Tunnel Mode
644 				if (next_header == IKE_PROTOCOL_ID_IPV4 || next_header == IKE_PROTOCOL_ID_IPV6)
645 				{
646 					// Check the contents by parsing the IPv4 / IPv6 header in the case of tunnel mode
647 					BUF *b = NewBuf();
648 					static UCHAR src_mac_dummy[6] = {0, 0, 0, 0, 0, 0, };
649 					static UCHAR dst_mac_dummy[6] = {0, 0, 0, 0, 0, 0, };
650 					USHORT tpid = Endian16(next_header == IKE_PROTOCOL_ID_IPV4 ? MAC_PROTO_IPV4 : MAC_PROTO_IPV6);
651 					PKT *pkt;
652 
653 					WriteBuf(b, src_mac_dummy, sizeof(src_mac_dummy));
654 					WriteBuf(b, dst_mac_dummy, sizeof(dst_mac_dummy));
655 					WriteBuf(b, &tpid, sizeof(tpid));
656 
657 					WriteBuf(b, dec_data, dec_size);
658 
659 					// Parse
660 					pkt = ParsePacket(b->Buf, b->Size);
661 
662 #ifdef	RAW_DEBUG
663 					IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, b->Buf, b->Size);
664 #endif	// RAW_DEBUG
665 
666 					if (pkt == NULL)
667 					{
668 						// Parsing failure
669 						dec_data = NULL;
670 						dec_size = 0;
671 					}
672 					else
673 					{
674 						// Parsing success
675 						switch (pkt->TypeL3)
676 						{
677 						case L3_IPV4:
678 							// Save the internal IP address information
679 							UINTToIP(&c->TunnelModeServerIP, pkt->L3.IPv4Header->DstIP);
680 							UINTToIP(&c->TunnelModeClientIP, pkt->L3.IPv4Header->SrcIP);
681 
682 							if (IPV4_GET_OFFSET(pkt->L3.IPv4Header) == 0)
683 							{
684 								if ((IPV4_GET_FLAGS(pkt->L3.IPv4Header) & 0x01) == 0)
685 								{
686 									if (pkt->L3.IPv4Header->Protocol == IPSEC_IP_PROTO_ETHERIP)
687 									{
688 										// EtherIP
689 										if (ike->IPsec->Services.EtherIP_IPsec)
690 										{
691 											// An EtherIP packet has been received
692 											ProcIPsecEtherIPPacketRecv(ike, c, pkt->IPv4PayloadData, pkt->IPv4PayloadSize, true);
693 										}
694 									}
695 									else if (pkt->L3.IPv4Header->Protocol == IPSEC_IP_PROTO_L2TPV3)
696 									{
697 										// L2TPv3
698 										if (ike->IPsec->Services.EtherIP_IPsec)
699 										{
700 											// A L2TPv3 packet has been received
701 											ProcL2TPv3PacketRecv(ike, c, pkt->IPv4PayloadData, pkt->IPv4PayloadSize, true);
702 										}
703 									}
704 								}
705 							}
706 							break;
707 
708 						case L3_IPV6:
709 							// Save the internal IP address information
710 							SetIP6(&c->TunnelModeServerIP, pkt->IPv6HeaderPacketInfo.IPv6Header->DestAddress.Value);
711 							SetIP6(&c->TunnelModeClientIP, pkt->IPv6HeaderPacketInfo.IPv6Header->SrcAddress.Value);
712 
713 							if (pkt->IPv6HeaderPacketInfo.IsFragment == false)
714 							{
715 								if (pkt->IPv6HeaderPacketInfo.FragmentHeader == NULL || (IPV6_GET_FLAGS(pkt->IPv6HeaderPacketInfo.FragmentHeader) & IPV6_FRAGMENT_HEADER_FLAG_MORE_FRAGMENTS) == 0)
716 								{
717 									if (pkt->IPv6HeaderPacketInfo.Protocol == IPSEC_IP_PROTO_ETHERIP)
718 									{
719 										// EtherIP
720 										if (ike->IPsec->Services.EtherIP_IPsec)
721 										{
722 											// An EtherIP packet has been received
723 											ProcIPsecEtherIPPacketRecv(ike, c, pkt->IPv6HeaderPacketInfo.Payload, pkt->IPv6HeaderPacketInfo.PayloadSize, true);
724 										}
725 									}
726 									else if (pkt->IPv6HeaderPacketInfo.Protocol == IPSEC_IP_PROTO_L2TPV3)
727 									{
728 										// L2TPv3
729 										if (ike->IPsec->Services.EtherIP_IPsec)
730 										{
731 											// A L2TPv3 packet has been received
732 											ProcL2TPv3PacketRecv(ike, c, pkt->IPv6HeaderPacketInfo.Payload, pkt->IPv6HeaderPacketInfo.PayloadSize, true);
733 										}
734 									}
735 								}
736 							}
737 							break;
738 						}
739 
740 						FreePacket(pkt);
741 					}
742 
743 					FreeBuf(b);
744 				}
745 			}
746 			else
747 			{
748 				// Transport mode
749 				if (next_header == IP_PROTO_UDP)
750 				{
751 					if (ike->IPsec->Services.L2TP_IPsec || ike->IPsec->Services.EtherIP_IPsec)
752 					{
753 						// An UDP packet has been received
754 						ProcIPsecUdpPacketRecv(ike, c, dec_data, dec_size);
755 					}
756 				}
757 				else if (next_header == IPSEC_IP_PROTO_ETHERIP)
758 				{
759 					if (ike->IPsec->Services.EtherIP_IPsec)
760 					{
761 						// An EtherIP packet has been received
762 						ProcIPsecEtherIPPacketRecv(ike, c, dec_data, dec_size, false);
763 					}
764 				}
765 				else if (next_header == IPSEC_IP_PROTO_L2TPV3)
766 				{
767 					if (ike->IPsec->Services.EtherIP_IPsec)
768 					{
769 						// A L2TPv3 packet has been received
770 						ProcL2TPv3PacketRecv(ike, c, dec_data, dec_size, false);
771 					}
772 				}
773 			}
774 
775 			update_status = true;
776 		}
777 
778 		FreeBuf(dec);
779 	}
780 
781 	if (update_status)
782 	{
783 		bool start_qm = false;
784 		// Update the status of the client
785 		c->CurrentIpSecSaRecv = ipsec_sa;
786 		if (ipsec_sa->PairIPsecSa != NULL)
787 		{
788 			c->CurrentIpSecSaSend = ipsec_sa->PairIPsecSa;
789 
790 			if (p->DestPort == IPSEC_PORT_IPSEC_ESP_UDP)
791 			{
792 				IPSECSA *send_sa = c->CurrentIpSecSaSend;
793 				if (send_sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TUNNEL)
794 				{
795 					send_sa->TransformSetting.CapsuleMode = IKE_P2_CAPSULE_NAT_TUNNEL_1;
796 				}
797 				else if (send_sa->TransformSetting.CapsuleMode == IKE_P2_CAPSULE_TRANSPORT)
798 				{
799 					send_sa->TransformSetting.CapsuleMode = IKE_P2_CAPSULE_NAT_TRANSPORT_1;
800 				}
801 			}
802 		}
803 		c->LastCommTick = ike->Now;
804 		ipsec_sa->LastCommTick = ike->Now;
805 		if (ipsec_sa->PairIPsecSa != NULL)
806 		{
807 			ipsec_sa->PairIPsecSa->LastCommTick = ike->Now;
808 		}
809 
810 		SetIkeClientEndpoint(ike, c, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort);
811 
812 		if (seq >= 0xf0000000)
813 		{
814 			// Execute a QuickMode forcibly since sequence number is going to exhaust
815 			start_qm = true;
816 		}
817 
818 		if (ipsec_sa->TransformSetting.LifeKilobytes != 0)
819 		{
820 			UINT64 hard_size = (UINT64)ipsec_sa->TransformSetting.LifeKilobytes * (UINT64)1000;
821 			UINT64 soft_size = hard_size * (UINT64)2 / (UINT64)3;
822 
823 			if (ipsec_sa->TotalSize >= soft_size)
824 			{
825 				// Execute a QuickMode forcibly because the capacity limit is going to exceed
826 				start_qm = true;
827 			}
828 		}
829 
830 		if (start_qm)
831 		{
832 			if (ipsec_sa->StartQM_FlagSet == false)
833 			{
834 				c->StartQuickModeAsSoon = true;
835 				ipsec_sa->StartQM_FlagSet = true;
836 			}
837 		}
838 	}
839 }
840 
841 // Received the L2TPv3 packet via the IPsec tunnel
ProcL2TPv3PacketRecv(IKE_SERVER * ike,IKE_CLIENT * c,UCHAR * data,UINT data_size,bool is_tunnel_mode)842 void ProcL2TPv3PacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, bool is_tunnel_mode)
843 {
844 	UDPPACKET p;
845 	// Validate arguments
846 	if (ike == NULL || c == NULL || data == NULL || data_size == 0)
847 	{
848 		return;
849 	}
850 
851 	c->IsL2TPOnIPsecTunnelMode = is_tunnel_mode;
852 
853 	IPsecIkeClientManageL2TPServer(ike, c);
854 
855 	// Pass the received packet to the L2TP server
856 	p.Type = 0;
857 	p.Data = data;
858 	p.DestPort = IPSEC_PORT_L2TPV3_VIRTUAL;
859 	p.Size = data_size;
860 
861 	if (is_tunnel_mode)
862 	{
863 		Copy(&p.DstIP, &c->TunnelModeServerIP, sizeof(IP));
864 		Copy(&p.SrcIP, &c->TunnelModeClientIP, sizeof(IP));
865 	}
866 	else
867 	{
868 		Copy(&p.DstIP, &c->L2TPServerIP, sizeof(IP));
869 		Copy(&p.SrcIP, &c->L2TPClientIP, sizeof(IP));
870 	}
871 	p.SrcPort = IPSEC_PORT_L2TPV3_VIRTUAL;
872 
873 #ifdef	RAW_DEBUG
874 	IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, ((UCHAR *)p.Data) + 4, p.Size - 4);
875 #endif	// RAW_DEBUG
876 
877 	ProcL2TPPacketRecv(c->L2TP, &p);
878 }
879 
880 // An EtherIP packet has been received via an IPsec tunnel
ProcIPsecEtherIPPacketRecv(IKE_SERVER * ike,IKE_CLIENT * c,UCHAR * data,UINT data_size,bool is_tunnel_mode)881 void ProcIPsecEtherIPPacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size, bool is_tunnel_mode)
882 {
883 	BLOCK *b;
884 	// Validate arguments
885 	if (ike == NULL || c == NULL || data == NULL || data_size == 0)
886 	{
887 		return;
888 	}
889 
890 	c->IsEtherIPOnIPsecTunnelMode = is_tunnel_mode;
891 
892 	IPsecIkeClientManageEtherIPServer(ike, c);
893 
894 	b = NewBlock(data, data_size, 0);
895 
896 	EtherIPProcRecvPackets(c->EtherIP, b);
897 
898 	Free(b);
899 }
900 
901 // An UDP packet has been received via the IPsec tunnel
ProcIPsecUdpPacketRecv(IKE_SERVER * ike,IKE_CLIENT * c,UCHAR * data,UINT data_size)902 void ProcIPsecUdpPacketRecv(IKE_SERVER *ike, IKE_CLIENT *c, UCHAR *data, UINT data_size)
903 {
904 	UDP_HEADER *u;
905 	UINT payload_size;
906 	UINT src_port, dst_port;
907 	UINT packet_length;
908 	// Validate arguments
909 	if (ike == NULL || c == NULL || data == NULL || data_size == 0)
910 	{
911 		return;
912 	}
913 
914 	if (data_size <= sizeof(UDP_HEADER))
915 	{
916 		// There is no UDP header or the data is 0 bytes
917 		return;
918 	}
919 
920 	// UDP header
921 	u = (UDP_HEADER *)data;
922 
923 	packet_length = Endian16(u->PacketLength);
924 
925 	if (packet_length <= sizeof(UDP_HEADER))
926 	{
927 		return;
928 	}
929 
930 	payload_size = packet_length - sizeof(UDP_HEADER);
931 
932 	if (payload_size == 0)
933 	{
934 		// No data
935 		return;
936 	}
937 
938 	if (data_size < (sizeof(UDP_HEADER) + payload_size))
939 	{
940 		// Data is not followed
941 		return;
942 	}
943 
944 	src_port = Endian16(u->SrcPort);
945 	dst_port = Endian16(u->DstPort);
946 
947 	if (dst_port == IPSEC_PORT_L2TP)
948 	{
949 		UDPPACKET p;
950 		// A L2TP packet has been received
951 		IPsecIkeClientManageL2TPServer(ike, c);
952 
953 		// Update Port number
954 		c->L2TPClientPort = src_port;
955 
956 		// Pass the received packet to the L2TP server
957 		p.Type = 0;
958 		p.Data = data + sizeof(UDP_HEADER);
959 		p.DestPort = IPSEC_PORT_L2TP;
960 		Copy(&p.DstIP, &c->L2TPServerIP, sizeof(IP));
961 		p.Size = payload_size;
962 		Copy(&p.SrcIP, &c->L2TPClientIP, sizeof(IP));
963 		p.SrcPort = IPSEC_PORT_L2TP;
964 
965 		ProcL2TPPacketRecv(c->L2TP, &p);
966 
967 		//Debug("IPsec UDP Recv: %u <= %u %u\n", dst_port, src_port, p.Size);
968 
969 #ifdef	RAW_DEBUG
970 		IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, p.Data, p.Size);
971 #endif	// RAW_DEBUG
972 	}
973 }
974 
975 // Send a raw packet for debugging
IPsecIkeSendUdpForDebug(UINT dst_port,UINT dst_ip,void * data,UINT size)976 void IPsecIkeSendUdpForDebug(UINT dst_port, UINT dst_ip, void *data, UINT size)
977 {
978 	SOCK *s = NewUDP(0);
979 	IP d;
980 
981 	SetIP(&d, dst_ip, dst_ip, dst_ip, dst_ip);
982 
983 	SendTo(s, &d, dst_port, data, size);
984 
985 	ReleaseSock(s);
986 }
987 
988 // L2TP packet transmission (via IPsec SA tunnel)
IPsecIkeClientSendL2TPPackets(IKE_SERVER * ike,IKE_CLIENT * c,L2TP_SERVER * l2tp)989 void IPsecIkeClientSendL2TPPackets(IKE_SERVER *ike, IKE_CLIENT *c, L2TP_SERVER *l2tp)
990 {
991 	UINT i;
992 	// Validate arguments
993 	if (ike == NULL || c == NULL || l2tp == NULL)
994 	{
995 		return;
996 	}
997 
998 	for (i = 0;i < LIST_NUM(l2tp->SendPacketList);i++)
999 	{
1000 		UDPPACKET *u = LIST_DATA(l2tp->SendPacketList, i);
1001 
1002 		if (u->SrcPort != IPSEC_PORT_L2TPV3_VIRTUAL)
1003 		{
1004 			// L2TP UDP packet transmission
1005 			IPsecSendUdpPacket(ike, c, IPSEC_PORT_L2TP, c->L2TPClientPort,
1006 				u->Data, u->Size);
1007 		}
1008 		else
1009 		{
1010 			// L2TPv3 special IP packet transmission
1011 			IPsecSendPacketByIkeClient(ike, c, u->Data, u->Size, IPSEC_IP_PROTO_L2TPV3);
1012 
1013 #ifdef	RAW_DEBUG
1014 			IPsecIkeSendUdpForDebug(IPSEC_PORT_L2TP, 1, ((UCHAR *)u->Data) + 4, u->Size - 4);
1015 #endif	// RAW_DEBUG
1016 		}
1017 
1018 		FreeUdpPacket(u);
1019 	}
1020 
1021 	DeleteAll(l2tp->SendPacketList);
1022 }
1023 
1024 // Manage the L2TP server that is associated with the IKE_CLIENT
IPsecIkeClientManageL2TPServer(IKE_SERVER * ike,IKE_CLIENT * c)1025 void IPsecIkeClientManageL2TPServer(IKE_SERVER *ike, IKE_CLIENT *c)
1026 {
1027 	L2TP_SERVER *l2tp;
1028 	// Validate arguments
1029 	if (ike == NULL || c == NULL)
1030 	{
1031 		return;
1032 	}
1033 
1034 	if (c->L2TP == NULL)
1035 	{
1036 		UINT crypt_block_size = IKE_MAX_BLOCK_SIZE;
1037 
1038 		if (c->CurrentIpSecSaRecv != NULL)
1039 		{
1040 			crypt_block_size = c->CurrentIpSecSaRecv->TransformSetting.Crypto->BlockSize;
1041 		}
1042 
1043 		c->L2TP = NewL2TPServerEx(ike->Cedar, ike, IsIP6(&c->ClientIP), crypt_block_size);
1044 		c->L2TP->IkeClient = c;
1045 
1046 		Copy(&c->L2TPServerIP, &c->ServerIP, sizeof(IP));
1047 		Copy(&c->L2TPClientIP, &c->ClientIP, sizeof(IP));
1048 
1049 		if (c->CurrentIpSecSaRecv != NULL)
1050 		{
1051 			Format(c->L2TP->CryptName, sizeof(c->L2TP->CryptName),
1052 				"IPsec - %s (%u bits)",
1053 				c->CurrentIpSecSaRecv->TransformSetting.Crypto->Name,
1054 				c->CurrentIpSecSaRecv->TransformSetting.CryptoKeySize * 8);
1055 		}
1056 
1057 		Debug("IKE_CLIENT 0x%X: L2TP Server Started.\n", c);
1058 
1059 		IPsecLog(ike, c, NULL, NULL, "LI_L2TP_SERVER_STARTED");
1060 	}
1061 
1062 	l2tp = c->L2TP;
1063 
1064 	if (l2tp->Interrupts == NULL)
1065 	{
1066 		l2tp->Interrupts = ike->Interrupts;
1067 	}
1068 
1069 	if (l2tp->SockEvent == NULL)
1070 	{
1071 		SetL2TPServerSockEvent(l2tp, ike->SockEvent);
1072 	}
1073 
1074 	l2tp->Now = ike->Now;
1075 }
1076 
1077 // Manage the EtherIP server that is associated with the IKE_CLIENT
IPsecIkeClientManageEtherIPServer(IKE_SERVER * ike,IKE_CLIENT * c)1078 void IPsecIkeClientManageEtherIPServer(IKE_SERVER *ike, IKE_CLIENT *c)
1079 {
1080 	ETHERIP_SERVER *s;
1081 	// Validate arguments
1082 	if (ike == NULL || c == NULL)
1083 	{
1084 		return;
1085 	}
1086 
1087 	if (c->EtherIP == NULL)
1088 	{
1089 		char crypt_name[MAX_SIZE];
1090 		UINT crypt_block_size = IKE_MAX_BLOCK_SIZE;
1091 
1092 		Zero(crypt_name, sizeof(crypt_name));
1093 
1094 		if (c->CurrentIpSecSaRecv != NULL)
1095 		{
1096 			Format(crypt_name, sizeof(crypt_name),
1097 				"IPsec - %s (%u bits)",
1098 				c->CurrentIpSecSaRecv->TransformSetting.Crypto->Name,
1099 				c->CurrentIpSecSaRecv->TransformSetting.CryptoKeySize * 8);
1100 
1101 			crypt_block_size = c->CurrentIpSecSaRecv->TransformSetting.Crypto->BlockSize;
1102 		}
1103 
1104 		c->EtherIP = NewEtherIPServer(ike->Cedar, ike->IPsec, ike,
1105 			&c->ClientIP, c->ClientPort,
1106 			&c->ServerIP, c->ServerPort, crypt_name,
1107 			c->IsEtherIPOnIPsecTunnelMode, crypt_block_size, c->ClientId,
1108 			++ike->CurrentEtherId);
1109 
1110 		Debug("IKE_CLIENT 0x%X: EtherIP Server Started.\n", c);
1111 
1112 		IPsecLog(ike, c, NULL, NULL, NULL, "LI_ETHERIP_SERVER_STARTED", ike->CurrentEtherId);
1113 	}
1114 	else
1115 	{
1116 		StrCpy(c->EtherIP->ClientId, sizeof(c->EtherIP->ClientId), c->ClientId);
1117 	}
1118 
1119 	s = c->EtherIP;
1120 
1121 	if (s->Interrupts == NULL)
1122 	{
1123 		s->Interrupts = ike->Interrupts;
1124 	}
1125 
1126 	if (s->SockEvent == NULL)
1127 	{
1128 		SetEtherIPServerSockEvent(s, ike->SockEvent);
1129 	}
1130 
1131 	s->Now = ike->Now;
1132 }
1133 
1134 // EtherIP packet transmission (via IPsec SA tunnel)
IPsecIkeClientSendEtherIPPackets(IKE_SERVER * ike,IKE_CLIENT * c,ETHERIP_SERVER * s)1135 void IPsecIkeClientSendEtherIPPackets(IKE_SERVER *ike, IKE_CLIENT *c, ETHERIP_SERVER *s)
1136 {
1137 	UINT i;
1138 	// Validate arguments
1139 	if (ike == NULL || c == NULL || s == NULL)
1140 	{
1141 		return;
1142 	}
1143 
1144 	for (i = 0;i < LIST_NUM(s->SendPacketList);i++)
1145 	{
1146 		BLOCK *b = LIST_DATA(s->SendPacketList, i);
1147 
1148 		// Packet transmission
1149 		IPsecSendPacketByIkeClient(ike, c, b->Buf, b->Size, IPSEC_IP_PROTO_ETHERIP);
1150 
1151 		FreeBlock(b);
1152 	}
1153 
1154 	DeleteAll(s->SendPacketList);
1155 }
1156 
1157 // Handle the deletion payload
ProcDeletePayload(IKE_SERVER * ike,IKE_CLIENT * c,IKE_PACKET_DELETE_PAYLOAD * d)1158 void ProcDeletePayload(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_DELETE_PAYLOAD *d)
1159 {
1160 	// Validate arguments
1161 	if (ike == NULL || c == NULL || d == NULL)
1162 	{
1163 		return;
1164 	}
1165 
1166 	if (d->ProtocolId == IKE_PROTOCOL_ID_IPSEC_ESP)
1167 	{
1168 		UINT i;
1169 		// Remove the IPsec SA
1170 		for (i = 0;i < LIST_NUM(d->SpiList);i++)
1171 		{
1172 			BUF *b = LIST_DATA(d->SpiList, i);
1173 
1174 			if (b->Size == 4)
1175 			{
1176 				UINT spi = READ_UINT(b->Buf);
1177 				MarkIPsecSaAsDeleted(ike, SearchIPsecSaBySpi(ike, c, spi));
1178 			}
1179 		}
1180 	}
1181 	else if (d->ProtocolId == IKE_PROTOCOL_ID_IKE)
1182 	{
1183 		UINT i;
1184 		// Remove the IKE SA
1185 		for (i = 0;i < LIST_NUM(d->SpiList);i++)
1186 		{
1187 			BUF *b = LIST_DATA(d->SpiList, i);
1188 
1189 			if (b->Size == 16)
1190 			{
1191 				UINT64 v1 = READ_UINT64(((UCHAR *)b->Buf) + 0);
1192 				UINT64 v2 = READ_UINT64(((UCHAR *)b->Buf) + 8);
1193 
1194 				IKE_SA *sa = FindIkeSaByResponderCookie(ike, v2);
1195 
1196 				if (sa != NULL && sa->IkeClient == c)
1197 				{
1198 					MarkIkeSaAsDeleted(ike, sa);
1199 				}
1200 			}
1201 		}
1202 	}
1203 }
1204 
1205 // Mark the IKE_CLIENT for deletion
MarkIkeClientAsDeleted(IKE_SERVER * ike,IKE_CLIENT * c)1206 void MarkIkeClientAsDeleted(IKE_SERVER *ike, IKE_CLIENT *c)
1207 {
1208 	char client_ip_str[MAX_SIZE];
1209 	char server_ip_str[MAX_SIZE];
1210 	// Validate arguments
1211 	if (ike == NULL || c == NULL)
1212 	{
1213 		return;
1214 	}
1215 
1216 	if (c->Deleting)
1217 	{
1218 		return;
1219 	}
1220 
1221 	ike->StateHasChanged = true;
1222 
1223 	c->Deleting = true;
1224 
1225 	IPToStr(client_ip_str, sizeof(client_ip_str), &c->ClientIP);
1226 	IPToStr(server_ip_str, sizeof(server_ip_str), &c->ServerIP);
1227 
1228 	Debug("Deleting IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, c->ClientPort, server_ip_str, c->ServerPort);
1229 
1230 	IPsecLog(ike, c, NULL, NULL, "LI_DELETE_IKE_CLIENT");
1231 }
1232 
1233 // Mark the IKE SA for deletion
MarkIkeSaAsDeleted(IKE_SERVER * ike,IKE_SA * sa)1234 void MarkIkeSaAsDeleted(IKE_SERVER *ike, IKE_SA *sa)
1235 {
1236 	// Validate arguments
1237 	if (ike == NULL || sa == NULL)
1238 	{
1239 		return;
1240 	}
1241 
1242 	if (sa->Deleting)
1243 	{
1244 		return;
1245 	}
1246 
1247 	ike->StateHasChanged = true;
1248 
1249 	sa->Deleting = true;
1250 
1251 	Debug("IKE SA %I64u - %I64u has been marked as being deleted.\n", sa->InitiatorCookie, sa->ResponderCookie);
1252 
1253 	SendDeleteIkeSaPacket(ike, sa->IkeClient, sa->InitiatorCookie, sa->ResponderCookie);
1254 
1255 	IPsecLog(ike, NULL, sa, NULL, "LI_DELETE_IKE_SA");
1256 }
1257 
1258 // Mark the IPsec SA for deletion
MarkIPsecSaAsDeleted(IKE_SERVER * ike,IPSECSA * sa)1259 void MarkIPsecSaAsDeleted(IKE_SERVER *ike, IPSECSA *sa)
1260 {
1261 	// Validate arguments
1262 	if (ike == NULL || sa == NULL)
1263 	{
1264 		return;
1265 	}
1266 
1267 	if (sa->Deleting)
1268 	{
1269 		return;
1270 	}
1271 
1272 	ike->StateHasChanged = true;
1273 
1274 	sa->Deleting = true;
1275 
1276 	Debug("IPsec SA 0x%X has been marked as being deleted.\n", sa->Spi);
1277 
1278 	SendDeleteIPsecSaPacket(ike, sa->IkeClient, sa->Spi);
1279 
1280 	IPsecLog(ike, NULL, NULL, sa, "LI_DELETE_IPSEC_SA");
1281 }
1282 
1283 // IPsec SA Deletion packet transmission process
SendDeleteIPsecSaPacket(IKE_SERVER * ike,IKE_CLIENT * c,UINT spi)1284 void SendDeleteIPsecSaPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT spi)
1285 {
1286 	IKE_PACKET_PAYLOAD *payload;
1287 	BUF *buf;
1288 	// Validate arguments
1289 	if (ike == NULL || c == NULL || spi == 0)
1290 	{
1291 		return;
1292 	}
1293 
1294 	buf = NewBuf();
1295 	WriteBufInt(buf, spi);
1296 
1297 	payload = IkeNewDeletePayload(IKE_PROTOCOL_ID_IPSEC_ESP, NewListSingle(buf));
1298 
1299 	SendInformationalExchangePacket(ike, c, payload);
1300 }
1301 
1302 // IKE SA deletion packet transmission process
SendDeleteIkeSaPacket(IKE_SERVER * ike,IKE_CLIENT * c,UINT64 init_cookie,UINT64 resp_cookie)1303 void SendDeleteIkeSaPacket(IKE_SERVER *ike, IKE_CLIENT *c, UINT64 init_cookie, UINT64 resp_cookie)
1304 {
1305 	IKE_PACKET_PAYLOAD *payload;
1306 	BUF *buf;
1307 	// Validate arguments
1308 	if (ike == NULL || c == NULL)
1309 	{
1310 		return;
1311 	}
1312 
1313 	buf = NewBuf();
1314 	WriteBufInt64(buf, init_cookie);
1315 	WriteBufInt64(buf, resp_cookie);
1316 
1317 	payload = IkeNewDeletePayload(IKE_PROTOCOL_ID_IKE, NewListSingle(buf));
1318 
1319 	SendInformationalExchangePacket(ike, c, payload);
1320 }
1321 
1322 // Information exchange packet transmission process
SendInformationalExchangePacket(IKE_SERVER * ike,IKE_CLIENT * c,IKE_PACKET_PAYLOAD * payload)1323 void SendInformationalExchangePacket(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_PAYLOAD *payload)
1324 {
1325 	SendInformationalExchangePacketEx(ike, c, payload, false, 0, 0);
1326 }
SendInformationalExchangePacketEx(IKE_SERVER * ike,IKE_CLIENT * c,IKE_PACKET_PAYLOAD * payload,bool force_plain,UINT64 init_cookie,UINT64 resp_cookie)1327 void SendInformationalExchangePacketEx(IKE_SERVER *ike, IKE_CLIENT *c, IKE_PACKET_PAYLOAD *payload, bool force_plain, UINT64 init_cookie, UINT64 resp_cookie)
1328 {
1329 	IKE_SA *sa;
1330 	IKE_PACKET *ps;
1331 	LIST *payload_list;
1332 	UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
1333 	IKE_PACKET_PAYLOAD *hash_payload;
1334 	BUF *ps_buf;
1335 	UINT after_hash_offset, after_hash_size;
1336 	BUF *ps_buf_after_hash;
1337 	BUF *tmp_buf;
1338 	UCHAR hash[IKE_MAX_HASH_SIZE];
1339 	IKE_CRYPTO_PARAM cp;
1340 	bool plain = false;
1341 	// Validate arguments
1342 	if (ike == NULL || c == NULL || payload == NULL)
1343 	{
1344 		IkeFreePayload(payload);
1345 		return;
1346 	}
1347 
1348 	sa = c->CurrentIkeSa;
1349 	if (sa == NULL)
1350 	{
1351 		plain = true;
1352 	}
1353 
1354 	if (force_plain)
1355 	{
1356 		plain = true;
1357 	}
1358 
1359 	if (plain && (init_cookie == 0 && resp_cookie == 0))
1360 	{
1361 		init_cookie = Rand64();
1362 		resp_cookie = 0;
1363 	}
1364 
1365 	payload_list = NewListFast(NULL);
1366 
1367 	Zero(dummy_hash_data, sizeof(dummy_hash_data));
1368 
1369 	// Hash payload
1370 	if (plain == false)
1371 	{
1372 		hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, sa->HashSize);
1373 		Add(payload_list, hash_payload);
1374 	}
1375 
1376 	// Body
1377 	Add(payload_list, payload);
1378 
1379 	// Packet creation
1380 	ps = IkeNew((plain ? init_cookie : sa->InitiatorCookie), (plain ? resp_cookie : sa->ResponderCookie),
1381 		IKE_EXCHANGE_TYPE_INFORMATION, false, false, false,
1382 		GenerateNewMessageId(ike), payload_list);
1383 
1384 	if (plain == false)
1385 	{
1386 		// Build a temporary packet
1387 		ps_buf = IkeBuild(ps, NULL);
1388 
1389 		// Get the payload after the hash part
1390 		after_hash_offset = sizeof(IKE_HEADER) + hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
1391 		after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
1392 
1393 		ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
1394 		FreeBuf(ps_buf);
1395 
1396 		// Calculate the hash
1397 		tmp_buf = NewBuf();
1398 		WriteBufInt(tmp_buf, ps->MessageId);
1399 		WriteBufBuf(tmp_buf, ps_buf_after_hash);
1400 		IkeHMac(sa->TransformSetting.Hash, hash, sa->SKEYID_a, sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
1401 		FreeBuf(tmp_buf);
1402 
1403 		// Overwrite the hash
1404 		Copy(hash_payload->Payload.Hash.Data->Buf, hash, sa->HashSize);
1405 
1406 		ps->FlagEncrypted = true;
1407 		FreeBuf(ps_buf_after_hash);
1408 	}
1409 
1410 	// Packet reply
1411 	Zero(&cp, sizeof(cp));
1412 
1413 	if (plain == false)
1414 	{
1415 		cp.Key = sa->CryptoKey;
1416 		IkeCalcPhase2InitialIv(cp.Iv, sa, ps->MessageId);
1417 	}
1418 
1419 	ps_buf = IkeBuild(ps, &cp);
1420 
1421 	IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort,
1422 		&c->ClientIP, c->ClientPort,
1423 		ps_buf->Buf, ps_buf->Size);
1424 
1425 #ifdef	RAW_DEBUG
1426 	IkeDebugUdpSendRawPacket(ps);
1427 #endif	// RAW_DEBUG
1428 
1429 	Free(ps_buf);
1430 
1431 	IkeFree(ps);
1432 }
1433 
1434 // Information exchange packet reception process
ProcIkeInformationalExchangePacketRecv(IKE_SERVER * ike,UDPPACKET * p,IKE_PACKET * header)1435 void ProcIkeInformationalExchangePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
1436 {
1437 	IKE_CLIENT *c;
1438 	IKE_SA *ike_sa;
1439 	// Validate arguments
1440 	if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0 || header->ResponderCookie == 0
1441 		|| header->MessageId == 0 || header->FlagEncrypted == false)
1442 	{
1443 		return;
1444 	}
1445 
1446 	c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
1447 
1448 	if (c == NULL)
1449 	{
1450 		return;
1451 	}
1452 
1453 	ike_sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
1454 
1455 	if (ike_sa != NULL && ike_sa->Established)
1456 	{
1457 		IKE_PACKET *pr;
1458 		IKE_CRYPTO_PARAM cp;
1459 
1460 		// Packet decoding
1461 		Zero(&cp, sizeof(cp));
1462 		cp.Key = ike_sa->CryptoKey;
1463 		IkeCalcPhase2InitialIv(cp.Iv, ike_sa, header->MessageId);
1464 
1465 		pr = IkeParse(p->Data, p->Size, &cp);
1466 #ifdef	RAW_DEBUG
1467 		IkeDebugUdpSendRawPacket(pr);
1468 #endif	// RAW_DEBUG
1469 		if (pr != NULL)
1470 		{
1471 			// Get the hash payload
1472 			IKE_PACKET_PAYLOAD *hash_payload;
1473 
1474 			hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
1475 			if (hash_payload != NULL)
1476 			{
1477 				// Get the payload after the hash
1478 				UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
1479 				void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
1480 				if (pr->DecryptedPayload->Size > header_and_hash_size)
1481 				{
1482 					UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
1483 					UCHAR hash1[IKE_MAX_HASH_SIZE];
1484 					BUF *hash1_buf;
1485 
1486 					hash1_buf = NewBuf();
1487 					WriteBufInt(hash1_buf, header->MessageId);
1488 					WriteBuf(hash1_buf, after_hash_data, after_hash_size);
1489 
1490 					IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize,
1491 						hash1_buf->Buf, hash1_buf->Size);
1492 
1493 					// Compare the hash value
1494 					if (IkeCompareHash(hash_payload, hash1, ike_sa->HashSize))
1495 					{
1496 						UINT i, num;
1497 						// Handle the deletion payload
1498 						num = IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_DELETE);
1499 						for (i = 0;i < num;i++)
1500 						{
1501 							IKE_PACKET_PAYLOAD *payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_DELETE, i);
1502 							IKE_PACKET_DELETE_PAYLOAD *del = &payload->Payload.Delete;
1503 
1504 							ProcDeletePayload(ike, c, del);
1505 						}
1506 						num = IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NOTICE);
1507 						// Handle the notification payload
1508 						for (i = 0;i < num;i++)
1509 						{
1510 							IKE_PACKET_PAYLOAD *payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NOTICE, i);
1511 							IKE_PACKET_NOTICE_PAYLOAD *n = &payload->Payload.Notice;
1512 
1513 							if (n->MessageType == IKE_NOTICE_DPD_REQUEST || n->MessageType == IKE_NOTICE_DPD_RESPONSE)
1514 							{
1515 								if (n->MessageData != NULL && n->MessageData->Size == sizeof(UINT))
1516 								{
1517 									UINT seq_no = READ_UINT(n->MessageData->Buf);
1518 
1519 									if (n->Spi->Size == (sizeof(UINT64) * 2))
1520 									{
1521 										UINT64 init_cookie = READ_UINT64(((UCHAR *)n->Spi->Buf));
1522 										UINT64 resp_cookie = READ_UINT64(((UCHAR *)n->Spi->Buf) + sizeof(UINT64));
1523 
1524 										if (init_cookie != 0 && resp_cookie != 0)
1525 										{
1526 											IKE_SA *found_ike_sa = SearchIkeSaByCookie(ike, init_cookie, resp_cookie);
1527 
1528 											if (found_ike_sa != NULL && found_ike_sa->IkeClient == c)
1529 											{
1530 												if (n->MessageType == IKE_NOTICE_DPD_REQUEST)
1531 												{
1532 													// Return the DPD Response (ACK) for the DPD Request
1533 													SendInformationalExchangePacket(ike, c,
1534 														IkeNewNoticeDpdPayload(true, init_cookie, resp_cookie,
1535 														seq_no));
1536 												}
1537 
1538 												// Update the status of the IKE SA
1539 												found_ike_sa->LastCommTick = ike->Now;
1540 												ike_sa->LastCommTick = ike->Now;
1541 												found_ike_sa->IkeClient->LastCommTick = ike->Now;
1542 												ike_sa->IkeClient->LastCommTick = ike->Now;
1543 												ike_sa->IkeClient->CurrentIkeSa = ike_sa;
1544 											}
1545 										}
1546 									}
1547 								}
1548 							}
1549 						}
1550 					}
1551 
1552 					FreeBuf(hash1_buf);
1553 				}
1554 			}
1555 
1556 			IkeFree(pr);
1557 		}
1558 	}
1559 }
1560 
1561 // Create a new message ID
GenerateNewMessageId(IKE_SERVER * ike)1562 UINT GenerateNewMessageId(IKE_SERVER *ike)
1563 {
1564 	UINT ret;
1565 	// Validate arguments
1566 	if (ike == NULL)
1567 	{
1568 		return 0;
1569 	}
1570 
1571 	while (true)
1572 	{
1573 		ret = Rand32();
1574 
1575 		if (ret != 0 && ret != 0xffffffff)
1576 		{
1577 			UINT i;
1578 			bool ok = true;
1579 
1580 			for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
1581 			{
1582 				IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
1583 
1584 				if (sa->MessageId == ret)
1585 				{
1586 					ok = false;
1587 					break;
1588 				}
1589 			}
1590 
1591 			if (ok)
1592 			{
1593 				return ret;
1594 			}
1595 		}
1596 	}
1597 }
1598 
1599 // Start the quick mode
StartQuickMode(IKE_SERVER * ike,IKE_CLIENT * c)1600 void StartQuickMode(IKE_SERVER *ike, IKE_CLIENT *c)
1601 {
1602 	IPSEC_SA_TRANSFORM_SETTING setting;
1603 	IKE_SA *ike_sa;
1604 	UINT message_id;
1605 	UCHAR iv[IKE_MAX_BLOCK_SIZE];
1606 	// Validate arguments
1607 	if (ike == NULL || c == NULL)
1608 	{
1609 		return;
1610 	}
1611 
1612 	if (IsZero(&c->CachedTransformSetting, sizeof(IPSEC_SA_TRANSFORM_SETTING)))
1613 	{
1614 		// Cached transform setting does not exist
1615 		Debug("Error: c->CachedTransformSetting is not existing.\n");
1616 		return;
1617 	}
1618 
1619 	ike_sa = c->CurrentIkeSa;
1620 	if (ike_sa == NULL)
1621 	{
1622 		return;
1623 	}
1624 
1625 	IPsecLog(ike, NULL, ike_sa, NULL, "LI_START_QM_FROM_SERVER");
1626 
1627 	Copy(&setting, &c->CachedTransformSetting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
1628 
1629 	message_id = GenerateNewMessageId(ike);
1630 
1631 	IkeCalcPhase2InitialIv(iv, ike_sa, message_id);
1632 
1633 #ifdef	FORCE_LIFETIME_QM
1634 	setting.LifeSeconds = FORCE_LIFETIME_QM;
1635 #endif	// FORCE_LIFETIME_QM
1636 
1637 	if (true)
1638 	{
1639 		IKE_PACKET *ps;
1640 		LIST *payload_list;
1641 		IKE_PACKET_PAYLOAD *send_hash_payload;
1642 		IKE_PACKET_PAYLOAD *send_sa_payload;
1643 		IKE_PACKET_PAYLOAD *send_proposal_payload;
1644 		IKE_PACKET_PAYLOAD *send_transform_payload;
1645 		IKE_PACKET_PAYLOAD *send_rand_payload;
1646 		IKE_PACKET_PAYLOAD *send_key_payload = NULL;
1647 		IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
1648 		UINT shared_key_size = 0;
1649 		UCHAR *shared_key = NULL;
1650 		BUF *initiator_rand;
1651 		IPSECSA *ipsec_sa_s_c, *ipsec_sa_c_s;
1652 		BUF *ps_buf;
1653 		UINT after_hash_offset, after_hash_size;
1654 		BUF *ps_buf_after_hash;
1655 		BUF *tmp_buf;
1656 		UINT spi;
1657 		UINT spi_be;
1658 		UCHAR hash1[IKE_MAX_HASH_SIZE];
1659 		UCHAR zero = 0;
1660 		DH_CTX *dh = NULL;
1661 		UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
1662 
1663 		initiator_rand = RandBuf(IKE_SA_RAND_SIZE);
1664 
1665 		if (setting.Dh != NULL)
1666 		{
1667 			// Generate DH
1668 			dh = IkeDhNewCtx(setting.Dh);
1669 
1670 			if (dh != NULL)
1671 			{
1672 				send_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE,
1673 					dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
1674 			}
1675 		}
1676 
1677 		Zero(dummy_hash_data, sizeof(dummy_hash_data));
1678 
1679 		// Dummy hash value
1680 		payload_list = NewListFast(NULL);
1681 		send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, ike_sa->HashSize);
1682 		Add(payload_list, send_hash_payload);
1683 
1684 		// Determine the SPI
1685 		spi = GenerateNewIPsecSaSpi(ike, 0);
1686 		spi_be = Endian32(spi);
1687 
1688 		// SA
1689 		send_transform_payload = TransformSettingToTransformPayloadForIPsec(ike, &setting);
1690 		send_proposal_payload = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IPSEC_ESP, &spi_be, sizeof(spi_be),
1691 			NewListSingle(send_transform_payload));
1692 		send_sa_payload = IkeNewSaPayload(NewListSingle(send_proposal_payload));
1693 		Add(payload_list, send_sa_payload);
1694 
1695 		// Random number
1696 		send_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, initiator_rand->Buf, initiator_rand->Size);
1697 		Add(payload_list, send_rand_payload);
1698 
1699 		// Key exchange
1700 		if (send_key_payload != NULL)
1701 		{
1702 			Add(payload_list, send_key_payload);
1703 		}
1704 
1705 		if (c->SendID1andID2)
1706 		{
1707 			// Add the ID payload
1708 			if (setting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_1 || setting.CapsuleMode == IKE_P2_CAPSULE_NAT_TUNNEL_2)
1709 			{
1710 				UCHAR zero[32];
1711 
1712 				Zero(zero, sizeof(zero));
1713 
1714 				// Tunnel Mode
1715 				send_id_1 = IkeNewIdPayload((IsIP4(&c->ServerIP) ? IKE_ID_IPV4_ADDR_SUBNET : IKE_ID_IPV6_ADDR_SUBNET),
1716 					0, 0,
1717 					zero, (IsIP4(&c->ServerIP) ? 8 : 32));
1718 
1719 				send_id_2 = IkeNewIdPayload(c->SendID1_Type,
1720 					c->SendID1_Protocol, c->SendID1_Port,
1721 					c->SendID1_Buf->Buf, c->SendID1_Buf->Size);
1722 			}
1723 			else
1724 			{
1725 				// Transport mode
1726 				// Specify in the reverse order in which the client has been specified
1727 				send_id_2 = IkeNewIdPayload(c->SendID1_Type,
1728 					c->SendID1_Protocol, c->SendID1_Port,
1729 					c->SendID1_Buf->Buf, c->SendID1_Buf->Size);
1730 
1731 				send_id_1 = IkeNewIdPayload(c->SendID2_Type,
1732 					c->SendID2_Protocol, c->SendID2_Port,
1733 					c->SendID2_Buf->Buf, c->SendID2_Buf->Size);
1734 			}
1735 
1736 			Add(payload_list, send_id_1);
1737 			Add(payload_list, send_id_2);
1738 		}
1739 
1740 		if (true)
1741 		{
1742 			// NAT-OA payload
1743 			if (c->SendNatOaDraft1)
1744 			{
1745 				Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT, &c->ServerIP));
1746 			}
1747 
1748 			if (c->SendNatOaDraft2)
1749 			{
1750 				Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT_2, &c->ServerIP));
1751 			}
1752 
1753 			if (c->SendNatOaRfc)
1754 			{
1755 				Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ClientIP));
1756 				Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ServerIP));
1757 			}
1758 		}
1759 
1760 		// Build a packet
1761 		ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie, IKE_EXCHANGE_TYPE_QUICK,
1762 			false, false, false, message_id, payload_list);
1763 
1764 		// Build a temporary packet
1765 		ps_buf = IkeBuild(ps, NULL);
1766 
1767 		// Get the payload after the hash part
1768 		after_hash_offset = sizeof(IKE_HEADER) + send_hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
1769 		after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
1770 
1771 		ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
1772 		FreeBuf(ps_buf);
1773 
1774 		// Calculate the hash #1
1775 		tmp_buf = NewBuf();
1776 		WriteBufInt(tmp_buf, message_id);
1777 		WriteBufBuf(tmp_buf, ps_buf_after_hash);
1778 		IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
1779 		FreeBuf(tmp_buf);
1780 
1781 		// Overwrite hash #1
1782 		Copy(send_hash_payload->Payload.Hash.Data->Buf, hash1, ike_sa->HashSize);
1783 
1784 		// Create an IPsec SA
1785 		ipsec_sa_c_s = NewIPsecSa(ike, c, ike_sa, true, message_id, false, iv, spi,
1786 			initiator_rand->Buf, initiator_rand->Size, NULL, 0,
1787 			&setting, shared_key, shared_key_size);
1788 
1789 		ipsec_sa_s_c = NewIPsecSa(ike, c, ike_sa, true, message_id, true, iv, 0,
1790 			initiator_rand->Buf, initiator_rand->Size, NULL, 0,
1791 			&setting, shared_key, shared_key_size);
1792 
1793 		ipsec_sa_c_s->PairIPsecSa = ipsec_sa_s_c;
1794 		ipsec_sa_s_c->PairIPsecSa = ipsec_sa_c_s;
1795 
1796 		ipsec_sa_s_c->Dh = dh;
1797 
1798 		Insert(ike->IPsecSaList, ipsec_sa_c_s);
1799 		Insert(ike->IPsecSaList, ipsec_sa_s_c);
1800 
1801 		// Packet transmission
1802 		ps->FlagEncrypted = true;
1803 		IPsecSaSendPacket(ike, ipsec_sa_s_c, ps);
1804 		ipsec_sa_s_c->NumResends = 3;
1805 #ifdef	RAW_DEBUG
1806 		IkeDebugUdpSendRawPacket(ps);
1807 #endif	// RAW_DEBUG
1808 
1809 		IkeFree(ps);
1810 		Free(shared_key);
1811 		FreeBuf(ps_buf_after_hash);
1812 		FreeBuf(initiator_rand);
1813 	}
1814 }
1815 
1816 // Process the quick mode received packet
ProcIkeQuickModePacketRecv(IKE_SERVER * ike,UDPPACKET * p,IKE_PACKET * header)1817 void ProcIkeQuickModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
1818 {
1819 	IKE_CLIENT *c;
1820 	IKE_SA *ike_sa;
1821 	// Validate arguments
1822 	if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0 || header->ResponderCookie == 0
1823 		|| header->MessageId == 0 || header->FlagEncrypted == false)
1824 	{
1825 		return;
1826 	}
1827 
1828 	c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
1829 
1830 	if (c == NULL)
1831 	{
1832 		return;
1833 	}
1834 
1835 	ike_sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
1836 
1837 	if (ike_sa == NULL)
1838 	{
1839 		// IKE SA does not exist
1840 		SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
1841 			header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
1842 	}
1843 
1844 	if (ike_sa != NULL && ike_sa->Established)
1845 	{
1846 		// Update the status of the IKE SA
1847 		ike_sa->LastCommTick = ike->Now;
1848 		ike_sa->IkeClient->LastCommTick = ike->Now;
1849 		ike_sa->IkeClient->CurrentIkeSa = ike_sa;
1850 
1851 		// Search whether the Message ID is already in the database
1852 		if (SearchIPsecSaByMessageId(ike, c, header->MessageId) == NULL)
1853 		{
1854 			IKE_PACKET *pr;
1855 			IKE_CRYPTO_PARAM cp;
1856 
1857 			// Message ID does not exist. Start a new Quick Mode session
1858 			Zero(&cp, sizeof(cp));
1859 			cp.Key = ike_sa->CryptoKey;
1860 			IkeCalcPhase2InitialIv(cp.Iv, ike_sa, header->MessageId);
1861 
1862 			pr = IkeParse(p->Data, p->Size, &cp);
1863 #ifdef	RAW_DEBUG
1864 			IkeDebugUdpSendRawPacket(pr);
1865 #endif	// RAW_DEBUG
1866 			if (pr != NULL)
1867 			{
1868 				// Get the hash payload
1869 				IKE_PACKET_PAYLOAD *hash_payload;
1870 
1871 				hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
1872 				if (hash_payload != NULL)
1873 				{
1874 					// Get the payload after the hash
1875 					UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
1876 					void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
1877 					if (pr->DecryptedPayload->Size > header_and_hash_size)
1878 					{
1879 						UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
1880 						UCHAR hash1[IKE_MAX_HASH_SIZE];
1881 						BUF *hash1_buf;
1882 
1883 						hash1_buf = NewBuf();
1884 						WriteBufInt(hash1_buf, header->MessageId);
1885 						WriteBuf(hash1_buf, after_hash_data, after_hash_size);
1886 
1887 						IkeHMac(ike_sa->TransformSetting.Hash, hash1, ike_sa->SKEYID_a, ike_sa->HashSize,
1888 							hash1_buf->Buf, hash1_buf->Size);
1889 
1890 						// Compare the hash value
1891 						if (IkeCompareHash(hash_payload, hash1, ike_sa->HashSize))
1892 						{
1893 							IKE_PACKET_PAYLOAD *sa_payload, *rand_payload, *key_payload, *id_payload_1, *id_payload_2;
1894 
1895 							// Get the payload of other
1896 							sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
1897 							rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
1898 							key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
1899 							id_payload_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
1900 							id_payload_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 1);
1901 
1902 							if (sa_payload != NULL && rand_payload != NULL)
1903 							{
1904 								IPSEC_SA_TRANSFORM_SETTING setting;
1905 
1906 								Zero(&setting, sizeof(setting));
1907 
1908 								// Interpret the SA payload
1909 								if (GetBestTransformSettingForIPsecSa(ike, pr, &setting, &p->DstIP) && (GetNumberOfIPsecSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
1910 								{
1911 									// Appropriate transform setting is selected
1912 									Debug("P2 Transform: %s %s %s(%u) %u %u\n",
1913 										(setting.Dh == NULL ? NULL : setting.Dh->Name), setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
1914 										setting.LifeKilobytes, setting.LifeSeconds);
1915 
1916 #ifdef	FORCE_LIFETIME_QM
1917 									setting.LifeSeconds = FORCE_LIFETIME_QM;
1918 #endif	// FORCE_LIFETIME_QM
1919 
1920 									// Cache the transform attribute value
1921 									Copy(&c->CachedTransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
1922 
1923 									// Check the key exchange payload if the PFS is specified
1924 									if (setting.Dh == NULL || (setting.Dh != NULL && key_payload != NULL &&
1925 										key_payload->Payload.KeyExchange.Data->Size <= setting.Dh->KeySize))
1926 									{
1927 										// Create a payload for response
1928 										IKE_PACKET *ps;
1929 										LIST *payload_list;
1930 										IKE_PACKET_PAYLOAD *send_hash_payload;
1931 										IKE_PACKET_PAYLOAD *send_sa_payload;
1932 										IKE_PACKET_PAYLOAD *send_proposal_payload;
1933 										IKE_PACKET_PAYLOAD *send_transform_payload;
1934 										IKE_PACKET_PAYLOAD *send_rand_payload;
1935 										IKE_PACKET_PAYLOAD *send_key_payload = NULL;
1936 										IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
1937 										UCHAR dummy_hash_data[IKE_MAX_HASH_SIZE];
1938 										DH_CTX *dh = NULL;
1939 										UINT shared_key_size = 0;
1940 										UCHAR *shared_key = NULL;
1941 										BUF *initiator_rand, *responder_rand;
1942 										IPSECSA *ipsec_sa_s_c, *ipsec_sa_c_s;
1943 										BUF *ps_buf;
1944 										UINT after_hash_offset, after_hash_size;
1945 										BUF *ps_buf_after_hash;
1946 										BUF *tmp_buf;
1947 										UINT spi;
1948 										UINT spi_be;
1949 										UCHAR hash2[IKE_MAX_HASH_SIZE];
1950 										UCHAR hash3[IKE_MAX_HASH_SIZE];
1951 										UCHAR zero = 0;
1952 
1953 										IPsecLog(ike, NULL, ike_sa, NULL, "LI_START_QM_FROM_CLIENT");
1954 
1955 										initiator_rand = CloneBuf(rand_payload->Payload.Rand.Data);
1956 										responder_rand = RandBuf(IKE_SA_RAND_SIZE);
1957 
1958 										if (setting.Dh != NULL)
1959 										{
1960 											// Calculate DH
1961 											dh = IkeDhNewCtx(setting.Dh);
1962 											shared_key_size = (dh == NULL ? 0 : dh->Size);
1963 											shared_key = ZeroMalloc(shared_key_size);
1964 
1965 											if (DhCompute(dh, shared_key, key_payload->Payload.KeyExchange.Data->Buf, key_payload->Payload.KeyExchange.Data->Size))
1966 											{
1967 												// DH calculation success
1968 												Debug("P2 DH Ok.\n");
1969 
1970 												send_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE,
1971 													dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
1972 
1973 												IkeDhFreeCtx(dh);
1974 											}
1975 											else
1976 											{
1977 												// DH calculation failure
1978 												Debug("P2 DhCompute failed.\n");
1979 
1980 												shared_key = NULL;
1981 												Free(shared_key);
1982 												shared_key_size = 0;
1983 
1984 												IPsecLog(ike, NULL, ike_sa, NULL, "LI_QM_DH_ERROR");
1985 											}
1986 										}
1987 
1988 										Zero(dummy_hash_data, sizeof(dummy_hash_data));
1989 
1990 										// Dummy hash value
1991 										payload_list = NewListFast(NULL);
1992 										send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, dummy_hash_data, ike_sa->HashSize);
1993 										Add(payload_list, send_hash_payload);
1994 
1995 										// Determine the SPI
1996 										spi = GenerateNewIPsecSaSpi(ike, setting.SpiServerToClient);
1997 										spi_be = Endian32(spi);
1998 
1999 										// SA
2000 										send_transform_payload = TransformSettingToTransformPayloadForIPsec(ike, &setting);
2001 										send_proposal_payload = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IPSEC_ESP, &spi_be, sizeof(spi_be),
2002 											NewListSingle(send_transform_payload));
2003 										send_sa_payload = IkeNewSaPayload(NewListSingle(send_proposal_payload));
2004 										Add(payload_list, send_sa_payload);
2005 
2006 										// Random number
2007 										send_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, responder_rand->Buf, responder_rand->Size);
2008 										Add(payload_list, send_rand_payload);
2009 
2010 										// Key exchange
2011 										if (send_key_payload != NULL)
2012 										{
2013 											Add(payload_list, send_key_payload);
2014 										}
2015 
2016 										// ID
2017 										if (id_payload_1 != NULL && id_payload_2 != NULL)
2018 										{
2019 											send_id_1 = IkeNewIdPayload(id_payload_1->Payload.Id.Type,
2020 												id_payload_1->Payload.Id.ProtocolId, id_payload_1->Payload.Id.Port,
2021 												id_payload_1->Payload.Id.IdData->Buf, id_payload_1->Payload.Id.IdData->Size);
2022 
2023 											send_id_2 = IkeNewIdPayload(id_payload_2->Payload.Id.Type,
2024 												id_payload_2->Payload.Id.ProtocolId, id_payload_2->Payload.Id.Port,
2025 												id_payload_2->Payload.Id.IdData->Buf, id_payload_2->Payload.Id.IdData->Size);
2026 
2027 											Add(payload_list, send_id_1);
2028 											Add(payload_list, send_id_2);
2029 
2030 											if (c->SendID1_Buf != NULL)
2031 											{
2032 												FreeBuf(c->SendID1_Buf);
2033 											}
2034 
2035 											if (c->SendID2_Buf != NULL)
2036 											{
2037 												FreeBuf(c->SendID2_Buf);
2038 											}
2039 
2040 											c->SendID1_Type = id_payload_1->Payload.Id.Type;
2041 											c->SendID1_Protocol = id_payload_1->Payload.Id.ProtocolId;
2042 											c->SendID1_Port = id_payload_1->Payload.Id.Port;
2043 											c->SendID1_Buf = CloneBuf(id_payload_1->Payload.Id.IdData);
2044 
2045 											c->SendID2_Type = id_payload_2->Payload.Id.Type;
2046 											c->SendID2_Protocol = id_payload_2->Payload.Id.ProtocolId;
2047 											c->SendID2_Port = id_payload_2->Payload.Id.Port;
2048 											c->SendID2_Buf = CloneBuf(id_payload_2->Payload.Id.IdData);
2049 
2050 											c->SendID1andID2 = true;
2051 										}
2052 										else
2053 										{
2054 											c->SendID1andID2 = false;
2055 										}
2056 
2057 										if (true)
2058 										{
2059 											// Reply if NAT-OA payload is presented by the client
2060 											IKE_PACKET_PAYLOAD *nat_oa_draft1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA_DRAFT, 0);
2061 											IKE_PACKET_PAYLOAD *nat_oa_draft2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA_DRAFT_2, 0);
2062 											IKE_PACKET_PAYLOAD *nat_oa_rfc_0 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA, 0);
2063 											IKE_PACKET_PAYLOAD *nat_oa_rfc_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_OA, 1);
2064 
2065 											c->SendNatOaDraft1 = c->SendNatOaDraft2 = c->SendNatOaRfc = false;
2066 
2067 											c->ShouldCalcChecksumForUDP = false;
2068 
2069 											if (nat_oa_draft1 != NULL)
2070 											{
2071 												Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT, &c->ServerIP));
2072 												c->SendNatOaDraft1 = true;
2073 
2074 												if (IsIP4(&nat_oa_draft1->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
2075 												{
2076 													Copy(&c->TransportModeClientIP, &nat_oa_draft1->Payload.NatOa.IpAddress, sizeof(IP));
2077 													Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
2078 
2079 													c->ShouldCalcChecksumForUDP = true;
2080 												}
2081 											}
2082 
2083 											if (nat_oa_draft2 != NULL)
2084 											{
2085 												Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA_DRAFT_2, &c->ServerIP));
2086 												c->SendNatOaDraft2 = true;
2087 
2088 												if (IsIP4(&nat_oa_draft2->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
2089 												{
2090 													Copy(&c->TransportModeClientIP, &nat_oa_draft2->Payload.NatOa.IpAddress, sizeof(IP));
2091 													Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
2092 
2093 													c->ShouldCalcChecksumForUDP = true;
2094 												}
2095 											}
2096 
2097 											if (nat_oa_rfc_0 != NULL && nat_oa_rfc_1 != NULL)
2098 											{
2099 												Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ClientIP));
2100 												Add(payload_list, IkeNewNatOaPayload(IKE_PAYLOAD_NAT_OA, &c->ServerIP));
2101 												c->SendNatOaRfc = true;
2102 
2103 												if (IsIP4(&nat_oa_rfc_0->Payload.NatOa.IpAddress) == IsIP4(&c->ServerIP))
2104 												{
2105 													Copy(&c->TransportModeClientIP, &nat_oa_rfc_0->Payload.NatOa.IpAddress, sizeof(IP));
2106 													Copy(&c->TransportModeServerIP, &c->ServerIP, sizeof(IP));
2107 
2108 													c->ShouldCalcChecksumForUDP = true;
2109 												}
2110 											}
2111 										}
2112 
2113 										// Build a packet
2114 										ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie, IKE_EXCHANGE_TYPE_QUICK,
2115 											false, false, false, header->MessageId, payload_list);
2116 
2117 										// Build a temporary packet
2118 										ps_buf = IkeBuild(ps, NULL);
2119 
2120 										// Get the payload after the hash part
2121 										after_hash_offset = sizeof(IKE_HEADER) + send_hash_payload->BitArray->Size + sizeof(IKE_COMMON_HEADER);
2122 										after_hash_size = ((ps_buf->Size > after_hash_offset) ? (ps_buf->Size - after_hash_offset) : 0);
2123 
2124 										ps_buf_after_hash = MemToBuf(((UCHAR *)ps_buf->Buf) + after_hash_offset, after_hash_size);
2125 										FreeBuf(ps_buf);
2126 
2127 										// Calculate the hash #2
2128 										tmp_buf = NewBuf();
2129 										WriteBufInt(tmp_buf, header->MessageId);
2130 										WriteBufBuf(tmp_buf, initiator_rand);
2131 										WriteBufBuf(tmp_buf, ps_buf_after_hash);
2132 										IkeHMac(ike_sa->TransformSetting.Hash, hash2, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
2133 										FreeBuf(tmp_buf);
2134 
2135 										// Calculate the hash #3
2136 										tmp_buf = NewBuf();
2137 										WriteBuf(tmp_buf, &zero, 1);
2138 										WriteBufInt(tmp_buf, header->MessageId);
2139 										WriteBufBuf(tmp_buf, initiator_rand);
2140 										WriteBufBuf(tmp_buf, responder_rand);
2141 										IkeHMac(ike_sa->TransformSetting.Hash, hash3, ike_sa->SKEYID_a, ike_sa->HashSize, tmp_buf->Buf, tmp_buf->Size);
2142 										FreeBuf(tmp_buf);
2143 
2144 										// Create an IPsec SA
2145 										ipsec_sa_c_s = NewIPsecSa(ike, c, ike_sa, false, header->MessageId, false, cp.NextIv, spi,
2146 											initiator_rand->Buf, initiator_rand->Size, responder_rand->Buf, responder_rand->Size,
2147 											&setting, shared_key, shared_key_size);
2148 										ipsec_sa_s_c = NewIPsecSa(ike, c, ike_sa, false, header->MessageId, true, cp.NextIv, setting.SpiServerToClient,
2149 											initiator_rand->Buf, initiator_rand->Size, responder_rand->Buf, responder_rand->Size,
2150 											&setting, shared_key, shared_key_size);
2151 
2152 										ipsec_sa_c_s->PairIPsecSa = ipsec_sa_s_c;
2153 										ipsec_sa_s_c->PairIPsecSa = ipsec_sa_c_s;
2154 
2155 										Insert(ike->IPsecSaList, ipsec_sa_c_s);
2156 										Insert(ike->IPsecSaList, ipsec_sa_s_c);
2157 
2158 										Copy(ipsec_sa_c_s->Hash3, hash3, ike_sa->HashSize);
2159 
2160 										// Overwrite hash #2
2161 										Copy(send_hash_payload->Payload.Hash.Data->Buf, hash2, ike_sa->HashSize);
2162 
2163 										// Packet reply
2164 										ps->FlagEncrypted = true;
2165 										IPsecSaSendPacket(ike, ipsec_sa_s_c, ps);
2166 										IkeSaSendPacket(ike, ike_sa, NULL);
2167 
2168 #ifdef	RAW_DEBUG
2169 										IkeDebugUdpSendRawPacket(ps);
2170 #endif	// RAW_DEBUG
2171 
2172 										IkeFree(ps);
2173 										Free(shared_key);
2174 										FreeBuf(ps_buf_after_hash);
2175 										FreeBuf(initiator_rand);
2176 										FreeBuf(responder_rand);
2177 									}
2178 								}
2179 								else
2180 								{
2181 									// No appropriate transform setting
2182 									Debug("No Appropriate Transform was Found.\n");
2183 
2184 									IPsecLog(ike, NULL, ike_sa, NULL, "LI_IPSEC_NO_TRANSFORM");
2185 
2186 									SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(true, header->InitiatorCookie, header->ResponderCookie));
2187 								}
2188 							}
2189 						}
2190 						else
2191 						{
2192 							Debug("QM-1: Hash 1 is invalid.\n");
2193 						}
2194 
2195 						FreeBuf(hash1_buf);
2196 					}
2197 				}
2198 
2199 				IkeFree(pr);
2200 			}
2201 		}
2202 		else
2203 		{
2204 			// Get the IPsec SA
2205 			IPSECSA *ipsec_sa_cs = SearchIPsecSaByMessageId(ike, c, header->MessageId);
2206 			if (ipsec_sa_cs != NULL)
2207 			{
2208 				IPSECSA *ipsec_sa_sc = ipsec_sa_cs->PairIPsecSa;
2209 				if (ipsec_sa_sc != NULL)
2210 				{
2211 					if (ipsec_sa_sc->Established == false && ipsec_sa_cs->Established == false)
2212 					{
2213 						IKE_PACKET *pr = IPsecSaRecvPacket(ike, ipsec_sa_cs, p->Data, p->Size);
2214 
2215 #ifdef	RAW_DEBUG
2216 						IkeDebugUdpSendRawPacket(pr);
2217 #endif	// RAW_DEBUG
2218 
2219 						if (pr != NULL)
2220 						{
2221 							if (ipsec_sa_cs->Initiated == false)
2222 							{
2223 								// Initiator is client-side
2224 								// Check hash3 payload
2225 								IKE_PACKET_PAYLOAD *hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
2226 
2227 								if (hash_payload != NULL)
2228 								{
2229 									BUF *hash_buf = hash_payload->Payload.Hash.Data;
2230 									if (hash_buf != NULL)
2231 									{
2232 										if (hash_buf->Size == ipsec_sa_cs->IkeSa->HashSize)
2233 										{
2234 											if (Cmp(hash_buf->Buf, ipsec_sa_cs->Hash3, hash_buf->Size) == 0)
2235 											{
2236 												ipsec_sa_cs->Established = ipsec_sa_sc->Established = true;
2237 												ipsec_sa_cs->EstablishedTick = ipsec_sa_sc->EstablishedTick = ike->Now;
2238 												ipsec_sa_cs->LastCommTick = ipsec_sa_sc->LastCommTick = ike->Now;
2239 
2240 												c->CurrentIpSecSaRecv = ipsec_sa_cs;
2241 												c->CurrentIpSecSaSend = ipsec_sa_sc;
2242 
2243 												Debug("IPsec SA 0x%X & 0x%X Established.\n",
2244 													ipsec_sa_cs->Spi,
2245 													ipsec_sa_sc->Spi);
2246 
2247 												IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_ESTABLISHED");
2248 
2249 												IPsecSaSendPacket(ike, ipsec_sa_sc, NULL);
2250 											}
2251 											else
2252 											{
2253 												Debug("QM-3: Hash 3 is invalid.\n");
2254 											}
2255 										}
2256 									}
2257 								}
2258 							}
2259 							else
2260 							{
2261 								// Initiator is server-side
2262 								// Get hash payload
2263 								IKE_PACKET_PAYLOAD *hash_payload;
2264 
2265 								hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
2266 								if (hash_payload != NULL && ipsec_sa_sc->InitiatorRand != NULL)
2267 								{
2268 									// Get the payload after the hash
2269 									UINT header_and_hash_size = sizeof(IKE_COMMON_HEADER) + hash_payload->BitArray->Size;
2270 									void *after_hash_data = ((UCHAR *)pr->DecryptedPayload->Buf) + header_and_hash_size;
2271 									if (pr->DecryptedPayload->Size > header_and_hash_size)
2272 									{
2273 										UINT after_hash_size = pr->DecryptedPayload->Size - header_and_hash_size;
2274 										UCHAR hash2[IKE_MAX_HASH_SIZE];
2275 										BUF *hash2_buf;
2276 
2277 										hash2_buf = NewBuf();
2278 										WriteBufInt(hash2_buf, header->MessageId);
2279 										WriteBufBuf(hash2_buf, ipsec_sa_sc->InitiatorRand);
2280 										WriteBuf(hash2_buf, after_hash_data, after_hash_size);
2281 
2282 										IkeHMac(ipsec_sa_sc->SKEYID_Hash, hash2, ipsec_sa_sc->SKEYID_a, ipsec_sa_sc->SKEYID_Hash->HashSize,
2283 											hash2_buf->Buf, hash2_buf->Size);
2284 
2285 										FreeBuf(hash2_buf);
2286 
2287 										// Compare the hash value
2288 										if (IkeCompareHash(hash_payload, hash2, ike_sa->HashSize))
2289 										{
2290 											IKE_PACKET_PAYLOAD *sa_payload, *rand_payload, *key_payload, *id_payload_1, *id_payload_2;
2291 
2292 											// Get the payload of other
2293 											sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
2294 											rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
2295 											key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
2296 											id_payload_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
2297 											id_payload_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 1);
2298 
2299 											if (sa_payload != NULL && rand_payload != NULL)
2300 											{
2301 												IPSEC_SA_TRANSFORM_SETTING setting;
2302 
2303 												// Interpret the SA payload
2304 												if (GetBestTransformSettingForIPsecSa(ike, pr, &setting, &p->DstIP))
2305 												{
2306 													// Appropriate transform setting is selected
2307 													Debug("P2 Transform: %s %s %s(%u) %u %u\n",
2308 														(setting.Dh == NULL ? NULL : setting.Dh->Name), setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
2309 														setting.LifeKilobytes, setting.LifeSeconds);
2310 
2311 #ifdef	FORCE_LIFETIME_QM
2312 													setting.LifeSeconds = FORCE_LIFETIME_QM;
2313 #endif	// FORCE_LIFETIME_QM
2314 
2315 													// Check the key exchange payload if the PFS is specified
2316 													if (setting.Dh == NULL || (setting.Dh != NULL && key_payload != NULL && ipsec_sa_sc->Dh != NULL &&
2317 														key_payload->Payload.KeyExchange.Data->Size <= setting.Dh->KeySize))
2318 													{
2319 														IKE_PACKET *ps;
2320 														LIST *payload_list;
2321 														IKE_PACKET_PAYLOAD *send_hash_payload;
2322 														IKE_PACKET_PAYLOAD *send_key_payload = NULL;
2323 														IKE_PACKET_PAYLOAD *send_id_1 = NULL, *send_id_2 = NULL;
2324 														DH_CTX *dh = NULL;
2325 														UINT shared_key_size = 0;
2326 														UCHAR *shared_key = NULL;
2327 														BUF *initiator_rand, *responder_rand;
2328 														BUF *tmp_buf;
2329 														UCHAR hash3[IKE_MAX_HASH_SIZE];
2330 														char tmp[MAX_SIZE];
2331 														UCHAR zero = 0;
2332 
2333 														initiator_rand = ipsec_sa_sc->InitiatorRand;
2334 														responder_rand = CloneBuf(rand_payload->Payload.Rand.Data);
2335 
2336 														if (setting.Dh != NULL)
2337 														{
2338 															// Calculate DH
2339 															DH_CTX *dh = ipsec_sa_sc->Dh;
2340 
2341 															shared_key_size = (dh == NULL ? 0 : dh->Size);
2342 															shared_key = ZeroMalloc(shared_key_size);
2343 
2344 															if (DhCompute(dh, shared_key, key_payload->Payload.KeyExchange.Data->Buf, key_payload->Payload.KeyExchange.Data->Size))
2345 															{
2346 																// DH calculation success
2347 																Debug("P2 DH Ok.\n");
2348 															}
2349 															else
2350 															{
2351 																// DH calculation failure
2352 																Debug("P2 DhCompute failed.\n");
2353 
2354 																shared_key = NULL;
2355 																Free(shared_key);
2356 																shared_key_size = 0;
2357 
2358 																IPsecLog(ike, NULL, ike_sa, NULL, "LI_QM_DH_ERROR");
2359 															}
2360 														}
2361 
2362 														// Update the information of IPsec SA
2363 														if (shared_key != NULL)
2364 														{
2365 															ipsec_sa_sc->SharedKey = NewBuf(shared_key, shared_key_size);
2366 															ipsec_sa_cs->SharedKey = NewBuf(shared_key, shared_key_size);
2367 														}
2368 
2369 														ipsec_sa_sc->Spi = setting.SpiServerToClient;
2370 														IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_SPI_SET", ipsec_sa_sc->Spi);
2371 														ike->IPsecSaList->sorted = false;
2372 
2373 														ipsec_sa_sc->ResponderRand = CloneBuf(responder_rand);
2374 														ipsec_sa_cs->ResponderRand = CloneBuf(responder_rand);
2375 
2376 														Copy(&ipsec_sa_sc->TransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
2377 														Copy(&ipsec_sa_cs->TransformSetting, &setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
2378 
2379 														ipsec_sa_sc->Established = true;
2380 														ipsec_sa_cs->Established = true;
2381 
2382 														IPsecLog(ike, NULL, NULL, ipsec_sa_sc, "LI_IPSEC_SA_ESTABLISHED");
2383 
2384 														ipsec_sa_sc->LastCommTick = ike->Now;
2385 														ipsec_sa_cs->LastCommTick = ike->Now;
2386 
2387 														c->CurrentIpSecSaRecv = ipsec_sa_cs;
2388 														c->CurrentIpSecSaSend = ipsec_sa_sc;
2389 
2390 														// Calculate the KEYMAT
2391 														IPsecCalcKeymat(ike, ipsec_sa_sc->SKEYID_Hash, ipsec_sa_sc->KeyMat, sizeof(ipsec_sa_sc->KeyMat),
2392 															ipsec_sa_sc->SKEYID_d, ipsec_sa_sc->SKEYID_Hash->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP,
2393 															ipsec_sa_sc->Spi, initiator_rand->Buf, initiator_rand->Size,
2394 															responder_rand->Buf, responder_rand->Size,
2395 															shared_key, shared_key_size);
2396 
2397 														IPsecCalcKeymat(ike, ipsec_sa_cs->SKEYID_Hash, ipsec_sa_cs->KeyMat, sizeof(ipsec_sa_cs->KeyMat),
2398 															ipsec_sa_cs->SKEYID_d, ipsec_sa_cs->SKEYID_Hash->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP,
2399 															ipsec_sa_cs->Spi, initiator_rand->Buf, initiator_rand->Size,
2400 															responder_rand->Buf, responder_rand->Size,
2401 															shared_key, shared_key_size);
2402 
2403 														IkeFreeKey(ipsec_sa_sc->CryptoKey);
2404 														IkeFreeKey(ipsec_sa_cs->CryptoKey);
2405 
2406 														ipsec_sa_sc->CryptoKey = IkeNewKey(setting.Crypto, ipsec_sa_sc->KeyMat, setting.CryptoKeySize);
2407 														ipsec_sa_cs->CryptoKey = IkeNewKey(setting.Crypto, ipsec_sa_cs->KeyMat, setting.CryptoKeySize);
2408 
2409 														Copy(ipsec_sa_sc->HashKey, ipsec_sa_sc->KeyMat + setting.CryptoKeySize, setting.Hash->HashSize);
2410 														Copy(ipsec_sa_cs->HashKey, ipsec_sa_cs->KeyMat + setting.CryptoKeySize, setting.Hash->HashSize);
2411 
2412 														BinToStrEx(tmp, sizeof(tmp), ipsec_sa_sc->KeyMat, ipsec_sa_sc->TransformSetting.CryptoKeySize);
2413 														Debug("  KEYMAT (SC): %s\n", tmp);
2414 
2415 														BinToStrEx(tmp, sizeof(tmp), ipsec_sa_cs->KeyMat, ipsec_sa_cs->TransformSetting.CryptoKeySize);
2416 														Debug("  KEYMAT (CS): %s\n", tmp);
2417 
2418 														Debug("IPsec SA 0x%X & 0x%X Established (Server is Initiator).\n",
2419 															ipsec_sa_cs->Spi,
2420 															ipsec_sa_sc->Spi);
2421 
2422 														// Calculate the hash #3
2423 														tmp_buf = NewBuf();
2424 														WriteBuf(tmp_buf, &zero, 1);
2425 														WriteBufInt(tmp_buf, header->MessageId);
2426 														WriteBufBuf(tmp_buf, initiator_rand);
2427 														WriteBufBuf(tmp_buf, responder_rand);
2428 														IkeHMac(ipsec_sa_cs->SKEYID_Hash, hash3, ipsec_sa_cs->SKEYID_a, ipsec_sa_cs->SKEYID_Hash->HashSize, tmp_buf->Buf, tmp_buf->Size);
2429 														FreeBuf(tmp_buf);
2430 
2431 														// Return the hash #3
2432 														send_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, hash3, ipsec_sa_cs->SKEYID_Hash->HashSize);
2433 
2434 														payload_list = NewListSingle(send_hash_payload);
2435 														ps = IkeNew(ike_sa->InitiatorCookie, ike_sa->ResponderCookie,
2436 															IKE_EXCHANGE_TYPE_QUICK, true, false, false, header->MessageId, payload_list);
2437 
2438 														IPsecSaSendPacket(ike, ipsec_sa_sc, ps);
2439 #ifdef	RAW_DEBUG
2440 														IkeDebugUdpSendRawPacket(ps);
2441 #endif	// RAW_DEBUG
2442 														ipsec_sa_sc->NumResends = 3;
2443 
2444 														if (false)
2445 														{
2446 															UINT i;
2447 
2448 															for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
2449 															{
2450 																IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
2451 
2452 																if (sa != ipsec_sa_sc && sa != ipsec_sa_cs)
2453 																{
2454 																	MarkIPsecSaAsDeleted(ike, sa);
2455 																}
2456 															}
2457 														}
2458 
2459 														IkeFree(ps);
2460 
2461 														// Release the memory
2462 														FreeBuf(responder_rand);
2463 													}
2464 												}
2465 												else
2466 												{
2467 													// No appropriate transform setting
2468 													Debug("No Appropriate Transform was Found.\n");
2469 
2470 													IPsecLog(ike, NULL, ike_sa, NULL, "LI_IPSEC_NO_TRANSFORM");
2471 
2472 													SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(true, header->InitiatorCookie, header->ResponderCookie));
2473 												}
2474 											}
2475 										}
2476 									}
2477 								}
2478 							}
2479 							IkeFree(pr);
2480 						}
2481 					}
2482 				}
2483 			}
2484 		}
2485 	}
2486 }
2487 
2488 // Calculate the KEYMAT
IPsecCalcKeymat(IKE_SERVER * ike,IKE_HASH * h,void * dst,UINT dst_size,void * skeyid_d_data,UINT skeyid_d_size,UCHAR protocol,UINT spi,void * rand_init_data,UINT rand_init_size,void * rand_resp_data,UINT rand_resp_size,void * df_key_data,UINT df_key_size)2489 void IPsecCalcKeymat(IKE_SERVER *ike, IKE_HASH *h, void *dst, UINT dst_size, void *skeyid_d_data, UINT skeyid_d_size, UCHAR protocol, UINT spi, void *rand_init_data, UINT rand_init_size,
2490 					 void *rand_resp_data, UINT rand_resp_size, void *df_key_data, UINT df_key_size)
2491 {
2492 	BUF *k;
2493 	BUF *ret;
2494 	// Validate arguments
2495 	if (ike == NULL || dst == NULL || h == NULL || rand_init_data == NULL || rand_resp_data == NULL||
2496 		(df_key_size != 0 && df_key_data == NULL))
2497 	{
2498 		return;
2499 	}
2500 
2501 	ret = NewBuf();
2502 
2503 	k = NULL;
2504 
2505 	while (true)
2506 	{
2507 		BUF *tmp = NewBuf();
2508 		UCHAR hash[IKE_MAX_HASH_SIZE];
2509 
2510 		if (k != NULL)
2511 		{
2512 			WriteBufBuf(tmp, k);
2513 		}
2514 
2515 		if (df_key_data != NULL)
2516 		{
2517 			WriteBuf(tmp, df_key_data, df_key_size);
2518 		}
2519 
2520 		WriteBuf(tmp, &protocol, 1);
2521 
2522 		WriteBufInt(tmp, spi);
2523 
2524 		WriteBuf(tmp, rand_init_data, rand_init_size);
2525 		WriteBuf(tmp, rand_resp_data, rand_resp_size);
2526 
2527 		if (k != NULL)
2528 		{
2529 			FreeBuf(k);
2530 		}
2531 
2532 		IkeHMac(h, hash, skeyid_d_data, skeyid_d_size, tmp->Buf, tmp->Size);
2533 
2534 		FreeBuf(tmp);
2535 
2536 		k = MemToBuf(hash, h->HashSize);
2537 
2538 		WriteBufBuf(ret, k);
2539 
2540 		if (ret->Size >= dst_size)
2541 		{
2542 			break;
2543 		}
2544 	}
2545 
2546 	Copy(dst, ret->Buf, dst_size);
2547 
2548 	FreeBuf(ret);
2549 	FreeBuf(k);
2550 }
2551 
2552 // Search for IPsec SA from Message ID
SearchIPsecSaByMessageId(IKE_SERVER * ike,IKE_CLIENT * c,UINT message_id)2553 IPSECSA *SearchIPsecSaByMessageId(IKE_SERVER *ike, IKE_CLIENT *c, UINT message_id)
2554 {
2555 	UINT i;
2556 	// Validate arguments
2557 	if (ike == NULL || c == NULL || message_id == 0)
2558 	{
2559 		return NULL;
2560 	}
2561 
2562 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
2563 	{
2564 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
2565 
2566 		if (sa->IkeClient == c)
2567 		{
2568 			if (sa->MessageId == message_id)
2569 			{
2570 				if (sa->ServerToClient == false)
2571 				{
2572 					if (sa->Established == false)
2573 					{
2574 						return sa;
2575 					}
2576 				}
2577 			}
2578 		}
2579 	}
2580 
2581 	return NULL;
2582 }
2583 
2584 // Search for IPsec SA from SPI value
SearchClientToServerIPsecSaBySpi(IKE_SERVER * ike,UINT spi)2585 IPSECSA *SearchClientToServerIPsecSaBySpi(IKE_SERVER *ike, UINT spi)
2586 {
2587 	IPSECSA t;
2588 	// Validate arguments
2589 	if (ike == NULL || spi == 0)
2590 	{
2591 		return NULL;
2592 	}
2593 
2594 	t.ServerToClient = false;
2595 	t.Spi = spi;
2596 
2597 	return Search(ike->IPsecSaList, &t);
2598 }
SearchIPsecSaBySpi(IKE_SERVER * ike,IKE_CLIENT * c,UINT spi)2599 IPSECSA *SearchIPsecSaBySpi(IKE_SERVER *ike, IKE_CLIENT *c, UINT spi)
2600 {
2601 	UINT i;
2602 	// Validate arguments
2603 	if (ike == NULL || c == NULL || spi == 0)
2604 	{
2605 		return NULL;
2606 	}
2607 
2608 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
2609 	{
2610 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
2611 
2612 		if (sa->Spi == spi)
2613 		{
2614 			if (sa->IkeClient == c)
2615 			{
2616 				return sa;
2617 			}
2618 		}
2619 	}
2620 
2621 	return NULL;
2622 }
2623 
2624 // Search an IKE SA from the value of the Cookie
SearchIkeSaByCookie(IKE_SERVER * ike,UINT64 init_cookie,UINT64 resp_cookie)2625 IKE_SA *SearchIkeSaByCookie(IKE_SERVER *ike, UINT64 init_cookie, UINT64 resp_cookie)
2626 {
2627 	UINT i;
2628 	// Validate arguments
2629 	if (ike == NULL)
2630 	{
2631 		return NULL;
2632 	}
2633 
2634 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
2635 	{
2636 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
2637 
2638 		if (sa->InitiatorCookie == init_cookie && sa->ResponderCookie == resp_cookie)
2639 		{
2640 			return sa;
2641 		}
2642 	}
2643 
2644 	return NULL;
2645 }
2646 
2647 // Generate the SPI value of new IPsec SA
GenerateNewIPsecSaSpi(IKE_SERVER * ike,UINT counterpart_spi)2648 UINT GenerateNewIPsecSaSpi(IKE_SERVER *ike, UINT counterpart_spi)
2649 {
2650 	UINT ret;
2651 	// Validate arguments
2652 	if (ike == NULL)
2653 	{
2654 		return 0;
2655 	}
2656 
2657 	while (true)
2658 	{
2659 		ret = Rand32();
2660 
2661 		if (ret != counterpart_spi)
2662 		{
2663 			if (ret >= 4096 && ret != INFINITE)
2664 			{
2665 				if (SearchClientToServerIPsecSaBySpi(ike, ret) == NULL)
2666 				{
2667 					return ret;
2668 				}
2669 			}
2670 		}
2671 	}
2672 }
2673 
2674 // Calculate the initial IV for Phase 2
IkeCalcPhase2InitialIv(void * iv,IKE_SA * sa,UINT message_id)2675 void IkeCalcPhase2InitialIv(void *iv, IKE_SA *sa, UINT message_id)
2676 {
2677 	BUF *b;
2678 	UCHAR hash[IKE_MAX_HASH_SIZE];
2679 	// Validate arguments
2680 	if (iv == NULL || sa == NULL)
2681 	{
2682 		return;
2683 	}
2684 
2685 	message_id = Endian32(message_id);
2686 
2687 	b = NewBuf();
2688 	WriteBuf(b, sa->Iv, sa->BlockSize);
2689 	WriteBuf(b, &message_id, sizeof(UINT));
2690 
2691 	IkeHash(sa->TransformSetting.Hash, hash, b->Buf, b->Size);
2692 
2693 	Copy(iv, hash, sa->TransformSetting.Crypto->BlockSize);
2694 
2695 	FreeBuf(b);
2696 }
2697 
2698 // Create a new IPsec SA
NewIPsecSa(IKE_SERVER * ike,IKE_CLIENT * c,IKE_SA * ike_sa,bool initiate,UINT message_id,bool server_to_client,void * iv,UINT spi,void * init_rand_data,UINT init_rand_size,void * res_rand_data,UINT res_rand_size,IPSEC_SA_TRANSFORM_SETTING * setting,void * shared_key_data,UINT shared_key_size)2699 IPSECSA *NewIPsecSa(IKE_SERVER *ike, IKE_CLIENT *c, IKE_SA *ike_sa, bool initiate, UINT message_id, bool server_to_client, void *iv, UINT spi, void *init_rand_data, UINT init_rand_size, void *res_rand_data, UINT res_rand_size, IPSEC_SA_TRANSFORM_SETTING *setting, void *shared_key_data, UINT shared_key_size)
2700 {
2701 	IPSECSA *sa;
2702 	char tmp[MAX_SIZE];
2703 	UINT total_key_size;
2704 	// Validate arguments
2705 	if (ike == NULL || c == NULL || ike_sa == NULL || message_id == 0 || iv == NULL || setting == NULL ||
2706 		(shared_key_data == NULL && shared_key_size != 0))
2707 	{
2708 		return NULL;
2709 	}
2710 
2711 	sa = ZeroMalloc(sizeof(IPSECSA));
2712 
2713 	if (server_to_client == false)
2714 	{
2715 		ike->CurrentIPsecSaId++;
2716 	}
2717 	sa->Id = ike->CurrentIPsecSaId;
2718 
2719 	sa->IkeClient = c;
2720 	sa->IkeSa = ike_sa;
2721 
2722 	sa->MessageId = message_id;
2723 	sa->FirstCommTick = ike->Now;
2724 	sa->LastCommTick = ike->Now;
2725 	sa->Initiated = initiate;
2726 
2727 	sa->ServerToClient = server_to_client;
2728 
2729 	sa->Spi = spi;
2730 
2731 	sa->SKEYID_Hash = ike_sa->TransformSetting.Hash;
2732 	Copy(sa->SKEYID_a, ike_sa->SKEYID_a, sa->SKEYID_Hash->HashSize);
2733 	Copy(sa->SKEYID_d, ike_sa->SKEYID_d, sa->SKEYID_Hash->HashSize);
2734 
2735 	sa->InitiatorRand = MemToBuf(init_rand_data, init_rand_size);
2736 
2737 	if (initiate == false)
2738 	{
2739 		sa->ResponderRand = MemToBuf(res_rand_data, res_rand_size);
2740 	}
2741 
2742 	Copy(sa->Iv, iv, ike_sa->BlockSize);
2743 
2744 	Copy(&sa->TransformSetting, setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
2745 
2746 	if (shared_key_data != NULL)
2747 	{
2748 		sa->SharedKey = MemToBuf(shared_key_data, shared_key_size);
2749 	}
2750 
2751 	total_key_size = sa->TransformSetting.CryptoKeySize + sa->TransformSetting.Hash->HashSize;
2752 
2753 	if (initiate == false)
2754 	{
2755 		IPsecCalcKeymat(ike, ike_sa->TransformSetting.Hash, sa->KeyMat, total_key_size,
2756 			ike_sa->SKEYID_d, ike_sa->HashSize, IKE_PROTOCOL_ID_IPSEC_ESP, spi, sa->InitiatorRand->Buf,
2757 			sa->InitiatorRand->Size, sa->ResponderRand->Buf, sa->ResponderRand->Size,
2758 			shared_key_data, shared_key_size);
2759 
2760 		sa->CryptoKey = IkeNewKey(sa->TransformSetting.Crypto, sa->KeyMat, sa->TransformSetting.CryptoKeySize);
2761 
2762 		Copy(sa->HashKey, sa->KeyMat + sa->TransformSetting.CryptoKeySize, sa->TransformSetting.Hash->HashSize);
2763 	}
2764 
2765 	Debug("New IPsec SA (StoC = %u): 0x%X 0x%X (%s %s %s(%u) %u %u)\n",
2766 		sa->ServerToClient,
2767 		sa->MessageId,
2768 		sa->Spi,
2769 		(setting->Dh == NULL ? NULL : setting->Dh->Name), setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize,
2770 		setting->LifeKilobytes, setting->LifeSeconds);
2771 
2772 	IPsecLog(ike, c, NULL, sa, "LI_NEW_IPSEC_SA",
2773 		(sa->ServerToClient ? _UU("LI_TAG_SERVER_TO_CLIENT") : _UU("LI_TAG_CLIENT_TO_SERVER")),
2774 		sa->Spi,
2775 		(setting->Dh == NULL ? NULL : setting->Dh->Name), setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize * 8,
2776 		setting->LifeKilobytes, setting->LifeSeconds);
2777 
2778 	Rand(sa->EspIv, sizeof(sa->EspIv));
2779 
2780 	if (initiate == false)
2781 	{
2782 		BinToStrEx(tmp, sizeof(tmp), sa->KeyMat, sa->TransformSetting.CryptoKeySize);
2783 		Debug("  KEYMAT: %s\n", tmp);
2784 	}
2785 
2786 	// Set the expiration time
2787 	if (setting->LifeSeconds != 0)
2788 	{
2789 		UINT64 span = (UINT64)((UINT64)setting->LifeSeconds * (UINT64)1000) + (UINT64)IKE_SOFT_EXPIRES_MARGIN;
2790 		sa->ExpiresHardTick = ike->Now + span;
2791 		sa->ExpiresSoftTick = ike->Now + span;
2792 		//sa->ExpiresSoftTick = ike->Now + (UINT64)5000;
2793 
2794 		AddInterrupt(ike->Interrupts, sa->ExpiresSoftTick);
2795 	}
2796 
2797 	return sa;
2798 }
2799 
2800 // Treat aggressive mode packet reception
ProcIkeAggressiveModePacketRecv(IKE_SERVER * ike,UDPPACKET * p,IKE_PACKET * header)2801 void ProcIkeAggressiveModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
2802 {
2803 	IKE_CLIENT *c;
2804 	char tmp[MAX_SIZE];
2805 	// Validate arguments
2806 	if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0)
2807 	{
2808 		return;
2809 	}
2810 
2811 	c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
2812 
2813 	if (c == NULL)
2814 	{
2815 		return;
2816 	}
2817 
2818 	if (header->ResponderCookie == 0)
2819 	{
2820 		// Start process of the state 1
2821 		IKE_CAPS caps;
2822 		IKE_SA *sa;
2823 		IKE_PACKET *pr = IkeParse(p->Data, p->Size, NULL);
2824 
2825 		if (pr != NULL)
2826 		{
2827 			// Determine the CAPS
2828 			IkeCheckCaps(&caps, pr);
2829 			if (caps.MS_L2TPIPSecVPNClient || caps.MS_NT5_ISAKMP_OAKLEY || caps.MS_Vid_InitialContact)
2830 			{
2831 				c->IsMicrosoft = true;
2832 			}
2833 
2834 			if ((caps.NatTraversalDraftIetf || caps.NatTraversalRfc3947) || (IsUdpPortOpened(ike->IPsec->UdpListener, &p->DstIP, IPSEC_PORT_IPSEC_ESP_RAW)))
2835 			{
2836 				sa = FindIkeSaByEndPointAndInitiatorCookie(ike, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, header->InitiatorCookie, IKE_SA_AGRESSIVE_MODE);
2837 
2838 				if (sa == NULL)
2839 				{
2840 					// Check whether there is acceptable SA parameters by analyzing proposed parameters
2841 					IKE_SA_TRANSFORM_SETTING setting;
2842 
2843 					if (GetBestTransformSettingForIkeSa(ike, pr, &setting) && (GetNumberOfIkeSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
2844 					{
2845 						IKE_PACKET_PAYLOAD *tp;
2846 						IKE_PACKET_PAYLOAD *pp;
2847 						IKE_PACKET_PAYLOAD *sap;
2848 						IKE_PACKET_PAYLOAD *client_sa_payload;
2849 						IKE_PACKET_PAYLOAD *your_key_payload;
2850 						IKE_PACKET_PAYLOAD *your_rand_payload;
2851 						IKE_PACKET_PAYLOAD *your_id_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
2852 
2853 						// Appropriate transform setting is selected
2854 						Debug("P1 Transform: %s %s %s(%u) %u %u\n",
2855 							setting.Dh->Name, setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
2856 							setting.LifeKilobytes, setting.LifeSeconds);
2857 
2858 						// Receive a key exchange packet
2859 						your_key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
2860 						your_rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
2861 						if (your_key_payload != NULL && your_rand_payload != NULL && your_id_payload != NULL)
2862 						{
2863 							// Check the key payload
2864 							BUF *your_key_buf = your_key_payload->Payload.KeyExchange.Data;
2865 							BUF *your_rand_buf = your_rand_payload->Payload.Rand.Data;
2866 
2867 							// DH generation
2868 							DH_CTX *dh = IkeDhNewCtx(setting.Dh);
2869 							UINT shared_key_size = (dh == NULL ? 0 : dh->Size);
2870 							UCHAR *shared_key = ZeroMalloc(shared_key_size);
2871 
2872 							// DH calculation
2873 							if (DhCompute(dh, shared_key, your_key_buf->Buf, your_key_buf->Size))
2874 							{
2875 								IKE_PACKET *ps;
2876 								LIST *payload_list;
2877 								IKE_PACKET_PAYLOAD *my_key_payload;
2878 								IKE_PACKET_PAYLOAD *my_rand_payload;
2879 								BUF *nat_buf1, *nat_buf2;
2880 								BUF *iv_buf;
2881 								UCHAR iv_hashed_data[IKE_MAX_HASH_SIZE];
2882 								UCHAR initiator_hash[IKE_MAX_HASH_SIZE];
2883 								BUF *b;
2884 								IKE_PACKET_PAYLOAD *my_id_payload, *my_hash_payload;
2885 								UCHAR responder_hash[IKE_MAX_HASH_SIZE];
2886 								BUF *idir_b;
2887 								IKE_PACKET_PAYLOAD *your_nat_d_1 = NULL;
2888 								IKE_PACKET_PAYLOAD *your_nat_d_2 = NULL;
2889 
2890 								// Create an IKE SA
2891 								sa = NewIkeSa(ike, c, header->InitiatorCookie, IKE_SA_AGRESSIVE_MODE, &setting);
2892 								Copy(&sa->Caps, &caps, sizeof(IKE_CAPS));
2893 								sa->State= IKE_SA_AM_STATE_1_SA;
2894 								Insert(ike->IkeSaList, sa);
2895 
2896 								sa->HashSize = sa->TransformSetting.Hash->HashSize;
2897 								sa->KeySize = sa->TransformSetting.CryptoKeySize;
2898 								sa->BlockSize = sa->TransformSetting.Crypto->BlockSize;
2899 
2900 								// Get the Caps additionally
2901 								if (sa->Caps.NatTraversalRfc3947)
2902 								{
2903 									sa->Caps.UsingNatTraversalRfc3947 = true;
2904 
2905 									your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 0);
2906 									your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 1);
2907 								}
2908 								else if (sa->Caps.NatTraversalDraftIetf)
2909 								{
2910 									sa->Caps.UsingNatTraversalDraftIetf = true;
2911 
2912 									your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 0);
2913 									your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 1);
2914 								}
2915 
2916 								// Calculation success
2917 								sa->DhSharedKey = MemToBuf(shared_key, shared_key_size);
2918 								sa->InitiatorRand = RandBuf(IKE_SA_RAND_SIZE);
2919 								sa->ResponderRand = CloneBuf(your_rand_buf);
2920 
2921 								// Save a bit array of SA payload presented by the client
2922 								client_sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
2923 								sa->SAi_b = CloneBuf(client_sa_payload->BitArray);
2924 
2925 								// Save the ID payload presented by the client
2926 								sa->YourIDPayloadForAM = CloneBuf(your_id_payload->BitArray);
2927 
2928 								//// Assemble the SA payload
2929 								// Construct transform payload
2930 								tp = TransformSettingToTransformPayloadForIke(ike, &setting);
2931 
2932 								// Build a proposal payload
2933 								pp = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IKE, NULL, 0, NewListSingle(tp));
2934 
2935 								// Build the SA payload
2936 								sap = IkeNewSaPayload(NewListSingle(pp));
2937 
2938 								payload_list = NewListSingle(sap);
2939 
2940 								// Send a key exchange packet
2941 								my_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
2942 								my_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
2943 
2944 								Add(payload_list, my_key_payload);
2945 								Add(payload_list, my_rand_payload);
2946 
2947 								// NAT-D Packet
2948 								// Address of the opponent. Randomize in order to be forced to use NAT
2949 								nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, Rand64(), Rand64(), &c->ClientIP, Rand16());
2950 
2951 								// My address
2952 								if (c->IsMicrosoft == false || (your_nat_d_1 == NULL || your_nat_d_2 == NULL || your_nat_d_1->BitArray == NULL))
2953 								{
2954 									// Calculate exactly
2955 									nat_buf2 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash,
2956 										sa->InitiatorCookie, sa->ResponderCookie, &c->ServerIP, c->ServerPort);
2957 								}
2958 								else
2959 								{
2960 									// Parrot the NAT_D payload indicating myself I got from
2961 									// the other if it has connected from a Microsoft VPN Client
2962 									nat_buf2 = CloneBuf(your_nat_d_1->BitArray);
2963 								}
2964 
2965 								// Save DH information
2966 								sa->GXi = CloneBuf(your_key_buf);
2967 								sa->GXr = CloneBuf(dh->MyPublicKey);
2968 
2969 								// Calculate the key set
2970 								IkeCalcSaKeySet(ike, sa, NULL);
2971 
2972 								// Calculate the initiator side hash value
2973 								b = NewBuf();
2974 								WriteBufBuf(b, sa->GXi);
2975 								WriteBufBuf(b, sa->GXr);
2976 								WriteBufInt64(b, sa->InitiatorCookie);
2977 								WriteBufInt64(b, sa->ResponderCookie);
2978 								WriteBufBuf(b, sa->SAi_b);
2979 								WriteBufBuf(b, sa->YourIDPayloadForAM);
2980 
2981 								IkeHMac(sa->TransformSetting.Hash, initiator_hash, sa->SKEYID, sa->HashSize,
2982 									b->Buf, b->Size);
2983 
2984 								FreeBuf(b);
2985 
2986 								Copy(sa->InitiatorHashForAM, initiator_hash, sa->HashSize);
2987 
2988 								// Prepare the response ID payload
2989 								// Generate the ID payload
2990 								if (IsIP6(&sa->IkeClient->ServerIP))
2991 								{
2992 									// IPv6 address
2993 									my_id_payload = IkeNewIdPayload(IKE_ID_IPV6_ADDR, 0, 0, sa->IkeClient->ServerIP.ipv6_addr, 16);
2994 								}
2995 								else
2996 								{
2997 									// IPv4 address
2998 									my_id_payload = IkeNewIdPayload(IKE_ID_IPV4_ADDR, 0, 0, sa->IkeClient->ServerIP.addr, 4);
2999 								}
3000 
3001 								// Build the ID payload tentatively
3002 								idir_b = IkeBuildIdPayload(&my_id_payload->Payload.Id);
3003 
3004 								b = NewBuf();
3005 								WriteBufBuf(b, sa->GXr);
3006 								WriteBufBuf(b, sa->GXi);
3007 								WriteBufInt64(b, sa->ResponderCookie);
3008 								WriteBufInt64(b, sa->InitiatorCookie);
3009 								WriteBufBuf(b, sa->SAi_b);
3010 								WriteBufBuf(b, idir_b);
3011 
3012 								IkeHMac(sa->TransformSetting.Hash, responder_hash, sa->SKEYID, sa->HashSize,
3013 									b->Buf, b->Size);
3014 
3015 								FreeBuf(b);
3016 								FreeBuf(idir_b);
3017 
3018 								my_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, responder_hash, sa->HashSize);
3019 
3020 								Add(payload_list, my_id_payload);
3021 								Add(payload_list, my_hash_payload);
3022 
3023 								ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_AGGRESSIVE,
3024 									false, false, false, 0, payload_list);
3025 
3026 								// Add the vendor ID
3027 								IkeAddVendorIdPayloads(ps);
3028 
3029 								// NAT-D related
3030 								if (sa->Caps.UsingNatTraversalRfc3947)
3031 								{
3032 									// RFC-compliant
3033 									Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf1->Buf, nat_buf1->Size));
3034 									Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf2->Buf, nat_buf2->Size));
3035 								}
3036 
3037 								if (sa->Caps.UsingNatTraversalDraftIetf)
3038 								{
3039 									// Draft compliant
3040 									Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf1->Buf, nat_buf1->Size));
3041 									Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf2->Buf, nat_buf2->Size));
3042 								}
3043 
3044 								FreeBuf(nat_buf1);
3045 								FreeBuf(nat_buf2);
3046 
3047 								StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
3048 								Debug("Client ID = %s\n", c->ClientId);
3049 
3050 								IPsecLog(ike, c, NULL, NULL, NULL, "LI_SET_CLIENT_ID", c->ClientId);
3051 
3052 								// Initial IV setting
3053 								iv_buf = NewBuf();
3054 								WriteBuf(iv_buf, your_key_buf->Buf, your_key_buf->Size);
3055 								WriteBuf(iv_buf, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
3056 								IkeHash(sa->TransformSetting.Hash, iv_hashed_data, iv_buf->Buf, iv_buf->Size);
3057 
3058 								BinToStrEx(tmp, sizeof(tmp), iv_hashed_data, sa->BlockSize);
3059 								Debug("Initial IV: %s\n", tmp);
3060 
3061 								IkeSaUpdateIv(sa, iv_hashed_data, sa->HashSize);
3062 
3063 								FreeBuf(iv_buf);
3064 
3065 								// Transmission
3066 								IkeSaSendPacket(ike, sa, ps);
3067 
3068 								IkeFree(ps);
3069 							}
3070 							else
3071 							{
3072 								// DH calculation failure
3073 								Debug("DhCompute failed.\n");
3074 							}
3075 
3076 							Free(shared_key);
3077 							DhFree(dh);
3078 						}
3079 					}
3080 					else
3081 					{
3082 						// No appropriate transform setting
3083 						Debug("No Appropriate Transform was Found.\n");
3084 
3085 						IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_TRANSFORM");
3086 
3087 						SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(false, header->InitiatorCookie, header->ResponderCookie));
3088 					}
3089 				}
3090 			}
3091 			else
3092 			{
3093 				// Client does not support NAT Traversal
3094 				Debug("Client doesn't support NAT-T.\n");
3095 
3096 				IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_NAT_T");
3097 			}
3098 
3099 			IkeFree(pr);
3100 		}
3101 	}
3102 	else
3103 	{
3104 		// Process of state 2
3105 		IKE_SA *sa;
3106 
3107 		sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
3108 
3109 		if (sa == NULL)
3110 		{
3111 			SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
3112 				header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
3113 		}
3114 
3115 		if (sa != NULL && sa->Mode == IKE_SA_AGRESSIVE_MODE)
3116 		{
3117 			IKE_PACKET *pr = NULL;
3118 
3119 			sa->LastCommTick = ike->Now;
3120 
3121 			switch (sa->State)
3122 			{
3123 			case IKE_SA_AM_STATE_1_SA:
3124 				pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
3125 				if (pr != NULL)
3126 				{
3127 					IKE_PACKET_PAYLOAD *your_hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
3128 
3129 					if (your_hash_payload != NULL)
3130 					{
3131 						// Compare the hash
3132 						if (IkeCompareHash(your_hash_payload, sa->InitiatorHashForAM, sa->HashSize))
3133 						{
3134 							// Transit to the established state
3135 							Debug("IKE SA 0x%X Established.\n", sa);
3136 							sa->State = IKE_SA_AM_STATE_2_ESTABLISHED;
3137 							sa->EstablishedTick = ike->Now;
3138 							sa->Established = true;
3139 							c->CurrentIkeSa = sa;
3140 							c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
3141 							StrCpy(c->Secret, sizeof(c->Secret), sa->Secret);
3142 
3143 							IPsecLog(ike, NULL, sa, NULL, "LI_IKE_SA_ESTABLISHED");
3144 
3145 							IkeSaSendPacket(ike, sa, NULL);
3146 						}
3147 						else
3148 						{
3149 							Debug("IKE SA 0x%X Invalid Hash.\n", sa);
3150 						}
3151 					}
3152 				}
3153 				break;
3154 			}
3155 
3156 			if (pr != NULL)
3157 			{
3158 				IkeFree(pr);
3159 			}
3160 		}
3161 	}
3162 }
3163 
3164 // Process of the main mode packet reception
ProcIkeMainModePacketRecv(IKE_SERVER * ike,UDPPACKET * p,IKE_PACKET * header)3165 void ProcIkeMainModePacketRecv(IKE_SERVER *ike, UDPPACKET *p, IKE_PACKET *header)
3166 {
3167 	IKE_CLIENT *c;
3168 	char tmp[MAX_SIZE];
3169 	// Validate arguments
3170 	if (ike == NULL || p == NULL || header == NULL || header->InitiatorCookie == 0)
3171 	{
3172 		return;
3173 	}
3174 
3175 	c = SearchOrCreateNewIkeClientForIkePacket(ike, &p->SrcIP, p->SrcPort, &p->DstIP, p->DestPort, header);
3176 
3177 	if (c == NULL)
3178 	{
3179 		return;
3180 	}
3181 
3182 	if (header->ResponderCookie == 0)
3183 	{
3184 		// Start process of the state 1
3185 		IKE_CAPS caps;
3186 		IKE_SA *sa;
3187 		IKE_PACKET *pr = IkeParse(p->Data, p->Size, NULL);
3188 
3189 		if (pr != NULL)
3190 		{
3191 			// Determine the CAPS
3192 			IkeCheckCaps(&caps, pr);
3193 			if (caps.MS_L2TPIPSecVPNClient || caps.MS_NT5_ISAKMP_OAKLEY || caps.MS_Vid_InitialContact)
3194 			{
3195 				c->IsMicrosoft = true;
3196 			}
3197 
3198 			if ((caps.NatTraversalDraftIetf || caps.NatTraversalRfc3947) || (IsUdpPortOpened(ike->IPsec->UdpListener, &p->DstIP, IPSEC_PORT_IPSEC_ESP_RAW)))
3199 			{
3200 				sa = FindIkeSaByEndPointAndInitiatorCookie(ike, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, header->InitiatorCookie, IKE_SA_MAIN_MODE);
3201 
3202 				if (sa == NULL)
3203 				{
3204 					// Check whether there is acceptable SA parameters by analyzing proposed parameters
3205 					IKE_SA_TRANSFORM_SETTING setting;
3206 
3207 					if (GetBestTransformSettingForIkeSa(ike, pr, &setting) && (GetNumberOfIkeSaOfIkeClient(ike, c) <= IKE_QUOTA_MAX_SA_PER_CLIENT))
3208 					{
3209 						IKE_PACKET *ps;
3210 						IKE_PACKET_PAYLOAD *tp;
3211 						IKE_PACKET_PAYLOAD *pp;
3212 						IKE_PACKET_PAYLOAD *sap;
3213 						LIST *payload_list;
3214 						IKE_PACKET_PAYLOAD *client_sa_payload;
3215 
3216 						// Appropriate transform setting is selected
3217 						Debug("P1 Transform: %s %s %s(%u) %u %u\n",
3218 							setting.Dh->Name, setting.Hash->Name, setting.Crypto->Name, setting.CryptoKeySize,
3219 							setting.LifeKilobytes, setting.LifeSeconds);
3220 
3221 #ifdef	FORCE_LIFETIME_MM
3222 						setting.LifeSeconds = FORCE_LIFETIME_MM;
3223 #endif	// FORCE_LIFETIME_MM
3224 
3225 						// Create an IKE SA
3226 						sa = NewIkeSa(ike, c, header->InitiatorCookie, IKE_SA_MAIN_MODE, &setting);
3227 
3228 						Copy(&sa->Caps, &caps, sizeof(IKE_CAPS));
3229 
3230 						Insert(ike->IkeSaList, sa);
3231 
3232 						// Answer the SA parameter selection results
3233 						sa->State = IKE_SA_MM_STATE_1_SA;
3234 
3235 						// Save a bit array of SA payload presented by the client
3236 						client_sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
3237 						sa->SAi_b = CloneBuf(client_sa_payload->BitArray);
3238 
3239 						//// Assemble the SA payload
3240 						// Construct a transform payload
3241 						tp = TransformSettingToTransformPayloadForIke(ike, &setting);
3242 
3243 						// Build a proposal payload
3244 						pp = IkeNewProposalPayload(1, IKE_PROTOCOL_ID_IKE, NULL, 0, NewListSingle(tp));
3245 
3246 						// Build a SA payload
3247 						sap = IkeNewSaPayload(NewListSingle(pp));
3248 
3249 						payload_list = NewListSingle(sap);
3250 
3251 						ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN,
3252 							false, false, false, 0, payload_list);
3253 
3254 						// Add the vendor ID payload
3255 						IkeAddVendorIdPayloads(ps);
3256 
3257 						IkeSaSendPacket(ike, sa, ps);
3258 
3259 						sa->HashSize = sa->TransformSetting.Hash->HashSize;
3260 						sa->KeySize = sa->TransformSetting.CryptoKeySize;
3261 						sa->BlockSize = sa->TransformSetting.Crypto->BlockSize;
3262 
3263 						IkeFree(ps);
3264 					}
3265 					else
3266 					{
3267 						// No appropriate transform setting
3268 						Debug("No Appropriate Transform was Found.\n");
3269 
3270 						IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_TRANSFORM");
3271 
3272 						SendInformationalExchangePacket(ike, c, IkeNewNoticeErrorNoProposalChosenPayload(false, header->InitiatorCookie, header->ResponderCookie));
3273 					}
3274 				}
3275 				else
3276 				{
3277 					// Ignore for IKE SA which already exists (Because it's likely to be a re-transmission)
3278 				}
3279 			}
3280 			else
3281 			{
3282 				// It does not support NAT Traversal
3283 				Debug("Client doesn't support NAT-T.\n");
3284 
3285 				IPsecLog(ike, c, NULL, NULL, "LI_IKE_NO_NAT_T");
3286 			}
3287 			IkeFree(pr);
3288 		}
3289 	}
3290 	else
3291 	{
3292 		// Process of state 2 or later
3293 		IKE_SA *sa;
3294 
3295 		sa = FindIkeSaByResponderCookieAndClient(ike, header->ResponderCookie, c);
3296 
3297 		if (sa == NULL)
3298 		{
3299 			SendInformationalExchangePacketEx(ike, c, IkeNewNoticeErrorInvalidCookiePayload(header->InitiatorCookie,
3300 				header->ResponderCookie), true, header->InitiatorCookie, header->ResponderCookie);
3301 		}
3302 
3303 		if (sa != NULL && sa->Mode == IKE_SA_MAIN_MODE)
3304 		{
3305 			IKE_PACKET *pr = NULL;
3306 
3307 			sa->LastCommTick = ike->Now;
3308 
3309 			switch (sa->State)
3310 			{
3311 			case IKE_SA_MM_STATE_1_SA:
3312 				pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
3313 				if (pr != NULL)
3314 				{
3315 					// Receive a key exchange packet
3316 					IKE_PACKET_PAYLOAD *your_key_payload;
3317 					IKE_PACKET_PAYLOAD *your_rand_payload;
3318 					IKE_PACKET_PAYLOAD *your_nat_d_1 = NULL;
3319 					IKE_PACKET_PAYLOAD *your_nat_d_2 = NULL;
3320 
3321 					your_key_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_KEY_EXCHANGE, 0);
3322 					your_rand_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_RAND, 0);
3323 
3324 					if (IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NAT_D) != 0)
3325 					{
3326 						sa->Caps.UsingNatTraversalRfc3947 = true;
3327 
3328 						your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 0);
3329 						your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D, 1);
3330 					}
3331 
3332 					if (IkeGetPayloadNum(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT) != 0)
3333 					{
3334 						sa->Caps.UsingNatTraversalDraftIetf = true;
3335 
3336 						your_nat_d_1 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 0);
3337 						your_nat_d_2 = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_NAT_D_DRAFT, 1);
3338 					}
3339 
3340 					if (your_key_payload != NULL && your_rand_payload != NULL)
3341 					{
3342 						// Check the key payload
3343 						BUF *your_key_buf = your_key_payload->Payload.KeyExchange.Data;
3344 						BUF *your_rand_buf = your_rand_payload->Payload.Rand.Data;
3345 
3346 						// DH generation
3347 						DH_CTX *dh = IkeDhNewCtx(sa->TransformSetting.Dh);
3348 						UINT shared_key_size = (dh == NULL ? 0 : dh->Size);
3349 						UCHAR *shared_key = ZeroMalloc(shared_key_size);
3350 
3351 						// DH calculation
3352 						if (DhCompute(dh, shared_key, your_key_buf->Buf, your_key_buf->Size))
3353 						{
3354 							IKE_PACKET *ps;
3355 							LIST *payload_list;
3356 							IKE_PACKET_PAYLOAD *my_key_payload;
3357 							IKE_PACKET_PAYLOAD *my_rand_payload;
3358 							BUF *nat_buf1, *nat_buf2;
3359 							BUF *iv_buf;
3360 							UCHAR iv_hashed_data[IKE_MAX_HASH_SIZE];
3361 
3362 							// Calculation success
3363 							sa->DhSharedKey = MemToBuf(shared_key, shared_key_size);
3364 							sa->InitiatorRand = RandBuf(IKE_SA_RAND_SIZE);
3365 							sa->ResponderRand = CloneBuf(your_rand_buf);
3366 
3367 							// Send a key exchange packet
3368 							my_key_payload = IkeNewDataPayload(IKE_PAYLOAD_KEY_EXCHANGE, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
3369 							my_rand_payload = IkeNewDataPayload(IKE_PAYLOAD_RAND, sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
3370 
3371 							payload_list = NewListSingle(my_key_payload);
3372 							Add(payload_list, my_rand_payload);
3373 
3374 							// NAT-D packet
3375 							// Address of the opponent. Randomize in order to be forced to use NAT
3376 							nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, Rand64(), Rand64(), &c->ClientIP, Rand16());
3377 							//nat_buf1 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash, sa->InitiatorCookie, sa->ResponderCookie, &c->ClientIP, c->ClientPort);
3378 							// My address
3379 
3380 							if (c->IsMicrosoft == false || (your_nat_d_1 == NULL || your_nat_d_2 == NULL || your_nat_d_1->BitArray == NULL))
3381 							{
3382 								// Calculate exactly
3383 								nat_buf2 = IkeCalcNatDetectHash(ike, sa->TransformSetting.Hash,
3384 									sa->InitiatorCookie, sa->ResponderCookie, &c->ServerIP, c->ServerPort);
3385 							}
3386 							else
3387 							{
3388 								// Parrot the NAT_D payload indicating myself I got from
3389 								// the other if it has connected from a Microsoft VPN Client
3390 								nat_buf2 = CloneBuf(your_nat_d_1->BitArray);
3391 							}
3392 
3393 							if (sa->Caps.UsingNatTraversalRfc3947)
3394 							{
3395 								// RFC-compliant
3396 								Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf1->Buf, nat_buf1->Size));
3397 								Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D, nat_buf2->Buf, nat_buf2->Size));
3398 							}
3399 
3400 							if (sa->Caps.UsingNatTraversalDraftIetf)
3401 							{
3402 								// Draft compliant
3403 								Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf1->Buf, nat_buf1->Size));
3404 								Add(payload_list, IkeNewDataPayload(IKE_PAYLOAD_NAT_D_DRAFT, nat_buf2->Buf, nat_buf2->Size));
3405 							}
3406 
3407 							FreeBuf(nat_buf1);
3408 							FreeBuf(nat_buf2);
3409 
3410 							ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN,
3411 								false, false, false, 0, payload_list);
3412 
3413 							// Initial IV setting
3414 							iv_buf = NewBuf();
3415 							WriteBuf(iv_buf, your_key_buf->Buf, your_key_buf->Size);
3416 							WriteBuf(iv_buf, dh->MyPublicKey->Buf, dh->MyPublicKey->Size);
3417 							IkeHash(sa->TransformSetting.Hash, iv_hashed_data, iv_buf->Buf, iv_buf->Size);
3418 
3419 							BinToStrEx(tmp, sizeof(tmp), iv_hashed_data, sa->BlockSize);
3420 							Debug("Initial IV: %s\n", tmp);
3421 
3422 							IkeSaUpdateIv(sa, iv_hashed_data, sa->HashSize);
3423 
3424 							FreeBuf(iv_buf);
3425 
3426 							// Save the DH information
3427 							sa->GXi = CloneBuf(your_key_buf);
3428 							sa->GXr = CloneBuf(dh->MyPublicKey);
3429 
3430 							// Transmission
3431 							IkeSaSendPacket(ike, sa, ps);
3432 
3433 							IkeFree(ps);
3434 
3435 							// Calculate the key set
3436 							IkeCalcSaKeySet(ike, sa, NULL);
3437 
3438 							sa->State = IKE_SA_MM_STATE_2_KEY;
3439 						}
3440 						else
3441 						{
3442 							// DH calculation failure
3443 							Debug("DhCompute failed.\n");
3444 						}
3445 
3446 						Free(shared_key);
3447 						DhFree(dh);
3448 					}
3449 				}
3450 				break;
3451 
3452 			case IKE_SA_MM_STATE_2_KEY:
3453 				pr = IkeSaRecvPacket(ike, sa, p->Data, p->Size);
3454 				if (pr != NULL && pr->FlagEncrypted)
3455 				{
3456 					// Receive an ID exchange packet
3457 					IKE_PACKET_PAYLOAD *your_id_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_ID, 0);
3458 					IKE_PACKET_PAYLOAD *your_hash_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_HASH, 0);
3459 
3460 					if (your_id_payload && your_hash_payload)
3461 					{
3462 						UCHAR initiator_hash[IKE_MAX_HASH_SIZE];
3463 						BUF *b;
3464 
3465 						// Calculate the initiator side hash value
3466 						b = NewBuf();
3467 						WriteBufBuf(b, sa->GXi);
3468 						WriteBufBuf(b, sa->GXr);
3469 						WriteBufInt64(b, sa->InitiatorCookie);
3470 						WriteBufInt64(b, sa->ResponderCookie);
3471 						WriteBufBuf(b, sa->SAi_b);
3472 						WriteBufBuf(b, your_id_payload->BitArray);
3473 
3474 						StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
3475 						Debug("Client ID = %s\n", c->ClientId);
3476 						IPsecLog(ike, c, NULL, NULL, NULL, "LI_SET_CLIENT_ID", c->ClientId);
3477 
3478 						IkeHMac(sa->TransformSetting.Hash, initiator_hash, sa->SKEYID, sa->HashSize,
3479 							b->Buf, b->Size);
3480 
3481 						FreeBuf(b);
3482 
3483 						// Hash comparison
3484 						if (IkeCompareHash(your_hash_payload, initiator_hash, sa->HashSize))
3485 						{
3486 							// Generate a response packet
3487 							IKE_PACKET *ps;
3488 							LIST *payload_list = NewListFast(NULL);
3489 							IKE_PACKET_PAYLOAD *my_id_payload, *my_hash_payload;
3490 							UCHAR responder_hash[IKE_MAX_HASH_SIZE];
3491 							BUF *idir_b;
3492 
3493 							// Generate an ID payload
3494 							if (IsIP6(&sa->IkeClient->ServerIP))
3495 							{
3496 								// IPv6 address
3497 								my_id_payload = IkeNewIdPayload(IKE_ID_IPV6_ADDR, 0, 0, sa->IkeClient->ServerIP.ipv6_addr, 16);
3498 							}
3499 							else
3500 							{
3501 								// IPv4 address
3502 								my_id_payload = IkeNewIdPayload(IKE_ID_IPV4_ADDR, 0, 0, sa->IkeClient->ServerIP.addr, 4);
3503 							}
3504 
3505 							// Build the ID payload tentatively
3506 							idir_b = IkeBuildIdPayload(&my_id_payload->Payload.Id);
3507 
3508 							// Generate the hash payload
3509 							b = NewBuf();
3510 							WriteBufBuf(b, sa->GXr);
3511 							WriteBufBuf(b, sa->GXi);
3512 							WriteBufInt64(b, sa->ResponderCookie);
3513 							WriteBufInt64(b, sa->InitiatorCookie);
3514 							WriteBufBuf(b, sa->SAi_b);
3515 							WriteBufBuf(b, idir_b);
3516 
3517 							IkeHMac(sa->TransformSetting.Hash, responder_hash, sa->SKEYID, sa->HashSize,
3518 								b->Buf, b->Size);
3519 
3520 							FreeBuf(b);
3521 							FreeBuf(idir_b);
3522 
3523 							my_hash_payload = IkeNewDataPayload(IKE_PAYLOAD_HASH, responder_hash, sa->HashSize);
3524 
3525 							Add(payload_list, my_id_payload);
3526 							Add(payload_list, my_hash_payload);
3527 
3528 							ps = IkeNew(sa->InitiatorCookie, sa->ResponderCookie, IKE_EXCHANGE_TYPE_MAIN, true, false,
3529 								false, 0, payload_list);
3530 
3531 							// Transmission
3532 							IkeSaSendPacket(ike, sa, ps);
3533 							sa->NumResends = 3;
3534 
3535 							IkeFree(ps);
3536 
3537 							StrCpy(c->ClientId, sizeof(c->ClientId), your_id_payload->Payload.Id.StrData);
3538 
3539 							// Transit to the established state
3540 							Debug("IKE SA 0x%X Established. Client ID=%s\n", sa, c->ClientId);
3541 							sa->State = IKE_SA_MM_STATE_3_ESTABLISHED;
3542 							sa->EstablishedTick = ike->Now;
3543 							c->CurrentIkeSa = sa;
3544 							c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
3545 							StrCpy(c->Secret, sizeof(c->Secret), sa->Secret);
3546 							sa->Established = true;
3547 
3548 							IPsecLog(ike, NULL, sa, NULL, "LI_IKE_SA_ESTABLISHED");
3549 						}
3550 						else
3551 						{
3552 							Debug("IKE SA 0x%X Invalid Hash.\n", sa);
3553 						}
3554 					}
3555 				}
3556 				break;
3557 			}
3558 
3559 			if (pr != NULL)
3560 			{
3561 				IkeFree(pr);
3562 			}
3563 		}
3564 	}
3565 }
3566 
3567 // Update the IV of IPsec SA
IPsecSaUpdateIv(IPSECSA * sa,void * iv,UINT iv_size)3568 void IPsecSaUpdateIv(IPSECSA *sa, void *iv, UINT iv_size)
3569 {
3570 	// Validate arguments
3571 	if (sa == NULL || iv == NULL)
3572 	{
3573 		return;
3574 	}
3575 
3576 	Copy(sa->Iv, iv, MIN(sa->IkeSa->BlockSize, iv_size));
3577 
3578 	if (iv_size < sa->IkeSa->BlockSize)
3579 	{
3580 		Zero(sa->Iv + sa->IkeSa->BlockSize, sa->IkeSa->BlockSize - iv_size);
3581 	}
3582 
3583 	sa->IsIvExisting = true;
3584 }
3585 
3586 // Update the IV of the IKE SA
IkeSaUpdateIv(IKE_SA * sa,void * iv,UINT iv_size)3587 void IkeSaUpdateIv(IKE_SA *sa, void *iv, UINT iv_size)
3588 {
3589 	// Validate arguments
3590 	if (sa == NULL || iv == NULL)
3591 	{
3592 		return;
3593 	}
3594 
3595 	Copy(sa->Iv, iv, MIN(sa->BlockSize, iv_size));
3596 
3597 	if (iv_size < sa->BlockSize)
3598 	{
3599 		Zero(sa->Iv + sa->BlockSize, sa->BlockSize - iv_size);
3600 	}
3601 
3602 	sa->IsIvExisting = true;
3603 }
3604 
3605 // Calculate the key set of the IKE SA
IkeCalcSaKeySet(IKE_SERVER * ike,IKE_SA * sa,char * secret)3606 void IkeCalcSaKeySet(IKE_SERVER *ike, IKE_SA *sa, char *secret)
3607 {
3608 	BUF *secret_buf;
3609 	BUF *rand_buf;
3610 	BUF *d_buf, *a_buf, *e_buf;
3611 	UCHAR u;
3612 	IKE_HASH *h;
3613 	char tmp[MAX_SIZE];
3614 	// Validate arguments
3615 	if (ike == NULL || sa == NULL)
3616 	{
3617 		return;
3618 	}
3619 
3620 	h = sa->TransformSetting.Hash;
3621 
3622 	// Calculation of SKEYID
3623 	StrCpy(sa->Secret, sizeof(sa->Secret), secret == NULL ? ike->Secret : secret);
3624 	secret_buf = IkeStrToPassword(sa->Secret);
3625 	rand_buf = CloneBuf(sa->ResponderRand);
3626 	SeekBufToEnd(rand_buf);
3627 	BinToStrEx(tmp, sizeof(tmp), rand_buf->Buf, rand_buf->Size);
3628 	Debug("ResponderRand: %s\n", tmp);
3629 	BinToStrEx(tmp, sizeof(tmp), sa->InitiatorRand->Buf, sa->InitiatorRand->Size);
3630 	Debug("InitiatorRand: %s\n", tmp);
3631 
3632 	WriteBufBuf(rand_buf, sa->InitiatorRand);
3633 
3634 	IkeHMacBuf(h, sa->SKEYID, secret_buf, rand_buf);
3635 
3636 	BinToStrEx(tmp, sizeof(tmp), sa->SKEYID, sa->HashSize);
3637 	Debug("SKEYID: %s\n", tmp);
3638 
3639 	// SKEYID_d
3640 	d_buf = CloneBuf(sa->DhSharedKey);
3641 	SeekBufToEnd(d_buf);
3642 	WriteBufInt64(d_buf, sa->InitiatorCookie);
3643 	WriteBufInt64(d_buf, sa->ResponderCookie);
3644 	u = 0;
3645 	WriteBuf(d_buf, &u, 1);
3646 	IkeHMac(h, sa->SKEYID_d, sa->SKEYID, sa->HashSize, d_buf->Buf, d_buf->Size);
3647 
3648 	BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_d, sa->HashSize);
3649 	Debug("SKEYID_d: %s\n", tmp);
3650 
3651 	// SKEYID_a
3652 	a_buf = MemToBuf(sa->SKEYID_d, sa->HashSize);
3653 	SeekBufToEnd(a_buf);
3654 	WriteBufBuf(a_buf, sa->DhSharedKey);
3655 	WriteBufInt64(a_buf, sa->InitiatorCookie);
3656 	WriteBufInt64(a_buf, sa->ResponderCookie);
3657 	u = 1;
3658 	WriteBuf(a_buf, &u, 1);
3659 	IkeHMac(h, sa->SKEYID_a, sa->SKEYID, sa->HashSize, a_buf->Buf, a_buf->Size);
3660 
3661 	BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_a, sa->HashSize);
3662 	Debug("SKEYID_a: %s\n", tmp);
3663 
3664 	// SKEYID_e
3665 	e_buf = MemToBuf(sa->SKEYID_a, sa->HashSize);
3666 	SeekBufToEnd(e_buf);
3667 	WriteBufBuf(e_buf, sa->DhSharedKey);
3668 	WriteBufInt64(e_buf, sa->InitiatorCookie);
3669 	WriteBufInt64(e_buf, sa->ResponderCookie);
3670 	u = 2;
3671 	WriteBuf(e_buf, &u, 1);
3672 	IkeHMac(h, sa->SKEYID_e, sa->SKEYID, sa->HashSize, e_buf->Buf, e_buf->Size);
3673 
3674 	BinToStrEx(tmp, sizeof(tmp), sa->SKEYID_e, sa->HashSize);
3675 	Debug("SKEYID_e: %s\n", tmp);
3676 
3677 	if (sa->CryptoKey != NULL)
3678 	{
3679 		IkeFreeKey(sa->CryptoKey);
3680 	}
3681 
3682 	sa->CryptoKey = IkeNewCryptoKeyFromK(ike, sa->SKEYID_e, sa->HashSize, sa->TransformSetting.Hash,
3683 		sa->TransformSetting.Crypto, sa->TransformSetting.CryptoKeySize);
3684 
3685 	// Release the memory
3686 	FreeBuf(secret_buf);
3687 	FreeBuf(rand_buf);
3688 	FreeBuf(d_buf);
3689 	FreeBuf(a_buf);
3690 	FreeBuf(e_buf);
3691 }
3692 
3693 // Extend the key size
IkeExpandKeySize(IKE_HASH * h,void * k,UINT k_size,UINT target_size)3694 BUF *IkeExpandKeySize(IKE_HASH *h, void *k, UINT k_size, UINT target_size)
3695 {
3696 	BUF *b1, *b2;
3697 	UCHAR tmp[IKE_MAX_HASH_SIZE];
3698 	UINT tmp_size;
3699 	// Validate arguments
3700 	if (h == NULL || k == NULL || k_size == 0)
3701 	{
3702 		return NULL;
3703 	}
3704 
3705 	if (k_size >= target_size)
3706 	{
3707 		return MemToBuf(k, target_size);
3708 	}
3709 
3710 	tmp[0] = 0;
3711 	tmp_size = 1;
3712 	b1 = NewBuf();
3713 
3714 	do
3715 	{
3716 		IkeHMac(h, tmp, k, k_size, tmp, tmp_size);
3717 		WriteBuf(b1, tmp, h->HashSize);
3718 
3719 		tmp_size = h->HashSize;
3720 	}
3721 	while (b1->Size < target_size);
3722 
3723 	b2 = MemToBuf(b1->Buf, target_size);
3724 
3725 	FreeBuf(b1);
3726 
3727 	return b2;
3728 }
3729 
3730 // Generate a key from K
IkeNewCryptoKeyFromK(IKE_SERVER * ike,void * k,UINT k_size,IKE_HASH * h,IKE_CRYPTO * c,UINT crypto_key_size)3731 IKE_CRYPTO_KEY *IkeNewCryptoKeyFromK(IKE_SERVER *ike, void *k, UINT k_size, IKE_HASH *h, IKE_CRYPTO *c, UINT crypto_key_size)
3732 {
3733 	BUF *key_buf;
3734 	IKE_CRYPTO_KEY *ret;
3735 	// Validate arguments
3736 	if (ike == NULL || k == NULL || k_size == 0 || h == NULL || c == NULL || crypto_key_size == 0)
3737 	{
3738 		return NULL;
3739 	}
3740 
3741 	key_buf = IkeExpandKeySize(h, k, k_size, crypto_key_size);
3742 	if (key_buf == NULL)
3743 	{
3744 		return NULL;
3745 	}
3746 
3747 	ret = IkeNewKey(c, key_buf->Buf, key_buf->Size);
3748 
3749 	FreeBuf(key_buf);
3750 
3751 	return ret;
3752 }
3753 
3754 // Generate a hash for NAT detection
IkeCalcNatDetectHash(IKE_SERVER * ike,IKE_HASH * hash,UINT64 initiator_cookie,UINT64 responder_cookie,IP * ip,UINT port)3755 BUF *IkeCalcNatDetectHash(IKE_SERVER *ike, IKE_HASH *hash, UINT64 initiator_cookie, UINT64 responder_cookie, IP *ip, UINT port)
3756 {
3757 	BUF *b;
3758 	USHORT us;
3759 	USHORT hash_data[IKE_MAX_HASH_SIZE];
3760 	// Validate arguments
3761 	if (ike == NULL || ip == NULL || hash == NULL)
3762 	{
3763 		return NewBuf();
3764 	}
3765 
3766 	b = NewBuf();
3767 
3768 	WriteBufInt64(b, initiator_cookie);
3769 	WriteBufInt64(b, responder_cookie);
3770 
3771 	if (IsIP6(ip))
3772 	{
3773 		WriteBuf(b, ip->ipv6_addr, sizeof(ip->ipv6_addr));
3774 	}
3775 	else
3776 	{
3777 		WriteBuf(b, ip->addr, sizeof(ip->addr));
3778 	}
3779 
3780 	us = Endian16((USHORT)port);
3781 
3782 	WriteBuf(b, &us, sizeof(USHORT));
3783 
3784 	IkeHash(hash, hash_data, b->Buf, b->Size);
3785 
3786 	FreeBuf(b);
3787 
3788 	return MemToBuf(hash_data, hash->HashSize);
3789 }
3790 
3791 // Check the capacity of the opposite IPsec client
IkeCheckCaps(IKE_CAPS * caps,IKE_PACKET * p)3792 void IkeCheckCaps(IKE_CAPS *caps, IKE_PACKET *p)
3793 {
3794 	// Validate arguments
3795 	if (caps == NULL || p == NULL)
3796 	{
3797 		Zero(caps, sizeof(IKE_CAPS));
3798 		return;
3799 	}
3800 
3801 	Zero(caps, sizeof(IKE_CAPS));
3802 
3803 	caps->NatTraversalRfc3947 = IkeIsVendorIdExists(p, IKE_VENDOR_ID_RFC3947_NAT_T);
3804 
3805 	caps->NatTraversalDraftIetf = IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_03) ||
3806 		IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02) ||
3807 		IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02_2) ||
3808 		IkeIsVendorIdExists(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_00);
3809 
3810 	caps->DpdRfc3706 = IkeIsVendorIdExists(p, IKE_VENDOR_ID_RFC3706_DPD);
3811 
3812 	caps->MS_L2TPIPSecVPNClient = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MICROSOFT_L2TP);
3813 	caps->MS_NT5_ISAKMP_OAKLEY = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MS_NT5_ISAKMPOAKLEY);
3814 	caps->MS_Vid_InitialContact = IkeIsVendorIdExists(p, IKE_VENDOR_ID_MS_VID_INITIALCONTACT);
3815 }
3816 
3817 // Check whether the specified vendor ID is contained in the packet
IkeIsVendorIdExists(IKE_PACKET * p,char * str)3818 bool IkeIsVendorIdExists(IKE_PACKET *p, char *str)
3819 {
3820 	BUF *buf;
3821 	UINT i, num;
3822 	bool ok = false;
3823 	// Validate arguments
3824 	if (p == NULL || str == NULL)
3825 	{
3826 		return false;
3827 	}
3828 
3829 	buf = IkeStrToVendorId(str);
3830 	if (buf == NULL)
3831 	{
3832 		return false;
3833 	}
3834 
3835 	num = IkeGetPayloadNum(p->PayloadList, IKE_PAYLOAD_VENDOR_ID);
3836 	for (i = 0;i < num;i++)
3837 	{
3838 		IKE_PACKET_PAYLOAD *payload = IkeGetPayload(p->PayloadList, IKE_PAYLOAD_VENDOR_ID, i);
3839 		if (payload == NULL)
3840 		{
3841 			break;
3842 		}
3843 
3844 		if (CompareBuf(payload->Payload.VendorId.Data, buf))
3845 		{
3846 			ok = true;
3847 		}
3848 		else
3849 		{
3850 			if (payload->Payload.VendorId.Data != NULL)
3851 			{
3852 				if (payload->Payload.VendorId.Data->Size >= buf->Size)
3853 				{
3854 					if (Cmp(payload->Payload.VendorId.Data->Buf, buf->Buf, buf->Size) == 0)
3855 					{
3856 						ok = true;
3857 					}
3858 				}
3859 			}
3860 		}
3861 	}
3862 
3863 	FreeBuf(buf);
3864 
3865 	return ok;
3866 }
3867 
3868 // Add the vendor ID payload list
IkeAddVendorIdPayloads(IKE_PACKET * p)3869 void IkeAddVendorIdPayloads(IKE_PACKET *p)
3870 {
3871 	// Validate arguments
3872 	if (p == NULL)
3873 	{
3874 		return;
3875 	}
3876 
3877 	IkeAddVendorId(p, IKE_VENDOR_ID_RFC3947_NAT_T);
3878 	IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_03);
3879 	IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02);
3880 	IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_02_2);
3881 	IkeAddVendorId(p, IKE_VENDOR_ID_IPSEC_NAT_T_IKE_00);
3882 	IkeAddVendorId(p, IKE_VENDOR_ID_RFC3706_DPD);
3883 }
3884 
3885 // Add the vendor ID payload
IkeAddVendorId(IKE_PACKET * p,char * str)3886 void IkeAddVendorId(IKE_PACKET *p, char *str)
3887 {
3888 	BUF *buf;
3889 	IKE_PACKET_PAYLOAD *payload;
3890 	// Validate arguments
3891 	if (p == NULL || str == NULL)
3892 	{
3893 		return;
3894 	}
3895 
3896 	buf = IkeStrToVendorId(str);
3897 	if (buf == NULL)
3898 	{
3899 		return;
3900 	}
3901 
3902 	payload = IkeNewDataPayload(IKE_PAYLOAD_VENDOR_ID, buf->Buf, buf->Size);
3903 
3904 	Add(p->PayloadList, payload);
3905 
3906 	FreeBuf(buf);
3907 }
3908 
3909 // Convert string to the vendor ID
IkeStrToVendorId(char * str)3910 BUF *IkeStrToVendorId(char *str)
3911 {
3912 	// Validate arguments
3913 	if (IsEmptyStr(str))
3914 	{
3915 		return NULL;
3916 	}
3917 
3918 	if (StartWith(str, "0x"))
3919 	{
3920 		BUF *buf = StrToBin(str + 2);
3921 
3922 		if (buf == NULL || buf->Size == 0)
3923 		{
3924 			FreeBuf(buf);
3925 			return NULL;
3926 		}
3927 
3928 		return buf;
3929 	}
3930 	else
3931 	{
3932 		BUF *buf;
3933 		UCHAR hash[MD5_SIZE];
3934 
3935 		Hash(hash, str, StrLen(str), false);
3936 
3937 		buf = MemToBuf(hash, sizeof(hash));
3938 
3939 		return buf;
3940 	}
3941 }
3942 
3943 // Receive a packet using the IKE SA
IkeSaRecvPacket(IKE_SERVER * ike,IKE_SA * sa,void * data,UINT size)3944 IKE_PACKET *IkeSaRecvPacket(IKE_SERVER *ike, IKE_SA *sa, void *data, UINT size)
3945 {
3946 	IKE_PACKET *ret;
3947 	// Validate arguments
3948 	if (ike == NULL || sa == NULL || (size != 0 && data == NULL))
3949 	{
3950 		return NULL;
3951 	}
3952 
3953 	if (sa->IsIvExisting == false || sa->CryptoKey == NULL)
3954 	{
3955 		ret = IkeParse(data, size, NULL);
3956 	}
3957 	else
3958 	{
3959 		IKE_CRYPTO_PARAM cp;
3960 
3961 		Copy(&cp.Iv, sa->Iv, sa->BlockSize);
3962 		cp.Key = sa->CryptoKey;
3963 
3964 		ret = IkeParse(data, size, &cp);
3965 
3966 		if (ret->FlagEncrypted)
3967 		{
3968 			IkeSaUpdateIv(sa, cp.NextIv, sa->BlockSize);
3969 		}
3970 	}
3971 
3972 	return ret;
3973 }
3974 
3975 // Receive a packet using IPsec SA (Quick Mode received)
IPsecSaRecvPacket(IKE_SERVER * ike,IPSECSA * sa,void * data,UINT size)3976 IKE_PACKET *IPsecSaRecvPacket(IKE_SERVER *ike, IPSECSA *sa, void *data, UINT size)
3977 {
3978 	IKE_PACKET *ret;
3979 	// Validate arguments
3980 	if (ike == NULL || sa == NULL || (size != 0 && data == NULL))
3981 	{
3982 		return NULL;
3983 	}
3984 
3985 	if (sa->IsIvExisting == false || sa->IkeSa->CryptoKey == NULL)
3986 	{
3987 		ret = IkeParse(data, size, NULL);
3988 	}
3989 	else
3990 	{
3991 		IKE_CRYPTO_PARAM cp;
3992 
3993 		Copy(&cp.Iv, sa->Iv, sa->IkeSa->BlockSize);
3994 		cp.Key = sa->IkeSa->CryptoKey;
3995 
3996 		ret = IkeParse(data, size, &cp);
3997 
3998 		if (ret->FlagEncrypted)
3999 		{
4000 			IPsecSaUpdateIv(sa, cp.NextIv, sa->IkeSa->BlockSize);
4001 			IPsecSaUpdateIv(sa->PairIPsecSa, cp.NextIv, sa->IkeSa->BlockSize);
4002 		}
4003 	}
4004 
4005 	return ret;
4006 }
4007 
4008 // Send a packet using IPsec SA (Quick Mode transmission)
IPsecSaSendPacket(IKE_SERVER * ike,IPSECSA * sa,IKE_PACKET * p)4009 void IPsecSaSendPacket(IKE_SERVER *ike, IPSECSA *sa, IKE_PACKET *p)
4010 {
4011 	BUF *buf;
4012 	// Validate arguments
4013 	if (ike == NULL || sa == NULL)
4014 	{
4015 		return;
4016 	}
4017 
4018 	if (p == NULL)
4019 	{
4020 		FreeBuf(sa->SendBuffer);
4021 		sa->SendBuffer = NULL;
4022 		sa->NextSendTick = 0;
4023 		return;
4024 	}
4025 
4026 	// Build a packet
4027 	if (p->FlagEncrypted == false)
4028 	{
4029 		buf = IkeBuild(p, NULL);
4030 	}
4031 	else
4032 	{
4033 		IKE_CRYPTO_PARAM cp;
4034 
4035 		Copy(cp.Iv, sa->Iv, sa->IkeSa->BlockSize);
4036 		cp.Key = sa->IkeSa->CryptoKey;
4037 
4038 		buf = IkeBuild(p, &cp);
4039 
4040 		IPsecSaUpdateIv(sa, cp.NextIv, sa->IkeSa->BlockSize);
4041 		IPsecSaUpdateIv(sa->PairIPsecSa, cp.NextIv, sa->IkeSa->BlockSize);
4042 	}
4043 
4044 	if (buf == NULL)
4045 	{
4046 		return;
4047 	}
4048 
4049 	// Register the last packet to re-transmit
4050 	if (sa->SendBuffer != NULL)
4051 	{
4052 		FreeBuf(sa->SendBuffer);
4053 	}
4054 
4055 	sa->SendBuffer = CloneBuf(buf);
4056 	sa->NextSendTick = ike->Now + (UINT64)(IKE_SA_RESEND_INTERVAL);
4057 	AddInterrupt(ike->Interrupts, sa->NextSendTick);
4058 
4059 	IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &sa->IkeClient->ServerIP, sa->IkeClient->ServerPort,
4060 		&sa->IkeClient->ClientIP, sa->IkeClient->ClientPort,
4061 		buf->Buf, buf->Size);
4062 
4063 	Free(buf);
4064 }
4065 
4066 // Send a packet using the IKE SA
IkeSaSendPacket(IKE_SERVER * ike,IKE_SA * sa,IKE_PACKET * p)4067 void IkeSaSendPacket(IKE_SERVER *ike, IKE_SA *sa, IKE_PACKET *p)
4068 {
4069 	BUF *buf;
4070 	// Validate arguments
4071 	if (ike == NULL || sa == NULL)
4072 	{
4073 		return;
4074 	}
4075 
4076 	if (p == NULL)
4077 	{
4078 		FreeBuf(sa->SendBuffer);
4079 		sa->SendBuffer = NULL;
4080 		sa->NextSendTick = 0;
4081 		return;
4082 	}
4083 
4084 	// Build a packet
4085 	if (p->FlagEncrypted == false)
4086 	{
4087 		buf = IkeBuild(p, NULL);
4088 	}
4089 	else
4090 	{
4091 		IKE_CRYPTO_PARAM cp;
4092 
4093 		Copy(cp.Iv, sa->Iv, sa->BlockSize);
4094 		cp.Key = sa->CryptoKey;
4095 
4096 		buf = IkeBuild(p, &cp);
4097 
4098 		IkeSaUpdateIv(sa, cp.NextIv, sa->BlockSize);
4099 	}
4100 
4101 	if (buf == NULL)
4102 	{
4103 		return;
4104 	}
4105 
4106 	if (p->ExchangeType != IKE_EXCHANGE_TYPE_INFORMATION)
4107 	{
4108 		// Register the last packet to re-transmit
4109 		if (sa->SendBuffer != NULL)
4110 		{
4111 			FreeBuf(sa->SendBuffer);
4112 		}
4113 
4114 		sa->SendBuffer = CloneBuf(buf);
4115 		sa->NextSendTick = ike->Now + (UINT64)(IKE_SA_RESEND_INTERVAL);
4116 		AddInterrupt(ike->Interrupts, sa->NextSendTick);
4117 	}
4118 
4119 	IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &sa->IkeClient->ServerIP, sa->IkeClient->ServerPort,
4120 		&sa->IkeClient->ClientIP, sa->IkeClient->ClientPort,
4121 		buf->Buf, buf->Size);
4122 
4123 	Free(buf);
4124 }
4125 
4126 // Send an UDP packet
IkeSendUdpPacket(IKE_SERVER * ike,UINT type,IP * server_ip,UINT server_port,IP * client_ip,UINT client_port,void * data,UINT size)4127 void IkeSendUdpPacket(IKE_SERVER *ike, UINT type, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, void *data, UINT size)
4128 {
4129 	UDPPACKET *p;
4130 	// Validate arguments
4131 	if (ike == NULL || server_ip == NULL || client_ip == NULL || server_port == 0 || client_port == 0 || data == NULL || size == 0)
4132 	{
4133 		return;
4134 	}
4135 
4136 	p = NewUdpPacket(server_ip, server_port, client_ip, client_port, data, size);
4137 
4138 	p->Type = type;
4139 
4140 	Add(ike->SendPacketList, p);
4141 }
4142 
4143 // Create an IKE SA
NewIkeSa(IKE_SERVER * ike,IKE_CLIENT * c,UINT64 init_cookie,UINT mode,IKE_SA_TRANSFORM_SETTING * setting)4144 IKE_SA *NewIkeSa(IKE_SERVER *ike, IKE_CLIENT *c, UINT64 init_cookie, UINT mode, IKE_SA_TRANSFORM_SETTING *setting)
4145 {
4146 	IKE_SA *sa;
4147 	// Validate arguments
4148 	if (ike == NULL || c == NULL || init_cookie == 0 || setting == NULL)
4149 	{
4150 		return NULL;
4151 	}
4152 
4153 	sa = ZeroMalloc(sizeof(IKE_SA));
4154 
4155 	sa->Id = ++ike->CurrentIkeSaId;
4156 
4157 	sa->IkeClient = c;
4158 	sa->InitiatorCookie = init_cookie;
4159 	sa->ResponderCookie = GenerateNewResponserCookie(ike);
4160 	sa->Mode = mode;
4161 	sa->FirstCommTick = sa->LastCommTick = ike->Now;
4162 	Copy(&sa->TransformSetting, setting, sizeof(IKE_SA_TRANSFORM_SETTING));
4163 
4164 	Debug("New IKE SA (Mode = %u): %I64u <--> %I64u (%s %s %s(%u) %u %u)\n",
4165 		mode,
4166 		sa->InitiatorCookie,
4167 		sa->ResponderCookie,
4168 		setting->Dh->Name, setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize,
4169 		setting->LifeKilobytes, setting->LifeSeconds);
4170 
4171 	IPsecLog(ike, NULL, sa, NULL, "LI_NEW_IKE_SA",
4172 		(mode == IKE_SA_MAIN_MODE ? _UU("LI_TAG_MAINMODE") : _UU("LI_TAG_AGGRESSIVE")),
4173 		sa->InitiatorCookie, sa->ResponderCookie,
4174 		setting->Dh->Name, setting->Hash->Name, setting->Crypto->Name, setting->CryptoKeySize * 8,
4175 		setting->LifeKilobytes, setting->LifeSeconds);
4176 
4177 	return sa;
4178 }
4179 
4180 // Search an IKE SA from the Responder Cookie
FindIkeSaByResponderCookie(IKE_SERVER * ike,UINT64 responder_cookie)4181 IKE_SA *FindIkeSaByResponderCookie(IKE_SERVER *ike, UINT64 responder_cookie)
4182 {
4183 	IKE_SA t;
4184 	// Validate arguments
4185 	if (ike == NULL || responder_cookie == 0)
4186 	{
4187 		return NULL;
4188 	}
4189 
4190 	t.ResponderCookie = responder_cookie;
4191 
4192 	return Search(ike->IkeSaList, &t);
4193 }
4194 
4195 // Search an IKE SA from the Responder Cookie and the IKE_CLIENT
FindIkeSaByResponderCookieAndClient(IKE_SERVER * ike,UINT64 responder_cookie,IKE_CLIENT * c)4196 IKE_SA *FindIkeSaByResponderCookieAndClient(IKE_SERVER *ike, UINT64 responder_cookie, IKE_CLIENT *c)
4197 {
4198 	IKE_SA *sa;
4199 	// Validate arguments
4200 	if (ike == NULL || responder_cookie == 0 || c == NULL)
4201 	{
4202 		return NULL;
4203 	}
4204 
4205 	sa = FindIkeSaByResponderCookie(ike, responder_cookie);
4206 	if (sa == NULL)
4207 	{
4208 		return NULL;
4209 	}
4210 
4211 	if (sa->IkeClient != c)
4212 	{
4213 		return NULL;
4214 	}
4215 
4216 	return sa;
4217 }
4218 
4219 // Search an IKE SA from the endpoint and the Initiator Cookie
FindIkeSaByEndPointAndInitiatorCookie(IKE_SERVER * ike,IP * client_ip,UINT client_port,IP * server_ip,UINT server_port,UINT64 init_cookie,UINT mode)4220 IKE_SA *FindIkeSaByEndPointAndInitiatorCookie(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, UINT64 init_cookie, UINT mode)
4221 {
4222 	UINT i;
4223 	// Validate arguments
4224 	if (ike == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0 || init_cookie == 0)
4225 	{
4226 		return NULL;
4227 	}
4228 
4229 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
4230 	{
4231 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
4232 		IKE_CLIENT *c;
4233 
4234 		c = sa->IkeClient;
4235 
4236 		if (CmpIpAddr(&c->ClientIP, client_ip) == 0 &&
4237 			CmpIpAddr(&c->ServerIP, server_ip) == 0 &&
4238 			c->ClientPort == client_port &&
4239 			c->ServerPort == server_port &&
4240 			sa->InitiatorCookie == init_cookie &&
4241 			sa->Mode == mode)
4242 		{
4243 			return sa;
4244 		}
4245 	}
4246 
4247 	return NULL;
4248 }
4249 
4250 // Get the number of IPsec SA that is associated with the IKE_CLIENT
GetNumberOfIPsecSaOfIkeClient(IKE_SERVER * ike,IKE_CLIENT * c)4251 UINT GetNumberOfIPsecSaOfIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
4252 {
4253 	UINT num = 0, i;
4254 	// Validate arguments
4255 	if (ike == NULL || c == NULL)
4256 	{
4257 		return 0;
4258 	}
4259 
4260 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
4261 	{
4262 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
4263 
4264 		if (sa->IkeClient == c)
4265 		{
4266 			num++;
4267 		}
4268 	}
4269 
4270 	return num;
4271 }
4272 
4273 // Get the number of IKE SA that is associated with the IKE_CLIENT
GetNumberOfIkeSaOfIkeClient(IKE_SERVER * ike,IKE_CLIENT * c)4274 UINT GetNumberOfIkeSaOfIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
4275 {
4276 	UINT num = 0, i;
4277 	// Validate arguments
4278 	if (ike == NULL || c == NULL)
4279 	{
4280 		return 0;
4281 	}
4282 
4283 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
4284 	{
4285 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
4286 
4287 		if (sa->IkeClient == c)
4288 		{
4289 			num++;
4290 		}
4291 	}
4292 
4293 	return num;
4294 }
4295 
4296 // Get the number of clients that are connected from the specified IP address
GetNumberOfIkeClientsFromIP(IKE_SERVER * ike,IP * client_ip)4297 UINT GetNumberOfIkeClientsFromIP(IKE_SERVER *ike, IP *client_ip)
4298 {
4299 	UINT i, num;
4300 	// Validate arguments
4301 	if (ike == NULL || client_ip == NULL)
4302 	{
4303 		return 0;
4304 	}
4305 
4306 	num = 0;
4307 
4308 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
4309 	{
4310 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
4311 
4312 		if (CmpIpAddr(&c->ClientIP, client_ip) == 0)
4313 		{
4314 			num++;
4315 		}
4316 	}
4317 
4318 	return num;
4319 }
4320 
4321 // Find the appropriate IKE client. Create if it is absent
SearchOrCreateNewIkeClientForIkePacket(IKE_SERVER * ike,IP * client_ip,UINT client_port,IP * server_ip,UINT server_port,IKE_PACKET * pr)4322 IKE_CLIENT *SearchOrCreateNewIkeClientForIkePacket(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, IKE_PACKET *pr)
4323 {
4324 	IKE_CLIENT *c;
4325 	// Validate arguments
4326 	if (ike == NULL || pr == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0 || pr == NULL)
4327 	{
4328 		return NULL;
4329 	}
4330 
4331 	c = SearchIkeClientForIkePacket(ike, client_ip, client_port, server_ip, server_port, pr);
4332 	if (c == NULL)
4333 	{
4334 		if (GetNumberOfIkeClientsFromIP(ike, client_ip) > IKE_QUOTA_MAX_NUM_CLIENTS_PER_IP ||
4335 			LIST_NUM(ike->ClientList) > IKE_QUOTA_MAX_NUM_CLIENTS)
4336 		{
4337 			return NULL;
4338 		}
4339 
4340 
4341 		c = NewIkeClient(ike, client_ip, client_port, server_ip, server_port);
4342 
4343 		Insert(ike->ClientList, c);
4344 	}
4345 
4346 	return SetIkeClientEndpoint(ike, c, client_ip, client_port, server_ip, server_port);
4347 }
4348 
4349 // Create an IKE client
NewIkeClient(IKE_SERVER * ike,IP * client_ip,UINT client_port,IP * server_ip,UINT server_port)4350 IKE_CLIENT *NewIkeClient(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
4351 {
4352 	IKE_CLIENT *c;
4353 	char client_ip_str[MAX_SIZE];
4354 	char server_ip_str[MAX_SIZE];
4355 	// Validate arguments
4356 	if (ike == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
4357 	{
4358 		return NULL;
4359 	}
4360 
4361 	c = ZeroMalloc(sizeof(IKE_CLIENT));
4362 
4363 	c->Id = ++ike->CurrentIkeClientId;
4364 
4365 	Copy(&c->ClientIP, client_ip, sizeof(IP));
4366 	c->ClientPort = client_port;
4367 
4368 	Copy(&c->ServerIP, server_ip, sizeof(IP));
4369 	Copy(&c->TransportModeServerIP, server_ip, sizeof(IP));
4370 	Copy(&c->TransportModeClientIP, client_ip, sizeof(IP));
4371 	c->ServerPort = server_port;
4372 
4373 	c->LastCommTick = ike->Now;
4374 	c->FirstCommTick = ike->Now;
4375 
4376 	IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
4377 	IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
4378 
4379 	Debug("New IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, client_port, server_ip_str, server_port);
4380 
4381 	IPsecLog(ike, c, NULL, NULL, "LI_NEW_IKE_CLIENT");
4382 
4383 	return c;
4384 }
4385 
4386 // Search for the best associated IKE client when an IKE packet has been received
SearchIkeClientForIkePacket(IKE_SERVER * ike,IP * client_ip,UINT client_port,IP * server_ip,UINT server_port,IKE_PACKET * pr)4387 IKE_CLIENT *SearchIkeClientForIkePacket(IKE_SERVER *ike, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port, IKE_PACKET *pr)
4388 {
4389 	IKE_CLIENT t;
4390 	IKE_CLIENT *c = NULL;
4391 	// Validate arguments
4392 	if (ike == NULL || pr == NULL || client_ip == NULL || server_ip == NULL || client_port == 0 || server_port == 0)
4393 	{
4394 		return NULL;
4395 	}
4396 
4397 	if (true)
4398 	{
4399 		UINT i;
4400 
4401 		if (pr->InitiatorCookie != 0 && pr->ResponderCookie != 0)
4402 		{
4403 			for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
4404 			{
4405 				IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
4406 
4407 				// Extract what Cookie matches exactly
4408 				if (sa->InitiatorCookie == pr->InitiatorCookie && sa->ResponderCookie == pr->ResponderCookie)
4409 				{
4410 					IKE_CLIENT *cc = sa->IkeClient;
4411 
4412 					if (CmpIpAddr(&cc->ServerIP, server_ip) == 0 &&
4413 						CmpIpAddr(&cc->ClientIP, client_ip) == 0)
4414 					{
4415 						c = cc;
4416 						break;
4417 					}
4418 				}
4419 			}
4420 		}
4421 	}
4422 
4423 	if (c == NULL)
4424 	{
4425 		// Search by a pair of IP address and port number
4426 		Copy(&t.ClientIP, client_ip, sizeof(IP));
4427 		t.ClientPort = client_port;
4428 		Copy(&t.ServerIP, server_ip, sizeof(IP));
4429 		t.ServerPort = server_port;
4430 
4431 		c = Search(ike->ClientList, &t);
4432 
4433 		if (c != NULL)// && server_port == IPSEC_PORT_IPSEC_ISAKMP)
4434 		{
4435 			// Search that the IKE_SA that points to this IKE_CLIENT exists and match the Cookie
4436 			bool ok = false;
4437 			UINT i;
4438 
4439 			if (server_port == IPSEC_PORT_IPSEC_ESP_UDP)
4440 			{
4441 				// Regard as OK if the port number exactly match in the case of connecting to a server-side 4500
4442 				ok = true;
4443 			}
4444 			else
4445 			{
4446 				if (c->CurrentIkeSa != NULL &&
4447 					c->CurrentIkeSa->InitiatorCookie == pr->InitiatorCookie &&
4448 					c->CurrentIkeSa->ResponderCookie == pr->ResponderCookie)
4449 				{
4450 					ok = true;
4451 				}
4452 				else
4453 				{
4454 					for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
4455 					{
4456 						IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
4457 
4458 						if (sa->IkeClient == c)
4459 						{
4460 							if (sa->InitiatorCookie == pr->InitiatorCookie &&
4461 								sa->ResponderCookie == pr->ResponderCookie)
4462 							{
4463 								ok = true;
4464 								break;
4465 							}
4466 						}
4467 					}
4468 				}
4469 			}
4470 
4471 			if (ok == false)
4472 			{
4473 				// Not found
4474 				c = NULL;
4475 			}
4476 		}
4477 	}
4478 
4479 	return c;
4480 }
4481 
4482 // Comparison of IPsec SA
CmpIPsecSa(void * p1,void * p2)4483 int CmpIPsecSa(void *p1, void *p2)
4484 {
4485 	IPSECSA *sa1, *sa2;
4486 	int r;
4487 	// Validate arguments
4488 	if (p1 == NULL || p2 == NULL)
4489 	{
4490 		return 0;
4491 	}
4492 	sa1 = *(IPSECSA **)p1;
4493 	sa2 = *(IPSECSA **)p2;
4494 	if (sa1 == NULL || sa2 == NULL)
4495 	{
4496 		return 0;
4497 	}
4498 
4499 	r = COMPARE_RET(sa1->ServerToClient, sa2->ServerToClient);
4500 	if (r != 0)
4501 	{
4502 		return r;
4503 	}
4504 
4505 	r = COMPARE_RET(sa1->Spi, sa2->Spi);
4506 
4507 	return r;
4508 }
4509 
4510 // Comparison of IKE_SA
CmpIkeSa(void * p1,void * p2)4511 int CmpIkeSa(void *p1, void *p2)
4512 {
4513 	IKE_SA *sa1, *sa2;
4514 	int r;
4515 	// Validate arguments
4516 	if (p1 == NULL || p2 == NULL)
4517 	{
4518 		return 0;
4519 	}
4520 	sa1 = *(IKE_SA **)p1;
4521 	sa2 = *(IKE_SA **)p2;
4522 	if (sa1 == NULL || sa2 == NULL)
4523 	{
4524 		return 0;
4525 	}
4526 
4527 	r = COMPARE_RET(sa1->ResponderCookie, sa2->ResponderCookie);
4528 
4529 	return r;
4530 }
4531 
4532 // Comparison of IKE_CLIENT
CmpIkeClient(void * p1,void * p2)4533 int CmpIkeClient(void *p1, void *p2)
4534 {
4535 	IKE_CLIENT *c1, *c2;
4536 	int r;
4537 	// Validate arguments
4538 	if (p1 == NULL || p2 == NULL)
4539 	{
4540 		return 0;
4541 	}
4542 	c1 = *(IKE_CLIENT **)p1;
4543 	c2 = *(IKE_CLIENT **)p2;
4544 	if (c1 == NULL || c2 == NULL)
4545 	{
4546 		return 0;
4547 	}
4548 
4549 	r = CmpIpAddr(&c1->ClientIP, &c2->ClientIP);
4550 	if (r != 0)
4551 	{
4552 		return r;
4553 	}
4554 
4555 	r = CmpIpAddr(&c1->ServerIP, &c2->ServerIP);
4556 	if (r != 0)
4557 	{
4558 		return r;
4559 	}
4560 
4561 	r = COMPARE_RET(c1->ClientPort, c2->ClientPort);
4562 	if (r != 0)
4563 	{
4564 		return r;
4565 	}
4566 
4567 	r = COMPARE_RET(c1->ServerPort, c2->ServerPort);
4568 	if (r != 0)
4569 	{
4570 		return r;
4571 	}
4572 
4573 	return 0;
4574 }
4575 
4576 // Update the endpoint information of IKE_CLIENT
SetIkeClientEndpoint(IKE_SERVER * ike,IKE_CLIENT * c,IP * client_ip,UINT client_port,IP * server_ip,UINT server_port)4577 IKE_CLIENT *SetIkeClientEndpoint(IKE_SERVER *ike, IKE_CLIENT *c, IP *client_ip, UINT client_port, IP *server_ip, UINT server_port)
4578 {
4579 	char client_ip_str[MAX_SIZE];
4580 	char server_ip_str[MAX_SIZE];
4581 	IKE_CLIENT *ret = c;
4582 	IKE_CLIENT *cc;
4583 	IKE_CLIENT t;
4584 	// Validate arguments
4585 	if (ike == NULL || c == NULL || client_ip == NULL || client_port == 0 || server_ip == NULL || server_port == 0)
4586 	{
4587 		return NULL;
4588 	}
4589 
4590 	if (CmpIpAddr(&c->ClientIP, client_ip) == 0 &&
4591 		CmpIpAddr(&c->ServerIP, server_ip) == 0 &&
4592 		c->ClientPort == client_port &&
4593 		c->ServerPort == server_port)
4594 	{
4595 		// No change
4596 		return ret;
4597 	}
4598 
4599 	if (IS_SPECIAL_PORT(client_port) || IS_SPECIAL_PORT(server_port))
4600 	{
4601 		// Don't change in the case of Raw socket
4602 		return ret;
4603 	}
4604 
4605 	// Search for an existing IKE_CLIENT which exactly matches to combination of the new IP address and the port number
4606 	Copy(&t.ClientIP, client_ip, sizeof(IP));
4607 	t.ClientPort = client_port;
4608 	Copy(&t.ServerIP, server_ip, sizeof(IP));
4609 	t.ServerPort = server_port;
4610 
4611 	cc = Search(ike->ClientList, &t);
4612 	if (cc != NULL && c != cc && cc->Deleting == false && c->L2TP == NULL)
4613 	{
4614 		UINT i;
4615 		// Merge into this existing IKE_CLIENT since it found
4616 		for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
4617 		{
4618 			IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
4619 
4620 			if (sa->IkeClient == c)
4621 			{
4622 				sa->IkeClient = cc;
4623 			}
4624 		}
4625 		for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
4626 		{
4627 			IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
4628 
4629 			if (sa->IkeClient == c)
4630 			{
4631 				sa->IkeClient = cc;
4632 			}
4633 		}
4634 
4635 		if (cc->LastCommTick < c->LastCommTick)
4636 		{
4637 			StrCpy(cc->ClientId, sizeof(cc->ClientId), c->ClientId);
4638 		}
4639 
4640 		cc->FirstCommTick = MIN(cc->FirstCommTick, c->FirstCommTick);
4641 		cc->LastCommTick = MAX(cc->LastCommTick, c->LastCommTick);
4642 
4643 		ret = cc;
4644 
4645 		IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
4646 		IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
4647 
4648 		Debug("Merge IKE_CLIENT: %p->%p: %s:%u -> %s:%u\n", c, cc, client_ip_str, client_port, server_ip_str, server_port);
4649 
4650 		IPsecLog(ike, c, NULL, NULL, "LI_CLIENT_MERGE", c->Id, cc->Id, cc->Id);
4651 
4652 		// Remove old IKE_CLIENT from the list and free
4653 		Delete(ike->ClientList, c);
4654 		FreeIkeClient(ike, c);
4655 	}
4656 	else
4657 	{
4658 		// Rewrite the end point information of this IKE_CLIENT because not found
4659 		Copy(&c->ClientIP, client_ip, sizeof(IP));
4660 		Copy(&c->ServerIP, server_ip, sizeof(IP));
4661 		c->ClientPort = client_port;
4662 		c->ServerPort = server_port;
4663 
4664 		IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
4665 		IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
4666 
4667 		Debug("Update IKE_CLIENT: %p: %s:%u -> %s:%u\n", c, client_ip_str, client_port, server_ip_str, server_port);
4668 
4669 		IPsecLog(ike, c, NULL, NULL, "LI_CLIENT_UPDATE");
4670 
4671 		ike->ClientList->sorted = false;
4672 	}
4673 
4674 	return ret;
4675 }
4676 
4677 // Select the optimal transform setting for IPsec SA
GetBestTransformSettingForIPsecSa(IKE_SERVER * ike,IKE_PACKET * pr,IPSEC_SA_TRANSFORM_SETTING * setting,IP * server_ip)4678 bool GetBestTransformSettingForIPsecSa(IKE_SERVER *ike, IKE_PACKET *pr, IPSEC_SA_TRANSFORM_SETTING *setting, IP *server_ip)
4679 {
4680 	IKE_PACKET_PAYLOAD *sa_payload;
4681 	IKE_PACKET_SA_PAYLOAD *sa;
4682 	UINT i, num;
4683 	bool ocmii_flag = false;
4684 	// Validate arguments
4685 	if (ike == NULL || pr == NULL || setting == NULL || server_ip == NULL)
4686 	{
4687 		return false;
4688 	}
4689 
4690 	Zero(setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
4691 
4692 	// Get the SA payload
4693 	sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
4694 	if (sa_payload == NULL)
4695 	{
4696 		return false;
4697 	}
4698 
4699 	sa = &sa_payload->Payload.Sa;
4700 
4701 	// Scan all proposal payloads
4702 	num = IkeGetPayloadNum(sa->PayloadList, IKE_PAYLOAD_PROPOSAL);
4703 	for (i = 0;i < num;i++)
4704 	{
4705 		IKE_PACKET_PAYLOAD *proposal_payload = IkeGetPayload(sa->PayloadList, IKE_PAYLOAD_PROPOSAL, i);
4706 
4707 		if (proposal_payload != NULL)
4708 		{
4709 			IKE_PACKET_PROPOSAL_PAYLOAD *proposal = &proposal_payload->Payload.Proposal;
4710 
4711 			// Examine the contents of the proposal payload
4712 			if (proposal->ProtocolId == IKE_PROTOCOL_ID_IPSEC_ESP && proposal->Spi->Size == 4)
4713 			{
4714 				// Scan all transform payloads
4715 				UINT j, num2;
4716 
4717 				num2 = IkeGetPayloadNum(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM);
4718 				for (j = 0;j < num2;j++)
4719 				{
4720 					IKE_PACKET_PAYLOAD *transform_payload = IkeGetPayload(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM, j);
4721 					if (transform_payload != NULL)
4722 					{
4723 						IKE_PACKET_TRANSFORM_PAYLOAD *transform = &transform_payload->Payload.Transform;
4724 						IPSEC_SA_TRANSFORM_SETTING set;
4725 
4726 						Zero(&set, sizeof(set));
4727 
4728 						if (TransformPayloadToTransformSettingForIPsecSa(ike, transform, &set, server_ip))
4729 						{
4730 							Copy(setting, &set, sizeof(IPSEC_SA_TRANSFORM_SETTING));
4731 
4732 							setting->SpiServerToClient = READ_UINT(proposal->Spi->Buf);
4733 
4734 							return true;
4735 						}
4736 						else
4737 						{
4738 							if (set.OnlyCapsuleModeIsInvalid)
4739 							{
4740 								if (ocmii_flag == false)
4741 								{
4742 									Copy(setting, &set, sizeof(IPSEC_SA_TRANSFORM_SETTING));
4743 									ocmii_flag = true;
4744 								}
4745 							}
4746 						}
4747 					}
4748 				}
4749 			}
4750 		}
4751 	}
4752 
4753 	return false;
4754 }
4755 
4756 // Select the optimal transform settings for the IKE SA
GetBestTransformSettingForIkeSa(IKE_SERVER * ike,IKE_PACKET * pr,IKE_SA_TRANSFORM_SETTING * setting)4757 bool GetBestTransformSettingForIkeSa(IKE_SERVER *ike, IKE_PACKET *pr, IKE_SA_TRANSFORM_SETTING *setting)
4758 {
4759 	IKE_PACKET_PAYLOAD *sa_payload;
4760 	IKE_PACKET_SA_PAYLOAD *sa;
4761 	UINT i, num;
4762 	// Validate arguments
4763 	if (ike == NULL || pr == NULL || setting == NULL)
4764 	{
4765 		return false;
4766 	}
4767 
4768 	// Get the SA payload
4769 	sa_payload = IkeGetPayload(pr->PayloadList, IKE_PAYLOAD_SA, 0);
4770 	if (sa_payload == NULL)
4771 	{
4772 		return false;
4773 	}
4774 
4775 	sa = &sa_payload->Payload.Sa;
4776 
4777 	// Scan all proposal payloads
4778 	num = IkeGetPayloadNum(sa->PayloadList, IKE_PAYLOAD_PROPOSAL);
4779 	for (i = 0;i < num;i++)
4780 	{
4781 		IKE_PACKET_PAYLOAD *proposal_payload = IkeGetPayload(sa->PayloadList, IKE_PAYLOAD_PROPOSAL, i);
4782 
4783 		if (proposal_payload != NULL)
4784 		{
4785 			IKE_PACKET_PROPOSAL_PAYLOAD *proposal = &proposal_payload->Payload.Proposal;
4786 
4787 			// Examine the contents of the proposal payload
4788 			if (proposal->ProtocolId == IKE_PROTOCOL_ID_IKE)
4789 			{
4790 				// Scan all transform payloads
4791 				UINT j, num2;
4792 
4793 				num2 = IkeGetPayloadNum(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM);
4794 				for (j = 0;j < num2;j++)
4795 				{
4796 					IKE_PACKET_PAYLOAD *transform_payload = IkeGetPayload(proposal->PayloadList, IKE_PAYLOAD_TRANSFORM, j);
4797 					if (transform_payload != NULL)
4798 					{
4799 						IKE_PACKET_TRANSFORM_PAYLOAD *transform = &transform_payload->Payload.Transform;
4800 
4801 						if (transform->TransformId == IKE_TRANSFORM_ID_P1_KEY_IKE)
4802 						{
4803 							IKE_SA_TRANSFORM_SETTING set;
4804 
4805 							if (TransformPayloadToTransformSettingForIkeSa(ike, transform, &set))
4806 							{
4807 								Copy(setting, &set, sizeof(IKE_SA_TRANSFORM_SETTING));
4808 								return true;
4809 							}
4810 						}
4811 					}
4812 				}
4813 			}
4814 		}
4815 	}
4816 
4817 	return false;
4818 }
4819 
4820 // Convert a structure to the transform payload (for IPsec SA)
TransformSettingToTransformPayloadForIPsec(IKE_SERVER * ike,IPSEC_SA_TRANSFORM_SETTING * setting)4821 IKE_PACKET_PAYLOAD *TransformSettingToTransformPayloadForIPsec(IKE_SERVER *ike, IPSEC_SA_TRANSFORM_SETTING *setting)
4822 {
4823 	LIST *value_list;
4824 	// Validate arguments
4825 	if (ike == NULL || setting == NULL)
4826 	{
4827 		return NULL;
4828 	}
4829 
4830 	value_list = NewListFast(NULL);
4831 
4832 	Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_HMAC, setting->HashId));
4833 
4834 	if (setting->Dh != NULL)
4835 	{
4836 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_DH_GROUP, setting->DhId));
4837 	}
4838 
4839 	if (setting->LifeSeconds != INFINITE)
4840 	{
4841 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, IKE_P2_LIFE_TYPE_SECONDS));
4842 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, setting->LifeSeconds));
4843 	}
4844 
4845 	if (setting->LifeKilobytes != INFINITE)
4846 	{
4847 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, IKE_P2_LIFE_TYPE_KILOBYTES));
4848 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, setting->LifeKilobytes));
4849 	}
4850 
4851 	if (setting->Crypto->VariableKeySize)
4852 	{
4853 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_KEY_SIZE, setting->CryptoKeySize * 8));
4854 	}
4855 
4856 	Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P2_CAPSULE, setting->CapsuleMode));
4857 
4858 	return IkeNewTransformPayload(1, setting->CryptoId, value_list);
4859 }
4860 
4861 // Convert a structure to the transform payload (for IKE SA)
TransformSettingToTransformPayloadForIke(IKE_SERVER * ike,IKE_SA_TRANSFORM_SETTING * setting)4862 IKE_PACKET_PAYLOAD *TransformSettingToTransformPayloadForIke(IKE_SERVER *ike, IKE_SA_TRANSFORM_SETTING *setting)
4863 {
4864 	LIST *value_list;
4865 	// Validate arguments
4866 	if (ike == NULL || setting == NULL)
4867 	{
4868 		return NULL;
4869 	}
4870 
4871 	value_list = NewListFast(NULL);
4872 
4873 	Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_CRYPTO, setting->CryptoId));
4874 	Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_HASH, setting->HashId));
4875 	Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_AUTH_METHOD, IKE_P1_AUTH_METHOD_PRESHAREDKEY));
4876 	Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_DH_GROUP, setting->DhId));
4877 
4878 	if (setting->LifeSeconds != INFINITE)
4879 	{
4880 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, IKE_P1_LIFE_TYPE_SECONDS));
4881 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, setting->LifeSeconds));
4882 	}
4883 
4884 	if (setting->LifeKilobytes != INFINITE)
4885 	{
4886 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, IKE_P1_LIFE_TYPE_KILOBYTES));
4887 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, setting->LifeKilobytes));
4888 	}
4889 
4890 	if (setting->Crypto->VariableKeySize)
4891 	{
4892 		Add(value_list, IkeNewTransformValue(IKE_TRANSFORM_VALUE_P1_KET_SIZE, setting->CryptoKeySize * 8));
4893 	}
4894 
4895 	return IkeNewTransformPayload(1, IKE_TRANSFORM_ID_P1_KEY_IKE, value_list);
4896 }
4897 
4898 // Convert a transform payload to a structure (for IPsec SA)
TransformPayloadToTransformSettingForIPsecSa(IKE_SERVER * ike,IKE_PACKET_TRANSFORM_PAYLOAD * transform,IPSEC_SA_TRANSFORM_SETTING * setting,IP * server_ip)4899 bool TransformPayloadToTransformSettingForIPsecSa(IKE_SERVER *ike, IKE_PACKET_TRANSFORM_PAYLOAD *transform, IPSEC_SA_TRANSFORM_SETTING *setting, IP *server_ip)
4900 {
4901 	UINT i;
4902 	UINT capsule_mode;
4903 	bool is_esp_supported;
4904 	// Validate arguments
4905 	if (ike == NULL || transform == NULL || setting == NULL || server_ip == NULL)
4906 	{
4907 		return false;
4908 	}
4909 
4910 	is_esp_supported = IsUdpPortOpened(ike->IPsec->UdpListener, server_ip, IPSEC_PORT_IPSEC_ESP_RAW);
4911 
4912 	Zero(setting, sizeof(IPSEC_SA_TRANSFORM_SETTING));
4913 
4914 	setting->CryptoId = transform->TransformId;
4915 	setting->HashId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_HMAC, 0);
4916 
4917 	setting->DhId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_DH_GROUP, 0);
4918 
4919 	setting->LifeKilobytes = INFINITE;
4920 	setting->LifeSeconds = INFINITE;
4921 
4922 	for (i = 0;i < IkeGetTransformValueNum(transform, IKE_TRANSFORM_VALUE_P2_LIFE_TYPE);i++)
4923 	{
4924 		UINT life_type = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_TYPE, i);
4925 
4926 		switch (life_type)
4927 		{
4928 		case IKE_P2_LIFE_TYPE_SECONDS:		// Number of seconds
4929 			setting->LifeSeconds = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, i);
4930 			break;
4931 
4932 		case IKE_P2_LIFE_TYPE_KILOBYTES:	// Kilobytes
4933 			setting->LifeKilobytes = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_LIFE_VALUE, i);
4934 			break;
4935 
4936 		default:
4937 			// Unsupported expiration type
4938 			return false;
4939 		}
4940 	}
4941 
4942 	setting->Crypto = GetIkeCrypto(ike->Engine, true, setting->CryptoId);
4943 	setting->Hash = GetIkeHash(ike->Engine, true, setting->HashId);
4944 	setting->Dh = GetIkeDh(ike->Engine, true, setting->DhId);
4945 
4946 	if (setting->Crypto == NULL || setting->Hash == NULL)
4947 	{
4948 		// Unsupported algorithm
4949 		return false;
4950 	}
4951 
4952 	if (setting->Crypto->VariableKeySize)
4953 	{
4954 		// Get the actual key size in the case of variable key size
4955 		setting->CryptoKeySize = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_KEY_SIZE, 0);
4956 
4957 		// bits -> bytes
4958 		setting->CryptoKeySize = setting->CryptoKeySize / 8;
4959 
4960 		if (setting->CryptoKeySize == 0 || IkeCheckKeySize(setting->Crypto, setting->CryptoKeySize) == false)
4961 		{
4962 			// The key size is not specified or inappropriate
4963 			return false;
4964 		}
4965 	}
4966 	else
4967 	{
4968 		// Get a fixed key length for fixed key size
4969 		setting->CryptoKeySize = setting->Crypto->KeySizes[0];
4970 	}
4971 
4972 	capsule_mode = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P2_CAPSULE, 0);
4973 	if (capsule_mode != IKE_P2_CAPSULE_NAT_TUNNEL_1 && capsule_mode != IKE_P2_CAPSULE_NAT_TUNNEL_2 &&
4974 		capsule_mode != IKE_P2_CAPSULE_NAT_TRANSPORT_1 && capsule_mode != IKE_P2_CAPSULE_NAT_TRANSPORT_2)
4975 	{
4976 		// No support for UDP encapsulation mode except for the NAT-Traversal
4977 		if (capsule_mode == IKE_P2_CAPSULE_TRANSPORT || capsule_mode == IKE_P2_CAPSULE_TUNNEL)
4978 		{
4979 			if (is_esp_supported == false)
4980 			{
4981 				setting->OnlyCapsuleModeIsInvalid = true;
4982 				return false;
4983 			}
4984 			else
4985 			{
4986 				// It is an environment that can send and receive ESP packets
4987 			}
4988 		}
4989 		else
4990 		{
4991 			return false;
4992 		}
4993 	}
4994 
4995 	setting->CapsuleMode = capsule_mode;
4996 
4997 	return true;
4998 }
4999 
5000 // Convert a transform payload to a structure (for IKE SA)
TransformPayloadToTransformSettingForIkeSa(IKE_SERVER * ike,IKE_PACKET_TRANSFORM_PAYLOAD * transform,IKE_SA_TRANSFORM_SETTING * setting)5001 bool TransformPayloadToTransformSettingForIkeSa(IKE_SERVER *ike, IKE_PACKET_TRANSFORM_PAYLOAD *transform, IKE_SA_TRANSFORM_SETTING *setting)
5002 {
5003 	UINT i;
5004 	// Validate arguments
5005 	if (ike == NULL || transform == NULL || setting == NULL)
5006 	{
5007 		return false;
5008 	}
5009 
5010 	Zero(setting, sizeof(IKE_SA_TRANSFORM_SETTING));
5011 
5012 	setting->CryptoId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_CRYPTO, 0);
5013 	setting->HashId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_HASH, 0);
5014 
5015 	if (IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_AUTH_METHOD, 0) != IKE_P1_AUTH_METHOD_PRESHAREDKEY)
5016 	{
5017 		// Only PSK authentication method is supported
5018 		return false;
5019 	}
5020 
5021 	setting->DhId = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_DH_GROUP, 0);
5022 
5023 	setting->LifeKilobytes = INFINITE;
5024 	setting->LifeSeconds = INFINITE;
5025 
5026 	for (i = 0;i < IkeGetTransformValueNum(transform, IKE_TRANSFORM_VALUE_P1_LIFE_TYPE);i++)
5027 	{
5028 		UINT life_type = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_TYPE, i);
5029 
5030 		switch (life_type)
5031 		{
5032 		case IKE_P1_LIFE_TYPE_SECONDS:		// Number of seconds
5033 			setting->LifeSeconds = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, i);
5034 			break;
5035 
5036 		case IKE_P1_LIFE_TYPE_KILOBYTES:	// Kilobytes
5037 			setting->LifeKilobytes = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_LIFE_VALUE, i);
5038 			break;
5039 
5040 		default:
5041 			// Unsupported expiration type
5042 			return false;
5043 		}
5044 	}
5045 
5046 	setting->Crypto = GetIkeCrypto(ike->Engine, false, setting->CryptoId);
5047 	setting->Hash = GetIkeHash(ike->Engine, false, setting->HashId);
5048 	setting->Dh = GetIkeDh(ike->Engine, false, setting->DhId);
5049 
5050 	if (setting->Crypto == NULL || setting->Hash == NULL || setting->Dh == NULL)
5051 	{
5052 		// Unsupported algorithm
5053 		return false;
5054 	}
5055 
5056 	if (setting->Crypto->VariableKeySize)
5057 	{
5058 		// Get the actual key size in the case of variable key size
5059 		setting->CryptoKeySize = IkeGetTransformValue(transform, IKE_TRANSFORM_VALUE_P1_KET_SIZE, 0);
5060 
5061 		// bits -> bytes
5062 		setting->CryptoKeySize = setting->CryptoKeySize / 8;
5063 
5064 		if (setting->CryptoKeySize == 0 || IkeCheckKeySize(setting->Crypto, setting->CryptoKeySize) == false)
5065 		{
5066 			// The key size is not specified or inappropriate
5067 			return false;
5068 		}
5069 	}
5070 	else
5071 	{
5072 		// Get a fixed key length for fixed key size
5073 		setting->CryptoKeySize = setting->Crypto->KeySizes[0];
5074 	}
5075 
5076 	return true;
5077 }
5078 
5079 // Creating a new Responder Cookie
GenerateNewResponserCookie(IKE_SERVER * ike)5080 UINT64 GenerateNewResponserCookie(IKE_SERVER *ike)
5081 {
5082 	UINT64 c;
5083 	// Validate arguments
5084 	if (ike == NULL)
5085 	{
5086 		return 0;
5087 	}
5088 
5089 	while (true)
5090 	{
5091 		bool b = false;
5092 		UINT i;
5093 
5094 		c = Rand64();
5095 
5096 		for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
5097 		{
5098 			IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
5099 
5100 			if (sa->ResponderCookie == c)
5101 			{
5102 				b = true;
5103 				break;
5104 			}
5105 		}
5106 
5107 		if (b == false)
5108 		{
5109 			return c;
5110 		}
5111 	}
5112 }
5113 
5114 // Parse the IKE packet header
ParseIKEPacketHeader(UDPPACKET * p)5115 IKE_PACKET *ParseIKEPacketHeader(UDPPACKET *p)
5116 {
5117 	// Validate arguments
5118 	if (p == NULL)
5119 	{
5120 		return NULL;
5121 	}
5122 
5123 	return IkeParseHeader(p->Data, p->Size, NULL);
5124 }
5125 
5126 // Search for another IPsec SA belonging to the IKE_CLIENT which have same conditions to the specified IPsec SA
GetOtherLatestIPsecSa(IKE_SERVER * ike,IPSECSA * sa)5127 IPSECSA *GetOtherLatestIPsecSa(IKE_SERVER *ike, IPSECSA *sa)
5128 {
5129 	UINT i;
5130 	UINT64 min_value = 0;
5131 	IPSECSA *max_sa = NULL;
5132 	// Validate arguments
5133 	if (ike == NULL || sa == NULL)
5134 	{
5135 		return NULL;
5136 	}
5137 
5138 	if (sa->IkeClient == NULL)
5139 	{
5140 		return NULL;
5141 	}
5142 
5143 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5144 	{
5145 		IPSECSA *sa2 = LIST_DATA(ike->IPsecSaList, i);
5146 
5147 		if (sa2 != sa)
5148 		{
5149 			if (sa2->IkeClient == sa->IkeClient)
5150 			{
5151 				if (sa2->ServerToClient == sa->ServerToClient)
5152 				{
5153 					if (sa2->Deleting == false)
5154 					{
5155 						if (sa2->Established)
5156 						{
5157 							UINT64 last_comm_tick = sa2->LastCommTick;
5158 
5159 							if (sa2->ServerToClient)
5160 							{
5161 								if (sa2->PairIPsecSa != NULL)
5162 								{
5163 									last_comm_tick = sa2->PairIPsecSa->LastCommTick;
5164 								}
5165 							}
5166 
5167 							if (min_value < last_comm_tick)
5168 							{
5169 								min_value = last_comm_tick;
5170 
5171 								max_sa = sa2;
5172 							}
5173 						}
5174 					}
5175 				}
5176 			}
5177 		}
5178 	}
5179 
5180 	return max_sa;
5181 }
5182 
5183 // Search for another IKE_SA belonging to the IKE_CLIENT which have same conditions to the specified IKE_SA
GetOtherLatestIkeSa(IKE_SERVER * ike,IKE_SA * sa)5184 IKE_SA *GetOtherLatestIkeSa(IKE_SERVER *ike, IKE_SA *sa)
5185 {
5186 	UINT i;
5187 	UINT64 min_value = 0;
5188 	IKE_SA *max_sa = NULL;
5189 	// Validate arguments
5190 	if (ike == NULL || sa == NULL)
5191 	{
5192 		return NULL;
5193 	}
5194 
5195 	if (sa->IkeClient == NULL)
5196 	{
5197 		return NULL;
5198 	}
5199 
5200 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
5201 	{
5202 		IKE_SA *sa2 = LIST_DATA(ike->IkeSaList, i);
5203 
5204 		if (sa2 != sa)
5205 		{
5206 			if (sa2->IkeClient == sa->IkeClient)
5207 			{
5208 				if (sa2->Deleting == false)
5209 				{
5210 					if (sa2->Established)
5211 					{
5212 						if (min_value < sa2->LastCommTick)
5213 						{
5214 							min_value = sa2->LastCommTick;
5215 
5216 							max_sa = sa2;
5217 						}
5218 					}
5219 				}
5220 			}
5221 		}
5222 	}
5223 
5224 	return max_sa;
5225 }
5226 
5227 // Purge the IPsec SA
PurgeIPsecSa(IKE_SERVER * ike,IPSECSA * sa)5228 void PurgeIPsecSa(IKE_SERVER *ike, IPSECSA *sa)
5229 {
5230 	UINT i;
5231 	IPSECSA *other_sa;
5232 	// Validate arguments
5233 	if (ike == NULL || sa == NULL)
5234 	{
5235 		return;
5236 	}
5237 
5238 	other_sa = GetOtherLatestIPsecSa(ike, sa);
5239 
5240 	// Rewrite the pairing partner by looking for IPsec SA that are paired
5241 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5242 	{
5243 		IPSECSA *sa2 = LIST_DATA(ike->IPsecSaList, i);
5244 
5245 		if (sa2->PairIPsecSa == sa)
5246 		{
5247 			sa2->PairIPsecSa = other_sa;
5248 		}
5249 	}
5250 
5251 	// Rewrite the IKE_CLIENT using this IPsec SA to use alternate
5252 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
5253 	{
5254 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
5255 
5256 		if (c->CurrentIpSecSaRecv == sa)
5257 		{
5258 			c->CurrentIpSecSaRecv = other_sa;
5259 		}
5260 
5261 		if (c->CurrentIpSecSaSend == sa)
5262 		{
5263 			c->CurrentIpSecSaSend = other_sa;
5264 		}
5265 	}
5266 
5267 	Delete(ike->IPsecSaList, sa);
5268 	FreeIPsecSa(sa);
5269 }
5270 
5271 // Remove the IKE SA
PurgeIkeSa(IKE_SERVER * ike,IKE_SA * sa)5272 void PurgeIkeSa(IKE_SERVER *ike, IKE_SA *sa)
5273 {
5274 	IKE_SA *other_sa;
5275 	UINT i;
5276 	// Validate arguments
5277 	if (ike == NULL || sa == NULL)
5278 	{
5279 		return;
5280 	}
5281 
5282 	Debug("Purging IKE SA %I64u-%I64u\n", sa->InitiatorCookie, sa->ResponderCookie);
5283 
5284 	// Rewrite to alternative IKE_SA of all IPsec SA that are using this IKE_SA
5285 	other_sa = GetOtherLatestIkeSa(ike, sa);
5286 
5287 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5288 	{
5289 		IPSECSA *ipsec_sa = LIST_DATA(ike->IPsecSaList, i);
5290 
5291 		if (ipsec_sa->IkeSa == sa)
5292 		{
5293 			if (other_sa == NULL)
5294 			{
5295 				// Remove this IPsec SA because there is no alternative IKE_SA
5296 				Debug("  Deleting IPsec SA 0x%X of this IKE SA (no alternatives)\n", ipsec_sa->Spi);
5297 				MarkIPsecSaAsDeleted(ike, ipsec_sa);
5298 				ipsec_sa->IkeSa = NULL;
5299 			}
5300 			else
5301 			{
5302 				// Replace to the alternative IKE_SA
5303 				Debug("  Replacing IKE SA of IPsec SA 0x%X from %I64u-%I64u to %I64u-%I64u\n", ipsec_sa->Spi,
5304 					sa->InitiatorCookie, sa->ResponderCookie,
5305 					other_sa->InitiatorCookie, other_sa->ResponderCookie);
5306 				ipsec_sa->IkeSa = other_sa;
5307 			}
5308 		}
5309 	}
5310 
5311 	// Substitute the IKE_SA of all IKE_CLIENT that are using this IKE_SA with alternative
5312 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
5313 	{
5314 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
5315 
5316 		if (c->CurrentIkeSa == sa)
5317 		{
5318 			c->CurrentIkeSa = other_sa;
5319 		}
5320 	}
5321 
5322 	Delete(ike->IkeSaList, sa);
5323 	FreeIkeSa(sa);
5324 }
5325 
5326 // Purge the IKE_CLIENT
PurgeIkeClient(IKE_SERVER * ike,IKE_CLIENT * c)5327 void PurgeIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
5328 {
5329 	UINT i;
5330 	// Validate arguments
5331 	if (ike == NULL || c == NULL)
5332 	{
5333 		return;
5334 	}
5335 
5336 	// Delete all of IPsec SA and IKE SA that belong to this IKE Client
5337 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
5338 	{
5339 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
5340 
5341 		if (sa->IkeClient == c)
5342 		{
5343 			MarkIkeSaAsDeleted(ike, sa);
5344 		}
5345 	}
5346 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5347 	{
5348 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
5349 
5350 		if (sa->IkeClient == c)
5351 		{
5352 			MarkIPsecSaAsDeleted(ike, sa);
5353 		}
5354 	}
5355 
5356 	Delete(ike->ClientList, c);
5357 	FreeIkeClient(ike, c);
5358 }
5359 
5360 // Remove the SA that has been marked to delete
PurgeDeletingSAsAndClients(IKE_SERVER * ike)5361 void PurgeDeletingSAsAndClients(IKE_SERVER *ike)
5362 {
5363 	UINT i;
5364 	LIST *o = NULL;
5365 	// Validate arguments
5366 	if (ike == NULL)
5367 	{
5368 		return;
5369 	}
5370 
5371 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
5372 	{
5373 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
5374 		if (sa->Deleting)
5375 		{
5376 			if (o == NULL)
5377 			{
5378 				o = NewListFast(NULL);
5379 			}
5380 
5381 			Add(o, sa);
5382 		}
5383 	}
5384 
5385 	for (i = 0;i < LIST_NUM(o);i++)
5386 	{
5387 		IKE_SA *sa = LIST_DATA(o, i);
5388 
5389 		PurgeIkeSa(ike, sa);
5390 	}
5391 
5392 	ReleaseList(o);
5393 
5394 	o = NULL;
5395 
5396 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5397 	{
5398 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
5399 		if (sa->Deleting)
5400 		{
5401 			if (o == NULL)
5402 			{
5403 				o = NewListFast(NULL);
5404 			}
5405 
5406 			Add(o, sa);
5407 		}
5408 	}
5409 
5410 	for (i = 0;i < LIST_NUM(o);i++)
5411 	{
5412 		IPSECSA *sa = LIST_DATA(o, i);
5413 
5414 		PurgeIPsecSa(ike, sa);
5415 	}
5416 
5417 	ReleaseList(o);
5418 
5419 	o = NULL;
5420 
5421 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
5422 	{
5423 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
5424 		if (c->Deleting)
5425 		{
5426 			if (o == NULL)
5427 			{
5428 				o = NewListFast(NULL);
5429 			}
5430 
5431 			Add(o, c);
5432 		}
5433 	}
5434 
5435 	for (i = 0;i < LIST_NUM(o);i++)
5436 	{
5437 		IKE_CLIENT *c = LIST_DATA(o, i);
5438 
5439 		PurgeIkeClient(ike, c);
5440 	}
5441 
5442 	ReleaseList(o);
5443 }
5444 
5445 // IKE interrupt process
ProcessIKEInterrupts(IKE_SERVER * ike)5446 void ProcessIKEInterrupts(IKE_SERVER *ike)
5447 {
5448 	UINT i;
5449 	// Validate arguments
5450 	if (ike == NULL)
5451 	{
5452 		return;
5453 	}
5454 
5455 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
5456 	{
5457 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
5458 
5459 		c->CurrentExpiresSoftTick_CtoS = 0;
5460 		c->CurrentExpiresSoftTick_StoC = 0;
5461 		c->CurrentNumEstablishedIPsecSA_CtoS = 0;
5462 		c->CurrentNumEstablishedIPsecSA_StoC = 0;
5463 		c->CurrentNumHealtyIPsecSA_CtoS = 0;
5464 		c->CurrentNumHealtyIPsecSA_StoC = 0;
5465 	}
5466 
5467 	// Packet retransmission by scanning all IKE SA
5468 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
5469 	{
5470 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
5471 
5472 		if (sa->SendBuffer != NULL)
5473 		{
5474 			if (ike->Now >= sa->NextSendTick)
5475 			{
5476 				IKE_CLIENT *c = sa->IkeClient;
5477 
5478 				IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort,
5479 					Clone(sa->SendBuffer->Buf, sa->SendBuffer->Size), sa->SendBuffer->Size);
5480 
5481 				sa->NextSendTick += (UINT64)(IKE_SA_RESEND_INTERVAL);
5482 
5483 				AddInterrupt(ike->Interrupts, sa->NextSendTick);
5484 
5485 				if (sa->NumResends != 0)
5486 				{
5487 					sa->NumResends--;
5488 					if (sa->NumResends == 0)
5489 					{
5490 						sa->NextSendTick = 0;
5491 						FreeBuf(sa->SendBuffer);
5492 						sa->SendBuffer = NULL;
5493 					}
5494 				}
5495 			}
5496 		}
5497 
5498 		// Remove those of non-communication
5499 		if (sa->IkeClient == NULL || (sa->IkeClient->CurrentIkeSa != sa))
5500 		{
5501 			// When the IKE_CLIENT don't point this
5502 			if (sa->Established == false)
5503 			{
5504 				// Make time-out in a short time when it is not established
5505 				if ((sa->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now)
5506 				{
5507 					WHERE;
5508 					MarkIkeSaAsDeleted(ike, sa);
5509 				}
5510 			}
5511 			else
5512 			{
5513 				// Timeout in a long time in the case of established
5514 				if ((sa->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now)
5515 				{
5516 					WHERE;
5517 					MarkIkeSaAsDeleted(ike, sa);
5518 				}
5519 			}
5520 		}
5521 	}
5522 
5523 	// Packet retransmission by scanning all IPsec SA
5524 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5525 	{
5526 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
5527 		IKE_CLIENT *c = sa->IkeClient;
5528 
5529 		if (sa->SendBuffer != NULL)
5530 		{
5531 			if (ike->Now >= sa->NextSendTick)
5532 			{
5533 				IKE_CLIENT *c = sa->IkeClient;
5534 
5535 				IkeSendUdpPacket(ike, IKE_UDP_TYPE_ISAKMP, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort,
5536 					Clone(sa->SendBuffer->Buf, sa->SendBuffer->Size), sa->SendBuffer->Size);
5537 
5538 				sa->NextSendTick += (UINT64)(IKE_SA_RESEND_INTERVAL);
5539 
5540 				AddInterrupt(ike->Interrupts, sa->NextSendTick);
5541 
5542 				if (sa->NumResends != 0)
5543 				{
5544 					sa->NumResends--;
5545 
5546 					if (sa->NumResends == 0)
5547 					{
5548 						sa->NextSendTick = 0;
5549 						FreeBuf(sa->SendBuffer);
5550 						sa->SendBuffer = NULL;
5551 					}
5552 				}
5553 			}
5554 		}
5555 
5556 		if (sa->Established && sa->Deleting == false && c != NULL)
5557 		{
5558 			// Get the flexible expiration date of SA for each IKE_CLIENT
5559 			if (sa->ServerToClient)
5560 			{
5561 				c->CurrentExpiresSoftTick_StoC = MAX(c->CurrentExpiresSoftTick_StoC, sa->ExpiresSoftTick);
5562 				c->CurrentNumEstablishedIPsecSA_StoC++;
5563 
5564 				if (sa->ExpiresSoftTick == 0 || sa->ExpiresSoftTick > ike->Now)
5565 				{
5566 					c->CurrentNumHealtyIPsecSA_StoC++;
5567 				}
5568 			}
5569 			else
5570 			{
5571 				c->CurrentExpiresSoftTick_CtoS = MAX(c->CurrentExpiresSoftTick_CtoS, sa->ExpiresSoftTick);
5572 				c->CurrentNumEstablishedIPsecSA_CtoS++;
5573 
5574 				if (sa->ExpiresSoftTick == 0 || sa->ExpiresSoftTick > ike->Now)
5575 				{
5576 					c->CurrentNumHealtyIPsecSA_CtoS++;
5577 				}
5578 			}
5579 		}
5580 
5581 		// Remove those of non-communication
5582 		if (sa->IkeClient == NULL || (sa->IkeClient->CurrentIpSecSaRecv != sa && sa->IkeClient->CurrentIpSecSaSend != sa))
5583 		{
5584 			// When the IKE_CLIENT don't point this
5585 			UINT64 last_comm_tick = sa->LastCommTick;
5586 
5587 			if (sa->ServerToClient && sa->PairIPsecSa != NULL)
5588 			{
5589 				last_comm_tick = sa->PairIPsecSa->LastCommTick;
5590 			}
5591 
5592 			if (sa->Established == false)
5593 			{
5594 				// Make time-out in a short time when it is not established
5595 				if ((last_comm_tick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now)
5596 				{
5597 					WHERE;
5598 					MarkIPsecSaAsDeleted(ike, sa);
5599 				}
5600 			}
5601 			else
5602 			{
5603 				// Timeout in a long time in the case of established
5604 				if ((last_comm_tick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now)
5605 				{
5606 					WHERE;
5607 					MarkIPsecSaAsDeleted(ike, sa);
5608 				}
5609 			}
5610 		}
5611 	}
5612 
5613 	// IKE_CLIENT scanning process
5614 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
5615 	{
5616 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
5617 		UINT64 tick;
5618 		UCHAR data[1];
5619 		bool need_qm = false;
5620 		bool need_qm_hard = false;
5621 		UINT64 qm_soft_tick = 0;
5622 
5623 		// Determine whether it is necessary to start a new Quick Mode
5624 		if (c->CurrentExpiresSoftTick_StoC != 0 && ike->Now >= c->CurrentExpiresSoftTick_StoC)
5625 		{
5626 			need_qm = true;
5627 			qm_soft_tick = MAX(qm_soft_tick, c->CurrentExpiresSoftTick_StoC);
5628 		}
5629 
5630 		if (c->CurrentExpiresSoftTick_CtoS != 0 && ike->Now >= c->CurrentExpiresSoftTick_CtoS)
5631 		{
5632 			need_qm = true;
5633 			qm_soft_tick = MAX(qm_soft_tick, c->CurrentExpiresSoftTick_StoC);
5634 		}
5635 
5636 		if (c->CurrentNumHealtyIPsecSA_CtoS == 0 || c->CurrentNumHealtyIPsecSA_StoC == 0)
5637 		{
5638 			need_qm = true;
5639 			need_qm_hard = true;
5640 		}
5641 
5642 		if (c->StartQuickModeAsSoon)
5643 		{
5644 			need_qm = true;
5645 			need_qm_hard = true;
5646 		}
5647 
5648 		if (c->Deleting || c->CurrentIkeSa == NULL || c->CurrentIkeSa->Deleting)
5649 		{
5650 			need_qm = false;
5651 			need_qm_hard = true;
5652 		}
5653 
5654 		if (need_qm)
5655 		{
5656 			if (c->StartQuickModeAsSoon || ((c->LastQuickModeStartTick + (UINT64)IKE_QUICKMODE_START_INTERVAL) <= ike->Now))
5657 			{
5658 				// Start the Quick Mode
5659 				Debug("IKE_CLIENT 0x%X: Begin QuickMode\n", c);
5660 				c->StartQuickModeAsSoon = false;
5661 				c->LastQuickModeStartTick = ike->Now;
5662 
5663 				AddInterrupt(ike->Interrupts, c->LastQuickModeStartTick + (UINT64)IKE_QUICKMODE_START_INTERVAL);
5664 
5665 				StartQuickMode(ike, c);
5666 			}
5667 		}
5668 
5669 		if (need_qm_hard)
5670 		{
5671 			if (c->NeedQmBeginTick == 0)
5672 			{
5673 				c->NeedQmBeginTick = ike->Now;
5674 			}
5675 		}
5676 		else
5677 		{
5678 			c->NeedQmBeginTick = 0;
5679 		}
5680 
5681 		if (((c->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT) <= ike->Now) ||
5682 			((c->CurrentIkeSa == NULL && c->CurrentIpSecSaRecv == NULL && c->CurrentIpSecSaSend == NULL) && (c->LastCommTick + (UINT64)IKE_TIMEOUT_FOR_IKE_CLIENT_FOR_NOT_ESTABLISHED) <= ike->Now) ||
5683 			(c->NeedQmBeginTick != 0 && ((c->NeedQmBeginTick + (UINT64)IKE_QUICKMODE_FAILED_TIMEOUT) <= ike->Now)))
5684 		{
5685 			// Remove IKE_CLIENT not communicating for a certain period of time
5686 			WHERE;
5687 			MarkIkeClientAsDeleted(ike, c);
5688 		}
5689 
5690 		// L2TP processing
5691 		if (c->L2TP != NULL)
5692 		{
5693 			IPsecIkeClientManageL2TPServer(ike, c);
5694 
5695 			// Interrupt processing occurs
5696 			L2TPProcessInterrupts(c->L2TP);
5697 
5698 			// Packet transmission
5699 			IPsecIkeClientSendL2TPPackets(ike, c, c->L2TP);
5700 		}
5701 
5702 		// EtherIP processing
5703 		if (c->EtherIP != NULL)
5704 		{
5705 			IPsecIkeClientManageEtherIPServer(ike, c);
5706 
5707 			// Interrupt processing occurs
5708 			EtherIPProcInterrupts(c->EtherIP);
5709 
5710 			// Packet transmission
5711 			IPsecIkeClientSendEtherIPPackets(ike, c, c->EtherIP);
5712 		}
5713 
5714 		// KeepAlive transmission
5715 		tick = MAX(c->LastCommTick + (UINT64)IKE_INTERVAL_UDP_KEEPALIVE, c->NextKeepAliveSendTick);
5716 
5717 		if (tick <= ike->Now && c->ServerPort == IPSEC_PORT_IPSEC_ESP_UDP)
5718 		{
5719 			c->NextKeepAliveSendTick = ike->Now + (UINT64)IKE_INTERVAL_UDP_KEEPALIVE;
5720 
5721 			AddInterrupt(ike->Interrupts, c->NextKeepAliveSendTick);
5722 
5723 			Zero(data, sizeof(data));
5724 			data[0] = 0xff;
5725 
5726 			IkeSendUdpPacket(ike, IKE_UDP_KEEPALIVE, &c->ServerIP, c->ServerPort, &c->ClientIP, c->ClientPort, Clone(data, sizeof(data)), sizeof(data));
5727 		}
5728 
5729 		// DPD transmission
5730 		if (c->NextDpdSendTick == 0 || c->NextDpdSendTick <= ike->Now)
5731 		{
5732 			if (c->CurrentIkeSa != NULL && c->CurrentIkeSa->Established)
5733 			{
5734 				if (c->CurrentIkeSa->Caps.DpdRfc3706)
5735 				{
5736 					c->NextDpdSendTick = ike->Now + (UINT64)IKE_INTERVAL_DPD_KEEPALIVE;
5737 
5738 					AddInterrupt(ike->Interrupts, c->NextDpdSendTick);
5739 
5740 					SendInformationalExchangePacket(ike, c,
5741 						IkeNewNoticeDpdPayload(false, c->CurrentIkeSa->InitiatorCookie, c->CurrentIkeSa->ResponderCookie,
5742 						c->DpdSeqNo++));
5743 				}
5744 			}
5745 		}
5746 	}
5747 
5748 	do
5749 	{
5750 		ike->StateHasChanged = false;
5751 
5752 		// Deletion process
5753 		PurgeDeletingSAsAndClients(ike);
5754 	}
5755 	while (ike->StateHasChanged);
5756 
5757 	// Maintenance of the thread list
5758 	MainteThreadList(ike->ThreadList);
5759 	/*Debug("ike->ThreadList: %u\n", LIST_NUM(ike->ThreadList));
5760 	{
5761 		UINT i;
5762 		for (i = 0;i < LIST_NUM(ike->ThreadList);i++)
5763 		{
5764 			THREAD *t = LIST_DATA(ike->ThreadList, i);
5765 
5766 			Debug("  Thread %u: 0x%p ID: %u Stop: %u Ref: %u\n", i, t, t->ThreadId, t->Stopped, t->ref->c->c);
5767 		}
5768 	}*/
5769 }
5770 
5771 // Stop the IKE server
StopIKEServer(IKE_SERVER * ike)5772 void StopIKEServer(IKE_SERVER *ike)
5773 {
5774 	// Validate arguments
5775 	if (ike == NULL)
5776 	{
5777 		return;
5778 	}
5779 }
5780 
5781 // Set the socket events in IKE server
SetIKEServerSockEvent(IKE_SERVER * ike,SOCK_EVENT * e)5782 void SetIKEServerSockEvent(IKE_SERVER *ike, SOCK_EVENT *e)
5783 {
5784 	// Validate arguments
5785 	if (ike == NULL)
5786 	{
5787 		return;
5788 	}
5789 
5790 	if (e != NULL)
5791 	{
5792 		AddRef(e->ref);
5793 	}
5794 
5795 	if (ike->SockEvent != NULL)
5796 	{
5797 		ReleaseSockEvent(ike->SockEvent);
5798 	}
5799 
5800 	ike->SockEvent = e;
5801 }
5802 
5803 // Release the IKE client
FreeIkeClient(IKE_SERVER * ike,IKE_CLIENT * c)5804 void FreeIkeClient(IKE_SERVER *ike, IKE_CLIENT *c)
5805 {
5806 	// Validate arguments
5807 	if (c == NULL || ike == NULL)
5808 	{
5809 		return;
5810 	}
5811 
5812 	if (c->L2TP != NULL)
5813 	{
5814 		StopL2TPServer(c->L2TP, true);
5815 		FreeL2TPServer(c->L2TP);
5816 	}
5817 
5818 	if (c->EtherIP != NULL)
5819 	{
5820 		ReleaseEtherIPServer(c->EtherIP);
5821 	}
5822 
5823 	FreeBuf(c->SendID1_Buf);
5824 	FreeBuf(c->SendID2_Buf);
5825 
5826 	Free(c);
5827 }
5828 
5829 // Release the IPsec SA
FreeIPsecSa(IPSECSA * sa)5830 void FreeIPsecSa(IPSECSA *sa)
5831 {
5832 	// Validate arguments
5833 	if (sa == NULL)
5834 	{
5835 		return;
5836 	}
5837 
5838 	IkeFreeKey(sa->CryptoKey);
5839 
5840 	FreeBuf(sa->SendBuffer);
5841 
5842 	FreeBuf(sa->InitiatorRand);
5843 	FreeBuf(sa->ResponderRand);
5844 
5845 	FreeBuf(sa->SharedKey);
5846 
5847 	IkeDhFreeCtx(sa->Dh);
5848 
5849 	Free(sa);
5850 }
5851 
5852 // Release the IKE SA
FreeIkeSa(IKE_SA * sa)5853 void FreeIkeSa(IKE_SA *sa)
5854 {
5855 	// Validate arguments
5856 	if (sa == NULL)
5857 	{
5858 		return;
5859 	}
5860 
5861 	FreeBuf(sa->SendBuffer);
5862 
5863 	FreeBuf(sa->InitiatorRand);
5864 	FreeBuf(sa->ResponderRand);
5865 	FreeBuf(sa->DhSharedKey);
5866 	FreeBuf(sa->YourIDPayloadForAM);
5867 
5868 	FreeBuf(sa->GXi);
5869 	FreeBuf(sa->GXr);
5870 
5871 	FreeBuf(sa->SAi_b);
5872 
5873 	IkeFreeKey(sa->CryptoKey);
5874 
5875 	Free(sa);
5876 }
5877 
5878 // Release the IKE server
FreeIKEServer(IKE_SERVER * ike)5879 void FreeIKEServer(IKE_SERVER *ike)
5880 {
5881 	UINT i;
5882 	// Validate arguments
5883 	if (ike == NULL)
5884 	{
5885 		return;
5886 	}
5887 
5888 	IPsecLog(ike, NULL, NULL, NULL, "LI_STOPPING");
5889 
5890 	for (i = 0;i < LIST_NUM(ike->SendPacketList);i++)
5891 	{
5892 		UDPPACKET *udp = LIST_DATA(ike->SendPacketList, i);
5893 
5894 		FreeUdpPacket(udp);
5895 	}
5896 
5897 	ReleaseList(ike->SendPacketList);
5898 
5899 	Debug("Num of IPsec SAs: %u\n", LIST_NUM(ike->IPsecSaList));
5900 	IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IPSEC_SA", LIST_NUM(ike->IPsecSaList));
5901 
5902 	for (i = 0;i < LIST_NUM(ike->IPsecSaList);i++)
5903 	{
5904 		IPSECSA *sa = LIST_DATA(ike->IPsecSaList, i);
5905 
5906 		FreeIPsecSa(sa);
5907 	}
5908 
5909 	ReleaseList(ike->IPsecSaList);
5910 
5911 	Debug("Num of IKE SAs: %u\n", LIST_NUM(ike->IkeSaList));
5912 	IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IKE_SA", LIST_NUM(ike->IkeSaList));
5913 
5914 	for (i = 0;i < LIST_NUM(ike->IkeSaList);i++)
5915 	{
5916 		IKE_SA *sa = LIST_DATA(ike->IkeSaList, i);
5917 
5918 		FreeIkeSa(sa);
5919 	}
5920 
5921 	ReleaseList(ike->IkeSaList);
5922 
5923 	Debug("Num of IKE_CLIENTs: %u\n", LIST_NUM(ike->ClientList));
5924 	IPsecLog(ike, NULL, NULL, NULL, "LI_NUM_IKE_CLIENTS", LIST_NUM(ike->ClientList));
5925 
5926 	for (i = 0;i < LIST_NUM(ike->ClientList);i++)
5927 	{
5928 		IKE_CLIENT *c = LIST_DATA(ike->ClientList, i);
5929 
5930 		FreeIkeClient(ike, c);
5931 	}
5932 
5933 	ReleaseList(ike->ClientList);
5934 
5935 	ReleaseSockEvent(ike->SockEvent);
5936 
5937 	IPsecLog(ike, NULL, NULL, NULL, "LI_STOP");
5938 
5939 	ReleaseCedar(ike->Cedar);
5940 
5941 	FreeIkeEngine(ike->Engine);
5942 
5943 	Debug("FreeThreadList()...\n");
5944 	FreeThreadList(ike->ThreadList);
5945 	Debug("FreeThreadList() Done.\n");
5946 
5947 	Free(ike);
5948 }
5949 
5950 // Create a new IKE server
NewIKEServer(CEDAR * cedar,IPSEC_SERVER * ipsec)5951 IKE_SERVER *NewIKEServer(CEDAR *cedar, IPSEC_SERVER *ipsec)
5952 {
5953 	IKE_SERVER *ike;
5954 	// Validate arguments
5955 	if (cedar == NULL)
5956 	{
5957 		return NULL;
5958 	}
5959 
5960 	ike = ZeroMalloc(sizeof(IKE_SERVER));
5961 
5962 	ike->Cedar = cedar;
5963 	AddRef(cedar->ref);
5964 
5965 	ike->IPsec = ipsec;
5966 
5967 	ike->Now = Tick64();
5968 
5969 	ike->SendPacketList = NewList(NULL);
5970 
5971 	ike->IkeSaList = NewList(CmpIkeSa);
5972 
5973 	ike->IPsecSaList = NewList(CmpIPsecSa);
5974 
5975 	ike->ClientList = NewList(CmpIkeClient);
5976 
5977 	ike->Engine = NewIkeEngine();
5978 
5979 	ike->ThreadList = NewThreadList();
5980 
5981 	IPsecLog(ike, NULL, NULL, NULL, "LI_START");
5982 
5983 	return ike;
5984 }
5985 
5986 
5987 
5988