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 // Interop_OpenVPN.c
103 // OpenVPN protocol stack
104
105 #include "CedarPch.h"
106
107
108 static bool g_no_openvpn_tcp = false;
109 static bool g_no_openvpn_udp = false;
110
111 // Ping signature of the OpenVPN protocol
112 static UCHAR ping_signature[] =
113 {
114 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
115 0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48
116 };
117
118 // Set the OpenVPN over TCP disabling flag
OvsSetNoOpenVpnTcp(bool b)119 void OvsSetNoOpenVpnTcp(bool b)
120 {
121 g_no_openvpn_tcp = b;
122 }
123
124 // Get the OpenVPN over TCP disabling flag
OvsGetNoOpenVpnTcp()125 bool OvsGetNoOpenVpnTcp()
126 {
127 return g_no_openvpn_tcp;
128 }
129
130 // Set the OpenVPN over UDP disabling flag
OvsSetNoOpenVpnUdp(bool b)131 void OvsSetNoOpenVpnUdp(bool b)
132 {
133 g_no_openvpn_udp = b;
134 }
135
136 // Get the OpenVPN over UDP disabling flag
OvsGetNoOpenVpnUdp()137 bool OvsGetNoOpenVpnUdp()
138 {
139 return g_no_openvpn_udp;
140 }
141
142
143 // Write the OpenVPN log
OvsLog(OPENVPN_SERVER * s,OPENVPN_SESSION * se,OPENVPN_CHANNEL * c,char * name,...)144 void OvsLog(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c, char *name, ...)
145 {
146 wchar_t prefix[MAX_SIZE * 2];
147 wchar_t buf2[MAX_SIZE * 2];
148 va_list args;
149 // Validate arguments
150 if (s == NULL)
151 {
152 return;
153 }
154 if (se == NULL)
155 {
156 UniStrCpy(prefix, sizeof(prefix), _UU("LO_PREFIX_RAW"));
157 }
158 else
159 {
160 if (c == NULL)
161 {
162 UniFormat(prefix, sizeof(prefix), _UU("LO_PREFIX_SESSION"),
163 se->Id, &se->ClientIp, se->ClientPort, &se->ServerIp, se->ServerPort);
164 }
165 else
166 {
167 UniFormat(prefix, sizeof(prefix), _UU("LO_PREFIX_CHANNEL"),
168 se->Id, &se->ClientIp, se->ClientPort, &se->ServerIp, se->ServerPort,
169 c->KeyId);
170 }
171 }
172 va_start(args, name);
173 UniFormatArgs(buf2, sizeof(buf2), _UU(name), args);
174 va_end(args);
175
176 UniStrCat(prefix, sizeof(prefix), buf2);
177
178 WriteServerLog(s->Cedar, prefix);
179 }
180
181 // Process the received packet
OvsProceccRecvPacket(OPENVPN_SERVER * s,UDPPACKET * p,UINT protocol)182 void OvsProceccRecvPacket(OPENVPN_SERVER *s, UDPPACKET *p, UINT protocol)
183 {
184 OPENVPN_SESSION *se;
185 OPENVPN_PACKET *recv_packet;
186 // Validate arguments
187 if (s == NULL || p == NULL)
188 {
189 return;
190 }
191
192
193 // Search for the session
194 se = OvsFindOrCreateSession(s, &p->DstIP, p->DestPort, &p->SrcIP, p->SrcPort, protocol);
195 if (se == NULL)
196 {
197 return;
198 }
199
200 // Parse the packet
201 recv_packet = OvsParsePacket(p->Data, p->Size);
202
203 if (recv_packet != NULL)
204 {
205 OPENVPN_CHANNEL *c = NULL;
206 if (recv_packet->OpCode != OPENVPN_P_DATA_V1 && recv_packet->MySessionId != 0)
207 {
208 Debug("RECV PACKET: %u %I64u\n", recv_packet->KeyId, recv_packet->MySessionId);
209 }
210 if (recv_packet->OpCode != OPENVPN_P_DATA_V1)
211 {
212 Debug(" PKT %u %u\n", recv_packet->OpCode, recv_packet->KeyId);
213 }
214
215 if (recv_packet->OpCode != OPENVPN_P_DATA_V1)
216 {
217 // Control packet
218 if (recv_packet->OpCode == OPENVPN_P_CONTROL_HARD_RESET_CLIENT_V2 ||
219 recv_packet->OpCode == OPENVPN_P_CONTROL_SOFT_RESET_V1)
220 {
221 // Connection request packet
222 if (se->Channels[recv_packet->KeyId] != NULL)
223 {
224 // Release when there is a channel data already
225 OvsFreeChannel(se->Channels[recv_packet->KeyId]);
226 se->Channels[recv_packet->KeyId] = NULL;
227 }
228
229 // Create a new channel
230 c = OvsNewChannel(se, recv_packet->KeyId);
231 if (se->ClientSessionId == 0)
232 {
233 se->ClientSessionId = recv_packet->MySessionId;
234 }
235 se->Channels[recv_packet->KeyId] = c;
236 Debug("OpenVPN New Channel :%u\n", recv_packet->KeyId);
237 //OvsLog(s, se, c, "LO_NEW_CHANNEL");
238 }
239 /* else if (recv_packet->OpCode == OPENVPN_P_CONTROL_SOFT_RESET_V1)
240 {
241 // Response to soft reset request packet
242 OPENVPN_PACKET *p;
243
244 p = OvsNewControlPacket(OPENVPN_P_CONTROL_SOFT_RESET_V1, recv_packet->KeyId, se->ServerSessionId,
245 0, NULL, 0, 0, 0, NULL);
246
247 OvsSendPacketNow(s, se, p);
248
249 OvsFreePacket(p);
250 }*/
251 else
252 {
253 // Packet other than the connection request
254 if (se->Channels[recv_packet->KeyId] != NULL)
255 {
256 c = se->Channels[recv_packet->KeyId];
257 }
258 }
259
260 if (c != NULL)
261 {
262 // Delete the send packet list by looking the packet ID in the ACK list of arrived packet
263 OvsDeleteFromSendingControlPacketList(c, recv_packet->NumAck, recv_packet->AckPacketId);
264
265 if (recv_packet->OpCode != OPENVPN_P_ACK_V1)
266 {
267 // Add the Packet ID of arrived packet to the list
268 InsertIntDistinct(c->AckReplyList, recv_packet->PacketId);
269 Debug("Recv Packet ID (c=%u): %u\n", c->KeyId, recv_packet->PacketId);
270
271 if ((recv_packet->PacketId > c->MaxRecvPacketId)
272 || (recv_packet->OpCode == OPENVPN_P_CONTROL_HARD_RESET_CLIENT_V2)
273 || (recv_packet->OpCode == OPENVPN_P_CONTROL_SOFT_RESET_V1))
274 {
275 c->MaxRecvPacketId = recv_packet->PacketId;
276
277 // Process the received control packet
278 OvsProcessRecvControlPacket(s, se, c, recv_packet);
279 }
280 }
281 }
282 }
283 else
284 {
285 // Data packet
286 if (se->Channels[recv_packet->KeyId] != NULL)
287 {
288 OPENVPN_CHANNEL *c = se->Channels[recv_packet->KeyId];
289 if (c->Status == OPENVPN_CHANNEL_STATUS_ESTABLISHED)
290 {
291 UCHAR *data;
292 UINT size;
293
294 data = recv_packet->Data;
295 size = recv_packet->DataSize;
296
297 if (size >= (c->MdRecv->Size + c->CipherDecrypt->IvSize + sizeof(UINT)))
298 {
299 UCHAR *hmac;
300 UCHAR *iv;
301 UCHAR hmac_test[128];
302
303 // HMAC
304 hmac = data;
305 data += c->MdRecv->Size;
306 size -= c->MdRecv->Size;
307
308 // Confirmation of HMAC
309 MdProcess(c->MdRecv, hmac_test, data, size);
310 if (Cmp(hmac_test, hmac, c->MdRecv->Size) == 0)
311 {
312 // Update of last communication time
313 se->LastCommTick = s->Now;
314
315 // IV
316 iv = data;
317 data += c->CipherDecrypt->IvSize;
318 size -= c->CipherDecrypt->IvSize;
319
320 // Payload
321 if (size >= 1 && (c->CipherDecrypt->BlockSize == 0 || (size % c->CipherDecrypt->BlockSize) == 0))
322 {
323 UINT data_packet_id;
324
325 // Decryption
326 size = CipherProcess(c->CipherDecrypt, iv, s->TmpBuf, data, size);
327
328 data = s->TmpBuf;
329
330 if (size >= sizeof(UINT))
331 {
332 data_packet_id = READ_UINT(data);
333
334 data += sizeof(UINT);
335 size -= sizeof(UINT);
336
337 if (size >= sizeof(ping_signature) &&
338 Cmp(data, ping_signature, sizeof(ping_signature)) == 0)
339 {
340 // Ignore since a ping packet has been received
341 DoNothing();
342 }
343 else
344 {
345 // Receive a packet!!
346 if (se->Ipc != NULL)
347 {
348 switch (se->Mode)
349 {
350 case OPENVPN_MODE_L2: // Send an Ethernet packet to a session
351 IPCSendL2(se->Ipc, data, size);
352 break;
353
354 case OPENVPN_MODE_L3: // Send an IPv4 packet to a session
355 IPCSendIPv4(se->Ipc, data, size);
356 break;
357 }
358 }
359 }
360 }
361 }
362 }
363 else
364 {
365 // Debug("HMAC Failed (c=%u)\n", c->KeyId);
366 }
367 }
368 }
369 }
370 }
371
372 OvsFreePacket(recv_packet);
373 }
374 }
375
376 // Remove a packet which the opponent has received from the transmission list
OvsDeleteFromSendingControlPacketList(OPENVPN_CHANNEL * c,UINT num_acks,UINT * acks)377 void OvsDeleteFromSendingControlPacketList(OPENVPN_CHANNEL *c, UINT num_acks, UINT *acks)
378 {
379 LIST *o;
380 UINT i;
381 // Validate arguments
382 if (c == NULL || num_acks == 0)
383 {
384 return;
385 }
386
387 o = NewListFast(NULL);
388 for (i = 0;i < num_acks;i++)
389 {
390 UINT ack = acks[i];
391 UINT j;
392
393 for (j = 0;j < LIST_NUM(c->SendControlPacketList);j++)
394 {
395 OPENVPN_CONTROL_PACKET *p = LIST_DATA(c->SendControlPacketList, j);
396
397 if (p->PacketId == ack)
398 {
399 AddDistinct(o, p);
400 }
401 }
402 }
403
404 for (i = 0;i < LIST_NUM(o);i++)
405 {
406 OPENVPN_CONTROL_PACKET *p = LIST_DATA(o, i);
407
408 Delete(c->SendControlPacketList, p);
409
410 OvsFreeControlPacket(p);
411 }
412
413 ReleaseList(o);
414 }
415
416 // Process the received control packet
OvsProcessRecvControlPacket(OPENVPN_SERVER * s,OPENVPN_SESSION * se,OPENVPN_CHANNEL * c,OPENVPN_PACKET * p)417 void OvsProcessRecvControlPacket(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c, OPENVPN_PACKET *p)
418 {
419 FIFO *recv_fifo = NULL;
420 FIFO *send_fifo = NULL;
421 // Validate arguments
422 if (s == NULL || se == NULL || c == NULL || p == NULL)
423 {
424 return;
425 }
426
427 if (p->OpCode == OPENVPN_P_CONTROL_V1)
428 {
429 Debug("SSL (c=%u): %u\n", c->KeyId, p->DataSize);
430
431 if (c->SslPipe == NULL)
432 {
433 // Create an SSL pipe
434 Lock(s->Cedar->lock);
435 {
436 bool cert_verify = true;
437 c->SslPipe = NewSslPipeEx(true, s->Cedar->ServerX, s->Cedar->ServerK, s->Dh, cert_verify, &c->ClientCert);
438 }
439 Unlock(s->Cedar->lock);
440
441 Debug("SSL Pipe Created (c=%u).\n", c->KeyId);
442 }
443
444 if (c->SslPipe->IsDisconnected == false)
445 {
446 // Pour the physically received data into SSL pipe
447 if (FifoSize(c->SslPipe->RawIn->SendFifo) < OPENVPN_MAX_SSL_RECV_BUF_SIZE)
448 {
449 Debug("SSL_Write: %u\n", p->DataSize);
450 WriteFifo(c->SslPipe->RawIn->SendFifo, p->Data, p->DataSize);
451 }
452 SyncSslPipe(c->SslPipe);
453 }
454 }
455
456 if (c->SslPipe != NULL && c->SslPipe->IsDisconnected == false)
457 {
458 recv_fifo = c->SslPipe->SslInOut->RecvFifo;
459 send_fifo = c->SslPipe->SslInOut->SendFifo;
460 }
461
462 Debug("SIZE: recv_fifo = %u, send_fifo = %u\n", FifoSize(recv_fifo), FifoSize(send_fifo));
463
464 switch (c->Status)
465 {
466 case OPENVPN_CHANNEL_STATUS_INIT:
467 switch (p->OpCode)
468 {
469 case OPENVPN_P_CONTROL_SOFT_RESET_V1:
470 // Key update (soft reset)
471 if (se->Established)
472 {
473 if (c->IsInitiatorServer == false)
474 {
475 OvsSendControlPacket(c, OPENVPN_P_CONTROL_SOFT_RESET_V1, NULL, 0);
476 }
477
478 c->Status = OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_KEY;
479 c->IsRekeyChannel = true;
480 }
481 break;
482
483 case OPENVPN_P_CONTROL_HARD_RESET_CLIENT_V2:
484 // New connection (hard reset)
485 OvsSendControlPacketEx(c, OPENVPN_P_CONTROL_HARD_RESET_SERVER_V2, NULL, 0, true);
486
487 c->Status = OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_KEY;
488 break;
489 }
490 break;
491
492 case OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_KEY:
493 if (FifoSize(recv_fifo) >= 1)
494 {
495 OPENVPN_KEY_METHOD_2 data;
496 UCHAR *ptr = FifoPtr(recv_fifo);
497
498 // Parse OPENVPN_KEY_METHOD_2
499 UINT read_size = OvsParseKeyMethod2(&data, ptr, FifoSize(recv_fifo), true);
500 if (read_size != 0)
501 {
502 BUF *b;
503
504 // Success in parsing key information
505 ReadFifo(recv_fifo, NULL, read_size);
506
507 // Set session parameters
508 OvsSetupSessionParameters(s, se, c, &data);
509
510 // Build OPENVPN_KEY_METHOD_2 to respond
511 b = OvsBuildKeyMethod2(&c->ServerKey);
512
513 // Transmission of the response data
514 if (b != NULL)
515 {
516 WriteFifo(send_fifo, b->Buf, b->Size);
517
518 FreeBuf(b);
519 }
520
521 // State transition
522 c->Status = OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_PUSH_REQUEST;
523 if (c->IsRekeyChannel)
524 {
525 c->Status = OPENVPN_CHANNEL_STATUS_ESTABLISHED;
526 c->EstablishedTick = s->Now;
527 Debug("OpenVPN Channel %u Established (re-key).\n", c->KeyId);
528 OvsLog(s, se, c, "LO_CHANNEL_ESTABLISHED_NEWKEY");
529 }
530 }
531 }
532 break;
533
534 case OPENVPN_CHANNEL_STATUS_TLS_WAIT_CLIENT_PUSH_REQUEST:
535 if (FifoSize(recv_fifo) >= 1)
536 {
537 char tmp[MAX_SIZE];
538 UINT read_size = OvsPeekStringFromFifo(recv_fifo, tmp, sizeof(tmp));
539
540 if (read_size >= 1)
541 {
542 Debug("Client->Server (c=%u): %s\n", c->KeyId, tmp);
543
544 ReadFifo(recv_fifo, NULL, read_size);
545
546 if (StartWith(tmp, "PUSH_REQUEST"))
547 {
548 // Since connection requested, start VPN connection
549 // When the IPC VPN connection has not been started yet, start it
550 OvsBeginIPCAsyncConnectionIfEmpty(s, se, c);
551
552 // State transition
553 c->Status = OPENVPN_CHANNEL_STATUS_TLS_VPN_CONNECTING;
554 }
555 }
556 }
557 break;
558
559 case OPENVPN_CHANNEL_STATUS_TLS_VPN_CONNECTING:
560 case OPENVPN_CHANNEL_STATUS_ESTABLISHED:
561 if (FifoSize(recv_fifo) >= 1)
562 {
563 char tmp[MAX_SIZE];
564 UINT read_size = OvsPeekStringFromFifo(recv_fifo, tmp, sizeof(tmp));
565
566 if (read_size >= 1)
567 {
568 Debug("Client->Server (c=%u): %s\n", c->KeyId, tmp);
569
570 ReadFifo(recv_fifo, NULL, read_size);
571
572 if (StartWith(tmp, "PUSH_REQUEST"))
573 {
574 WriteFifo(send_fifo, se->PushReplyStr, StrLen(se->PushReplyStr));
575 }
576 }
577 }
578 break;
579 }
580 }
581
582 // Calculate the proper MSS
OvsCalcTcpMss(OPENVPN_SERVER * s,OPENVPN_SESSION * se,OPENVPN_CHANNEL * c)583 UINT OvsCalcTcpMss(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c)
584 {
585 UINT ret = MTU_FOR_PPPOE;
586 // Validate arguments
587 if (s == NULL || se == NULL || c == NULL)
588 {
589 return 0;
590 }
591
592 if (c->MdSend == NULL || c->CipherEncrypt == NULL)
593 {
594 return 0;
595 }
596
597 if (se->Protocol == OPENVPN_PROTOCOL_TCP)
598 {
599 // Calculation is not required for TCP mode
600 return 0;
601 }
602
603 // IPv4 / IPv6
604 if (IsIP4(&se->ClientIp))
605 {
606 ret -= 20;
607 }
608 else
609 {
610 ret -= 40;
611 }
612
613 // UDP
614 ret -= 8;
615
616 // opcode
617 ret -= 1;
618
619 // HMAC
620 ret -= c->MdSend->Size;
621
622 // IV
623 ret -= c->CipherEncrypt->IvSize;
624
625 // Packet ID
626 ret -= 4;
627
628 if (c->CipherEncrypt->IsNullCipher == false)
629 {
630 // block
631 ret -= c->CipherEncrypt->BlockSize;
632 }
633
634 if (se->Mode == OPENVPN_MODE_L2)
635 {
636 // Inner Ethernet Header
637 ret -= 14;
638 }
639
640 // Inner IPv4
641 ret -= 20;
642
643 // Inner TCP
644 ret -= 20;
645
646 return ret;
647 }
648
649 // When the IPC VPN connection has not been started yet, start it
OvsBeginIPCAsyncConnectionIfEmpty(OPENVPN_SERVER * s,OPENVPN_SESSION * se,OPENVPN_CHANNEL * c)650 void OvsBeginIPCAsyncConnectionIfEmpty(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c)
651 {
652 // Validate arguments
653 if (s == NULL || se == NULL || c == NULL)
654 {
655 return;
656 }
657
658 if (IsIPCConnected(se->Ipc) == false)
659 {
660 FreeIPC(se->Ipc);
661
662 se->Ipc = NULL;
663 }
664
665 if (se->IpcAsync == NULL)
666 {
667 IPC_PARAM p;
668 ETHERIP_ID id;
669
670 Zero(&p, sizeof(p));
671 Zero(&id, sizeof(id));
672
673 // Parse the user name
674 PPPParseUsername(s->Cedar, c->ClientKey.Username, &id);
675
676
677 // Build IPC connection parameters
678 StrCpy(p.ClientName, sizeof(p.ClientName), OPENVPN_IPC_CLIENT_NAME);
679 StrCpy(p.Postfix, sizeof(p.Postfix), (se->Mode == OPENVPN_MODE_L3 ? OPENVPN_IPC_POSTFIX_L3 : OPENVPN_IPC_POSTFIX_L2));
680
681 StrCpy(p.UserName, sizeof(p.UserName), id.UserName);
682 StrCpy(p.HubName, sizeof(p.HubName), id.HubName);
683 StrCpy(p.Password, sizeof(p.Password), c->ClientKey.Password);
684
685 Copy(&p.ClientIp, &se->ClientIp, sizeof(IP));
686 p.ClientPort = se->ClientPort;
687
688 Copy(&p.ServerIp, &se->ServerIp, sizeof(IP));
689 p.ServerPort = se->ServerPort;
690
691 if (c->CipherEncrypt->IsNullCipher == false)
692 {
693 StrCpy(p.CryptName, sizeof(p.CryptName), c->CipherEncrypt->Name);
694 }
695
696 if (se->Mode == OPENVPN_MODE_L3)
697 {
698 // L3 Mode
699 p.IsL3Mode = true;
700 }
701 else
702 {
703 // L2 Mode
704 p.BridgeMode = true;
705 }
706
707 if (IsEmptyStr(c->ClientKey.Username) || IsEmptyStr(c->ClientKey.Password))
708 {
709 // OpenVPN X.509 certificate authentication is used only when no username / password is specified
710 if (c->ClientCert.X != NULL)
711 {
712 p.ClientCertificate = c->ClientCert.X;
713 }
714 }
715
716 p.IsOpenVPN = true;
717
718 p.Layer = (se->Mode == OPENVPN_MODE_L2) ? IPC_LAYER_2 : IPC_LAYER_3;
719
720 // Calculate the MSS
721 p.Mss = OvsCalcTcpMss(s, se, c);
722 Debug("MSS=%u\n", p.Mss);
723
724 // Start an IPC connection
725 se->IpcAsync = NewIPCAsync(s->Cedar, &p, s->SockEvent);
726 }
727 }
728
729 // Peek a NULL-terminated string from the FIFO
OvsPeekStringFromFifo(FIFO * f,char * str,UINT str_size)730 UINT OvsPeekStringFromFifo(FIFO *f, char *str, UINT str_size)
731 {
732 UINT i;
733 bool ok = false;
734 // Validate arguments
735 if (f == NULL || str == NULL || str_size == 0)
736 {
737 return 0;
738 }
739
740 StrCpy(str, str_size, "");
741
742 for (i = 0;i < MIN(str_size, FifoSize(f));i++)
743 {
744 char c = *(((char *)FifoPtr(f)) + i);
745
746 if (c != 0)
747 {
748 str[i] = c;
749 }
750 else
751 {
752 str[i] = 0;
753 i++;
754 ok = true;
755 break;
756 }
757 }
758
759 if (ok == false)
760 {
761 return 0;
762 }
763
764 return i;
765 }
766
767 // Set session parameters
OvsSetupSessionParameters(OPENVPN_SERVER * s,OPENVPN_SESSION * se,OPENVPN_CHANNEL * c,OPENVPN_KEY_METHOD_2 * data)768 void OvsSetupSessionParameters(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_CHANNEL *c, OPENVPN_KEY_METHOD_2 *data)
769 {
770 LIST *o;
771 BUF *b;
772 char opt_str[MAX_SIZE];
773 // Validate arguments
774 if (s == NULL || se == NULL || c == NULL || data == NULL)
775 {
776 return;
777 }
778
779 Copy(&c->ClientKey, data, sizeof(OPENVPN_KEY_METHOD_2));
780
781 // Parse the parameter string
782 Debug("Parsing Option Str: %s\n", data->OptionString);
783
784 OvsLog(s, se, c, "LO_OPTION_STR_RECV", data->OptionString);
785
786 if (c->ClientCert.X != NULL)
787 {
788 if (c->ClientCert.X->subject_name != NULL)
789 {
790 OvsLog(s, se, c, "LO_CLIENT_CERT", c->ClientCert.X->subject_name->CommonName);
791 }
792 else
793 {
794 OvsLog(s, se, c, "LO_CLIENT_CERT", "(unknown CN)");
795 }
796 }
797 else if (!c->ClientCert.PreverifyErr)
798 {
799 OvsLog(s, se, c, "LO_CLIENT_NO_CERT");
800 }
801 else
802 {
803 OvsLog(s, se, c, "LO_CLIENT_UNVERIFIED_CERT", c->ClientCert.PreverifyErrMessage);
804 }
805
806 Zero(opt_str, sizeof(opt_str));
807 StrCpy(opt_str, sizeof(opt_str), data->OptionString);
808 if (s->Cedar != NULL && (IsEmptyStr(opt_str) || StartWith(opt_str, "V0 UNDEF") || InStr(opt_str, ",") == false))
809 {
810 StrCpy(opt_str, sizeof(opt_str), s->Cedar->OpenVPNDefaultClientOption);
811 }
812
813 o = OvsParseOptions(opt_str);
814
815 if (se->Mode == OPENVPN_MODE_UNKNOWN)
816 {
817 UINT mtu;
818 // Layer
819 if (StrCmpi(IniStrValue(o, "dev-type"), "tun") == 0)
820 {
821 // L3
822 se->Mode = OPENVPN_MODE_L3;
823 }
824 else
825 {
826 // L2
827 se->Mode = OPENVPN_MODE_L2;
828 }
829
830 // Link MTU
831 mtu = IniIntValue(o, "link-mtu");
832 if (mtu == 0)
833 {
834 mtu = OPENVPN_MTU_LINK;
835 }
836 se->LinkMtu = mtu;
837
838 // Tun MTU
839 mtu = IniIntValue(o, "tun-mtu");
840 if (mtu == 0)
841 {
842 mtu = OPENVPN_MTU_TUN;
843 }
844 se->TunMtu = mtu;
845 }
846
847 // Protocol
848 if (se->Protocol == OPENVPN_PROTOCOL_TCP)
849 {
850 // TCP
851 // UDP
852 if (IsIP6(&se->ClientIp) == false)
853 {
854 StrCpy(c->Proto, sizeof(c->Proto), "TCPv4_SERVER");
855 }
856 else
857 {
858 StrCpy(c->Proto, sizeof(c->Proto), "TCPv6_SERVER");
859 }
860 }
861 else
862 {
863 // UDP
864 if (IsIP6(&se->ClientIp) == false)
865 {
866 StrCpy(c->Proto, sizeof(c->Proto), "UDPv4");
867 }
868 else
869 {
870 StrCpy(c->Proto, sizeof(c->Proto), "UDPv6");
871 }
872 }
873
874 // Encryption algorithm
875 c->CipherEncrypt = OvsGetCipher(IniStrValue(o, "cipher"));
876 c->CipherDecrypt = NewCipher(c->CipherEncrypt->Name);
877
878 // Hash algorithm
879 c->MdSend = OvsGetMd(IniStrValue(o, "auth"));
880 c->MdRecv = NewMd(c->MdSend->Name);
881
882 // Random number generation
883 Rand(c->ServerKey.Random1, sizeof(c->ServerKey.Random1));
884 Rand(c->ServerKey.Random2, sizeof(c->ServerKey.Random2));
885
886 // Generate the Master Secret
887 b = NewBuf();
888 WriteBuf(b, OPENVPN_PREMASTER_LABEL, StrLen(OPENVPN_PREMASTER_LABEL));
889 WriteBuf(b, c->ClientKey.Random1, sizeof(c->ClientKey.Random1));
890 WriteBuf(b, c->ServerKey.Random1, sizeof(c->ServerKey.Random1));
891 Enc_tls1_PRF(b->Buf, b->Size,
892 c->ClientKey.PreMasterSecret, sizeof(c->ClientKey.PreMasterSecret),
893 c->MasterSecret, sizeof(c->MasterSecret));
894 FreeBuf(b);
895
896 // Generate an Expansion Key
897 b = NewBuf();
898 WriteBuf(b, OPENVPN_EXPANSION_LABEL, StrLen(OPENVPN_EXPANSION_LABEL));
899 WriteBuf(b, c->ClientKey.Random2, sizeof(c->ClientKey.Random2));
900 WriteBuf(b, c->ServerKey.Random2, sizeof(c->ServerKey.Random2));
901 WriteBufInt64(b, se->ClientSessionId);
902 WriteBufInt64(b, se->ServerSessionId);
903 Enc_tls1_PRF(b->Buf, b->Size, c->MasterSecret, sizeof(c->MasterSecret),
904 c->ExpansionKey, sizeof(c->ExpansionKey));
905 FreeBuf(b);
906
907 // Set the key
908 SetCipherKey(c->CipherDecrypt, c->ExpansionKey + 0, false);
909 SetCipherKey(c->CipherEncrypt, c->ExpansionKey + 128, true);
910 SetMdKey(c->MdRecv, c->ExpansionKey + 64, c->MdRecv->Size);
911 SetMdKey(c->MdSend, c->ExpansionKey + 192, c->MdSend->Size);
912
913 OvsFreeOptions(o);
914
915 // Generate the response option string
916 Format(c->ServerKey.OptionString, sizeof(c->ServerKey.OptionString),
917 "V4,dev-type %s,link-mtu %u,tun-mtu %u,proto %s,"
918 "cipher %s,auth %s,keysize %u,key-method 2,tls-server",
919 (se->Mode == OPENVPN_MODE_L2 ? "tap" : "tun"),
920 se->LinkMtu,
921 se->TunMtu,
922 c->Proto,
923 c->CipherEncrypt->Name, c->MdSend->Name, c->CipherEncrypt->KeySize * 8);
924 Debug("Building OptionStr: %s\n", c->ServerKey.OptionString);
925
926 OvsLog(s, se, c, "LO_OPTION_STR_SEND", c->ServerKey.OptionString);
927 }
928
929 // Get the encryption algorithm
OvsGetCipher(char * name)930 CIPHER *OvsGetCipher(char *name)
931 {
932 CIPHER *c = NULL;
933
934 if (IsEmptyStr(name) == false && IsStrInStrTokenList(OPENVPN_CIPHER_LIST, name, NULL, false))
935 {
936 c = NewCipher(name);
937 }
938
939 if (c == NULL)
940 {
941 c = NewCipher(OPENVPN_DEFAULT_CIPHER);
942 }
943
944 return c;
945 }
946
947 // Get the hash algorithm
OvsGetMd(char * name)948 MD *OvsGetMd(char *name)
949 {
950 MD *m = NULL;
951
952 if (IsEmptyStr(name) == false && IsStrInStrTokenList(OPENVPN_MD_LIST, name, NULL, false))
953 {
954 m = NewMd(name);
955 }
956
957 if (m == NULL)
958 {
959 m = NewMd(OPENVPN_DEFAULT_MD);
960 }
961
962 return m;
963 }
964
965 // Parse the option string
OvsParseOptions(char * str)966 LIST *OvsParseOptions(char *str)
967 {
968 LIST *o = NewListFast(NULL);
969 TOKEN_LIST *t;
970
971 t = ParseTokenWithoutNullStr(str, ",");
972 if (t != NULL)
973 {
974 UINT i;
975
976 for (i = 0;i < t->NumTokens;i++)
977 {
978 char key[MAX_SIZE];
979 char value[MAX_SIZE];
980 char *line = t->Token[i];
981 Trim(line);
982
983 if (GetKeyAndValue(line, key, sizeof(key), value, sizeof(value), " \t"))
984 {
985 INI_ENTRY *e = ZeroMalloc(sizeof(INI_ENTRY));
986
987 e->Key = CopyStr(key);
988 e->Value = CopyStr(value);
989
990 Add(o, e);
991 }
992 }
993
994 FreeToken(t);
995 }
996
997 return o;
998 }
999
1000 // Release the option list
OvsFreeOptions(LIST * o)1001 void OvsFreeOptions(LIST *o)
1002 {
1003 // Validate arguments
1004 if (o == NULL)
1005 {
1006 return;
1007 }
1008
1009 FreeIni(o);
1010 }
1011
1012 // Create an Option List
OvsNewOptions()1013 LIST *OvsNewOptions()
1014 {
1015 return NewListFast(NULL);
1016 }
1017
1018 // Add a value to the option list
OvsAddOption(LIST * o,char * key,char * value)1019 void OvsAddOption(LIST *o, char *key, char *value)
1020 {
1021 INI_ENTRY *e;
1022 // Validate arguments
1023 if (o == NULL)
1024 {
1025 return;
1026 }
1027
1028 e = GetIniEntry(o, key);
1029 if (e != NULL)
1030 {
1031 // Overwrite existing keys
1032 Free(e->Key);
1033 e->Key = CopyStr(key);
1034
1035 Free(e->Value);
1036 e->Value = CopyStr(value);
1037 }
1038 else
1039 {
1040 // Create a new key
1041 e = ZeroMalloc(sizeof(INI_ENTRY));
1042
1043 e->Key = CopyStr(key);
1044 e->Value = CopyStr(value);
1045
1046 Add(o, e);
1047 }
1048 }
1049
1050 // Confirm whether there is specified option key string
OvsHasOption(LIST * o,char * key)1051 bool OvsHasOption(LIST *o, char *key)
1052 {
1053 // Validate arguments
1054 if (o == NULL || key == NULL)
1055 {
1056 return false;
1057 }
1058
1059 if (GetIniEntry(o, key) != NULL)
1060 {
1061 return true;
1062 }
1063
1064 return false;
1065 }
1066
1067 // Build the data from KEY_METHOD2
OvsBuildKeyMethod2(OPENVPN_KEY_METHOD_2 * d)1068 BUF *OvsBuildKeyMethod2(OPENVPN_KEY_METHOD_2 *d)
1069 {
1070 BUF *b;
1071 UCHAR uc;
1072 // Validate arguments
1073 if (d == NULL)
1074 {
1075 return NULL;
1076 }
1077
1078 b = NewBuf();
1079
1080 // Reserved
1081 WriteBufInt(b, 0);
1082
1083 // Method
1084 uc = 2;
1085 WriteBuf(b, &uc, sizeof(UCHAR));
1086
1087 // Random1
1088 WriteBuf(b, d->Random1, sizeof(d->Random1));
1089
1090 // Random2
1091 WriteBuf(b, d->Random2, sizeof(d->Random2));
1092
1093 // Option String
1094 OvsWriteStringToBuf(b, d->OptionString, sizeof(d->OptionString));
1095
1096 // Username
1097 OvsWriteStringToBuf(b, d->Username, sizeof(d->Username));
1098
1099 // Password
1100 OvsWriteStringToBuf(b, d->Password, sizeof(d->Password));
1101
1102 // PeerInfo
1103 OvsWriteStringToBuf(b, d->PeerInfo, sizeof(d->PeerInfo));
1104
1105 return b;
1106 }
1107
1108 // Append a string to buf
OvsWriteStringToBuf(BUF * b,char * str,UINT max_size)1109 void OvsWriteStringToBuf(BUF *b, char *str, UINT max_size)
1110 {
1111 USHORT us;
1112 UINT i;
1113 char *tmp;
1114 // Validate arguments
1115 if (b == NULL)
1116 {
1117 return;
1118 }
1119 if (str == NULL)
1120 {
1121 str = "";
1122 }
1123
1124 if (StrLen(str) == 0)
1125 {
1126 us = 0;
1127 WriteBuf(b, &us, sizeof(USHORT));
1128 return;
1129 }
1130
1131 i = StrSize(str);
1132 i = MIN(i, max_size);
1133 us = Endian16((USHORT)i);
1134 WriteBuf(b, &us, sizeof(USHORT));
1135
1136 tmp = Malloc(i);
1137 Copy(tmp, str, i);
1138 tmp[i - 1] = 0;
1139 WriteBuf(b, tmp, i);
1140
1141 Free(tmp);
1142 }
1143
1144 // Parse the KEY_METHOD2
OvsParseKeyMethod2(OPENVPN_KEY_METHOD_2 * ret,UCHAR * data,UINT size,bool client_mode)1145 UINT OvsParseKeyMethod2(OPENVPN_KEY_METHOD_2 *ret, UCHAR *data, UINT size, bool client_mode)
1146 {
1147 BUF *b;
1148 UINT read_size = 0;
1149 UINT ui;
1150 UCHAR uc;
1151 // Validate arguments
1152 Zero(ret, sizeof(OPENVPN_KEY_METHOD_2));
1153 if (ret == NULL || data == NULL || size == 0)
1154 {
1155 return 0;
1156 }
1157
1158 b = NewBuf();
1159 WriteBuf(b, data, size);
1160 SeekBuf(b, 0, 0);
1161
1162 // Reserved
1163 if (ReadBuf(b, &ui, sizeof(UINT)) == sizeof(UINT))
1164 {
1165 // Method
1166 if (ReadBuf(b, &uc, sizeof(UCHAR)) == sizeof(UCHAR) && uc == 2)
1167 {
1168 // Pre Master Secret
1169 if (client_mode == false || ReadBuf(b, ret->PreMasterSecret, sizeof(ret->PreMasterSecret)) == sizeof(ret->PreMasterSecret))
1170 {
1171 // Random1
1172 if (ReadBuf(b, ret->Random1, sizeof(ret->Random1)) == sizeof(ret->Random1))
1173 {
1174 // Random2
1175 if (ReadBuf(b, ret->Random2, sizeof(ret->Random2)) == sizeof(ret->Random2))
1176 {
1177 // String
1178 if (OvsReadStringFromBuf(b, ret->OptionString, sizeof(ret->OptionString)) &&
1179 OvsReadStringFromBuf(b, ret->Username, sizeof(ret->Username)) &&
1180 OvsReadStringFromBuf(b, ret->Password, sizeof(ret->Password)) &&
1181 OvsReadStringFromBuf(b, ret->PeerInfo, sizeof(ret->PeerInfo)))
1182 {
1183 read_size = b->Current;
1184 }
1185 }
1186 }
1187 }
1188 }
1189 }
1190
1191 FreeBuf(b);
1192
1193 return read_size;
1194 }
1195
1196 // Read a string from BUF
OvsReadStringFromBuf(BUF * b,char * str,UINT str_size)1197 bool OvsReadStringFromBuf(BUF *b, char *str, UINT str_size)
1198 {
1199 USHORT us;
1200 // Validate arguments
1201 if (b == NULL || str == NULL)
1202 {
1203 return false;
1204 }
1205
1206 if (ReadBuf(b, &us, sizeof(USHORT)) != sizeof(USHORT))
1207 {
1208 return false;
1209 }
1210
1211 us = Endian16(us);
1212
1213 if (us == 0)
1214 {
1215 StrCpy(str, str_size, "");
1216 return true;
1217 }
1218
1219 if (us > str_size)
1220 {
1221 return false;
1222 }
1223
1224 if (ReadBuf(b, str, us) != us)
1225 {
1226 return false;
1227 }
1228
1229 if (str[us - 1] != 0)
1230 {
1231 return false;
1232 }
1233
1234 return true;
1235 }
1236
1237 // Transmission of control packet (Automatic segmentation with the maximum size)
OvsSendControlPacketWithAutoSplit(OPENVPN_CHANNEL * c,UCHAR opcode,UCHAR * data,UINT data_size)1238 void OvsSendControlPacketWithAutoSplit(OPENVPN_CHANNEL *c, UCHAR opcode, UCHAR *data, UINT data_size)
1239 {
1240 BUF *b;
1241 // Validate arguments
1242 if (c == NULL || (data_size != 0 && data == NULL))
1243 {
1244 return;
1245 }
1246
1247 b = NewBuf();
1248 WriteBuf(b, data, data_size);
1249 SeekBuf(b, 0, 0);
1250
1251 while (true)
1252 {
1253 UCHAR tmp[OPENVPN_CONTROL_PACKET_MAX_DATASIZE];
1254 UINT size = ReadBuf(b, tmp, sizeof(tmp));
1255
1256 if (size == 0)
1257 {
1258 break;
1259 }
1260
1261 OvsSendControlPacket(c, opcode, tmp, size);
1262 //Debug(" *** CNT SEND %u\n", size);
1263 }
1264
1265 FreeBuf(b);
1266 }
1267
1268 // Send the control packet
OvsSendControlPacket(OPENVPN_CHANNEL * c,UCHAR opcode,UCHAR * data,UINT data_size)1269 void OvsSendControlPacket(OPENVPN_CHANNEL *c, UCHAR opcode, UCHAR *data, UINT data_size)
1270 {
1271 OvsSendControlPacketEx(c, opcode, data, data_size, false);
1272 }
OvsSendControlPacketEx(OPENVPN_CHANNEL * c,UCHAR opcode,UCHAR * data,UINT data_size,bool no_resend)1273 void OvsSendControlPacketEx(OPENVPN_CHANNEL *c, UCHAR opcode, UCHAR *data, UINT data_size, bool no_resend)
1274 {
1275 OPENVPN_CONTROL_PACKET *p;
1276 // Validate arguments
1277 if (c == NULL || (data_size != 0 && data == NULL))
1278 {
1279 return;
1280 }
1281
1282 p = ZeroMalloc(sizeof(OPENVPN_CONTROL_PACKET));
1283
1284 p->NoResend = no_resend;
1285
1286 p->OpCode = opcode;
1287 p->PacketId = c->NextSendPacketId++;
1288
1289 if (data != NULL)
1290 {
1291 p->Data = Clone(data, data_size);
1292 p->DataSize = data_size;
1293 }
1294
1295 p->NextSendTime = 0;
1296
1297 Add(c->SendControlPacketList, p);
1298 }
1299
1300 // Release the control packet being transmitted
OvsFreeControlPacket(OPENVPN_CONTROL_PACKET * p)1301 void OvsFreeControlPacket(OPENVPN_CONTROL_PACKET *p)
1302 {
1303 // Validate arguments
1304 if (p == NULL)
1305 {
1306 return;
1307 }
1308
1309 if (p->Data != NULL)
1310 {
1311 Free(p->Data);
1312 }
1313
1314 Free(p);
1315 }
1316
1317 // Get a list of packet ID to be responded
OvsGetAckReplyList(OPENVPN_CHANNEL * c,UINT * ret)1318 UINT OvsGetAckReplyList(OPENVPN_CHANNEL *c, UINT *ret)
1319 {
1320 UINT i;
1321 LIST *o = NULL;
1322 UINT num;
1323 // Validate arguments
1324 if (c == NULL || ret == NULL)
1325 {
1326 return 0;
1327 }
1328
1329 num = MIN(LIST_NUM(c->AckReplyList), OPENVPN_MAX_NUMACK);
1330
1331 for (i = 0;i < num;i++)
1332 {
1333 UINT *v = LIST_DATA(c->AckReplyList, i);
1334
1335 if (o == NULL)
1336 {
1337 o = NewListFast(NULL);
1338 }
1339
1340 Add(o, v);
1341
1342 ret[i] = *v;
1343 }
1344
1345 for (i = 0;i < LIST_NUM(o);i++)
1346 {
1347 UINT *v = LIST_DATA(o, i);
1348
1349 Delete(c->AckReplyList, v);
1350
1351 Free(v);
1352 }
1353
1354 ReleaseList(o);
1355
1356 return num;
1357 }
1358
1359 // Release the channel
OvsFreeChannel(OPENVPN_CHANNEL * c)1360 void OvsFreeChannel(OPENVPN_CHANNEL *c)
1361 {
1362 UINT i;
1363 // Validate arguments
1364 if (c == NULL)
1365 {
1366 return;
1367 }
1368
1369 if (c->SslPipe != NULL)
1370 {
1371 FreeSslPipe(c->SslPipe);
1372 }
1373
1374 ReleaseIntList(c->AckReplyList);
1375
1376 for (i = 0;i < LIST_NUM(c->SendControlPacketList);i++)
1377 {
1378 OPENVPN_CONTROL_PACKET *p = LIST_DATA(c->SendControlPacketList, i);
1379
1380 OvsFreeControlPacket(p);
1381 }
1382
1383 ReleaseList(c->SendControlPacketList);
1384
1385 FreeCipher(c->CipherDecrypt);
1386 FreeCipher(c->CipherEncrypt);
1387
1388 FreeMd(c->MdRecv);
1389 FreeMd(c->MdSend);
1390
1391 if (c->ClientCert.X != NULL)
1392 {
1393 FreeX(c->ClientCert.X);
1394 }
1395
1396 Free(c);
1397 }
1398
1399 // Create a new channel
OvsNewChannel(OPENVPN_SESSION * se,UCHAR key_id)1400 OPENVPN_CHANNEL *OvsNewChannel(OPENVPN_SESSION *se, UCHAR key_id)
1401 {
1402 OPENVPN_CHANNEL *c;
1403 // Validate arguments
1404 if (se == NULL)
1405 {
1406 return NULL;
1407 }
1408
1409 c = ZeroMalloc(sizeof(OPENVPN_CHANNEL));
1410
1411 c->Session = se;
1412 c->Server = se->Server;
1413
1414 c->Status = OPENVPN_CHANNEL_STATUS_INIT;
1415
1416 c->AckReplyList = NewIntList(true);
1417
1418 c->SendControlPacketList = NewListFast(NULL);
1419
1420 c->KeyId = key_id;
1421
1422 Rand(c->NextIv, sizeof(c->NextIv));
1423
1424 //c->NextRekey = se->Server->Now + (UINT64)5000;
1425
1426 se->LastCreatedChannelIndex = key_id;
1427
1428 return c;
1429 }
1430
1431 // Create a new server-side channel ID
OvsNewServerSessionId(OPENVPN_SERVER * s)1432 UINT64 OvsNewServerSessionId(OPENVPN_SERVER *s)
1433 {
1434 // Validate arguments
1435 if (s == NULL)
1436 {
1437 return 0;
1438 }
1439
1440 while (true)
1441 {
1442 UINT64 id = Rand64();
1443 UINT i;
1444 bool exists = false;
1445
1446 if (id == 0 || id == (UINT64)(0xFFFFFFFFFFFFFFFFULL))
1447 {
1448 continue;
1449 }
1450
1451 for (i = 0;i < LIST_NUM(s->SessionList);i++)
1452 {
1453 OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i);
1454 if (se->ServerSessionId == id)
1455 {
1456 exists = true;
1457 }
1458 }
1459
1460 if (exists == false)
1461 {
1462 return id;
1463 }
1464 }
1465 }
1466
1467 // Build and submit the OpenVPN data packet
OvsSendDataPacket(OPENVPN_CHANNEL * c,UCHAR key_id,UINT data_packet_id,void * data,UINT data_size)1468 void OvsSendDataPacket(OPENVPN_CHANNEL *c, UCHAR key_id, UINT data_packet_id, void *data, UINT data_size)
1469 {
1470 UCHAR uc;
1471 UCHAR *encrypted_data;
1472 UINT encrypted_size;
1473 UCHAR *dest_data;
1474 UINT dest_size;
1475 UINT r;
1476
1477 // Validate arguments
1478 if (c == NULL || data == NULL || data_size == 0)
1479 {
1480 return;
1481 }
1482
1483 uc = ((OPENVPN_P_DATA_V1 << 3) & 0xF8) | (key_id & 0x07);
1484
1485 // Generate the data to be encrypted
1486
1487 encrypted_size = sizeof(UINT) + data_size;
1488 encrypted_data = ZeroMalloc(encrypted_size);
1489
1490 WRITE_UINT(encrypted_data, data_packet_id);
1491 Copy(encrypted_data + sizeof(UINT), data, data_size);
1492
1493 // Prepare a buffer to store the results
1494 dest_data = Malloc(sizeof(UCHAR) + c->MdSend->Size + c->CipherEncrypt->IvSize + encrypted_size + 256);
1495
1496 // Encrypt
1497 r = CipherProcess(c->CipherEncrypt, c->NextIv, dest_data + sizeof(UCHAR) + c->MdSend->Size + c->CipherEncrypt->IvSize,
1498 encrypted_data, encrypted_size);
1499 dest_size = sizeof(UCHAR) + c->MdSend->Size + c->CipherEncrypt->IvSize + r;
1500
1501 // Copy the IV
1502 Copy(dest_data + sizeof(UCHAR) + c->MdSend->Size, c->NextIv, c->CipherEncrypt->IvSize);
1503
1504 // Calculate the HMAC
1505 MdProcess(c->MdSend, dest_data + sizeof(UCHAR), dest_data + sizeof(UCHAR) + c->MdSend->Size,
1506 dest_size - sizeof(UCHAR) - c->MdSend->Size);
1507
1508 // Update the NextIV
1509 Copy(c->NextIv, dest_data + dest_size - c->CipherEncrypt->IvSize, c->CipherEncrypt->IvSize);
1510
1511 // Op-code
1512 dest_data[0] = uc;
1513
1514 OvsSendPacketRawNow(c->Server, c->Session, dest_data, dest_size);
1515
1516 Free(encrypted_data);
1517 }
1518
1519 // Build an OpenVPN control packet
OvsBuildPacket(OPENVPN_PACKET * p)1520 BUF *OvsBuildPacket(OPENVPN_PACKET *p)
1521 {
1522 BUF *b;
1523 UCHAR uc;
1524 UINT num_ack;
1525 // Validate arguments
1526 if (p == NULL)
1527 {
1528 return NULL;
1529 }
1530
1531 b = NewBuf();
1532
1533 // OpCode + KeyID
1534 uc = ((p->OpCode << 3) & 0xF8) | (p->KeyId & 0x07);
1535 WriteBufChar(b, uc);
1536
1537 if (p->OpCode == OPENVPN_P_DATA_V1)
1538 {
1539 // Data Packet
1540 WriteBuf(b, p->Data, p->DataSize);
1541 SeekBuf(b, 0, 0);
1542 return b;
1543 }
1544
1545 // Sender Channel ID
1546 WriteBufInt64(b, p->MySessionId);
1547
1548 // NumAck
1549 num_ack = MIN(p->NumAck, OPENVPN_MAX_NUMACK);
1550 WriteBufChar(b, (UCHAR)num_ack);
1551
1552 if (p->NumAck >= 1)
1553 {
1554 UINT i;
1555
1556 for (i = 0;i < num_ack;i++)
1557 {
1558 WriteBufInt(b, (UCHAR)p->AckPacketId[i]);
1559 }
1560
1561 // Received Channel ID
1562 WriteBufInt64(b, p->YourSessionId);
1563 }
1564
1565 if (p->OpCode != OPENVPN_P_ACK_V1)
1566 {
1567 // Packet ID
1568 WriteBufInt(b, p->PacketId);
1569
1570 // Payload
1571 if (p->DataSize >= 1 && p->Data != NULL)
1572 {
1573 WriteBuf(b, p->Data, p->DataSize);
1574 }
1575 }
1576
1577 SeekBuf(b, 0, 0);
1578
1579 return b;
1580 }
1581
1582 // Parse the OpenVPN packet
OvsParsePacket(UCHAR * data,UINT size)1583 OPENVPN_PACKET *OvsParsePacket(UCHAR *data, UINT size)
1584 {
1585 UCHAR uc;
1586 OPENVPN_PACKET *ret = NULL;
1587 // Validate arguments
1588 if (data == NULL || size == 0)
1589 {
1590 return NULL;
1591 }
1592
1593 ret = ZeroMalloc(sizeof(OPENVPN_PACKET));
1594
1595 // OpCode + KeyID
1596 if (size < 1)
1597 {
1598 goto LABEL_ERROR;
1599 }
1600 uc = *((UCHAR *)data);
1601 data++;
1602 size--;
1603
1604 ret->OpCode = ((uc & 0xF8) >> 3) & 0x1F;
1605 ret->KeyId = uc & 0x07;
1606
1607 if (ret->OpCode == OPENVPN_P_DATA_V1)
1608 {
1609 // Data packet
1610 ret->DataSize = size;
1611 ret->Data = Clone(data, size);
1612 return ret;
1613 }
1614
1615 // Sender Channel ID
1616 if (size < sizeof(UINT64))
1617 {
1618 goto LABEL_ERROR;
1619 }
1620 ret->MySessionId = READ_UINT64(data);
1621 data += sizeof(UINT64);
1622 size -= sizeof(UINT64);
1623
1624 // ACK
1625 if (size < 1)
1626 {
1627 goto LABEL_ERROR;
1628 }
1629 uc = *((UCHAR *)data);
1630 data++;
1631 size--;
1632
1633 ret->NumAck = uc;
1634
1635 if (ret->NumAck > 4)
1636 {
1637 goto LABEL_ERROR;
1638 }
1639
1640 if (ret->NumAck >= 1)
1641 {
1642 UINT i;
1643
1644 if (size < (sizeof(UINT) * (UINT)ret->NumAck + sizeof(UINT64)))
1645 {
1646 goto LABEL_ERROR;
1647 }
1648
1649 for (i = 0;i < ret->NumAck;i++)
1650 {
1651 UINT ui;
1652
1653 ui = READ_UINT(data);
1654
1655 ret->AckPacketId[i] = ui;
1656
1657 data += sizeof(UINT);
1658 size -= sizeof(UINT);
1659 }
1660
1661 ret->YourSessionId = READ_UINT64(data);
1662 data += sizeof(UINT64);
1663 size -= sizeof(UINT64);
1664 }
1665
1666 if (ret->OpCode != OPENVPN_P_ACK_V1)
1667 {
1668 // Read the Packet ID Because in the case of other than ACK
1669 if (size < sizeof(UINT))
1670 {
1671 goto LABEL_ERROR;
1672 }
1673
1674 ret->PacketId = READ_UINT(data);
1675 data += sizeof(UINT);
1676 size -= sizeof(UINT);
1677
1678 // Payload
1679 ret->DataSize = size;
1680 if (size >= 1)
1681 {
1682 ret->Data = Clone(data, size);
1683 }
1684 }
1685
1686 return ret;
1687
1688 LABEL_ERROR:
1689 Debug("OvsParsePacket Error.\n");
1690 if (ret != NULL)
1691 {
1692 OvsFreePacket(ret);
1693 }
1694 return NULL;
1695 }
1696
1697 // Release the OpenVPN packet
OvsFreePacket(OPENVPN_PACKET * p)1698 void OvsFreePacket(OPENVPN_PACKET *p)
1699 {
1700 // Validate arguments
1701 if (p == NULL)
1702 {
1703 return;
1704 }
1705
1706 if (p->Data != NULL)
1707 {
1708 Free(p->Data);
1709 }
1710
1711 Free(p);
1712 }
1713
1714 // If the session does not exist, create a session
OvsFindOrCreateSession(OPENVPN_SERVER * s,IP * server_ip,UINT server_port,IP * client_ip,UINT client_port,UINT protocol)1715 OPENVPN_SESSION *OvsFindOrCreateSession(OPENVPN_SERVER *s, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, UINT protocol)
1716 {
1717 OPENVPN_SESSION *se;
1718 // Validate arguments
1719 if (s == NULL || server_ip == NULL || server_port == 0 || client_ip == NULL || client_port == 0)
1720 {
1721 return NULL;
1722 }
1723
1724 se = OvsSearchSession(s, server_ip, server_port, client_ip, client_port, protocol);
1725 if (se == NULL)
1726 {
1727 se = OvsNewSession(s, server_ip, server_port, client_ip, client_port, protocol);
1728
1729 if (se != NULL)
1730 {
1731 Insert(s->SessionList, se);
1732 }
1733 }
1734
1735 return se;
1736 }
1737
1738 // Get the number of sessions currently connected from the IP address of the client
OvsGetNumSessionByClientIp(OPENVPN_SERVER * s,IP * ip)1739 UINT OvsGetNumSessionByClientIp(OPENVPN_SERVER *s, IP *ip)
1740 {
1741 UINT i;
1742 UINT ret = 0;
1743 // Validate arguments
1744 if (s == NULL || ip == NULL)
1745 {
1746 return 0;
1747 }
1748
1749 for (i = 0;i < LIST_NUM(s->SessionList);i++)
1750 {
1751 OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i);
1752
1753 if (CmpIpAddr(&se->ClientIp, ip) == 0)
1754 {
1755 ret++;
1756 }
1757 }
1758
1759 return ret;
1760 }
1761
1762 // Create a new session
OvsNewSession(OPENVPN_SERVER * s,IP * server_ip,UINT server_port,IP * client_ip,UINT client_port,UINT protocol)1763 OPENVPN_SESSION *OvsNewSession(OPENVPN_SERVER *s, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, UINT protocol)
1764 {
1765 OPENVPN_SESSION *se;
1766 char server_ip_str[MAX_SIZE];
1767 char client_ip_str[MAX_SIZE];
1768 // Validate arguments
1769 if (s == NULL || server_ip == NULL || server_port == 0 || client_ip == NULL || client_port == 0)
1770 {
1771 return NULL;
1772 }
1773
1774
1775 if (OvsGetNumSessionByClientIp(s, client_ip) > OPENVPN_QUOTA_MAX_NUM_SESSIONS_PER_IP)
1776 {
1777 // Number of sessions from the same IP address too many
1778 return NULL;
1779 }
1780
1781 if (LIST_NUM(s->SessionList) > OPENVPN_QUOTA_MAX_NUM_SESSIONS)
1782 {
1783 // Too many OpenVPN sessions
1784 return NULL;
1785 }
1786
1787 se = ZeroMalloc(sizeof(OPENVPN_SESSION));
1788
1789 se->Server = s;
1790
1791 Copy(&se->ClientIp, client_ip, sizeof(IP));
1792 se->ClientPort = client_port;
1793
1794 Copy(&se->ServerIp, server_ip, sizeof(IP));
1795 se->ServerPort = server_port;
1796
1797 se->LastCommTick = s->Now;
1798
1799 se->Protocol = protocol;
1800
1801 se->ServerSessionId = OvsNewServerSessionId(se->Server);
1802
1803 se->CreatedTick = s->Now;
1804
1805 se->Id = s->NextSessionId;
1806 s->NextSessionId++;
1807
1808 IPToStr(server_ip_str, sizeof(server_ip_str), server_ip);
1809 IPToStr(client_ip_str, sizeof(client_ip_str), client_ip);
1810 Debug("OpenVPN New Session: %s:%u -> %s:%u Proto=%u\n", server_ip_str, server_port,
1811 client_ip_str, client_port, protocol);
1812
1813 //OvsLog(s, se, NULL, "LO_NEW_SESSION", (protocol == OPENVPN_PROTOCOL_UDP ? "UDP" : "TCP"));
1814
1815 return se;
1816 }
1817
1818 // Release the session
OvsFreeSession(OPENVPN_SESSION * se)1819 void OvsFreeSession(OPENVPN_SESSION *se)
1820 {
1821 UINT i;
1822 // Validate arguments
1823 if (se == NULL)
1824 {
1825 return;
1826 }
1827
1828 // If there is IP addresses which is got from a DHCP server in the session, release it
1829 if (se->Ipc != NULL)
1830 {
1831 if (se->Mode == OPENVPN_MODE_L3)
1832 {
1833 if (se->IpcAsync != NULL)
1834 {
1835 IP dhcp_ip;
1836
1837 UINTToIP(&dhcp_ip, se->IpcAsync->L3ClientAddressOption.ServerAddress);
1838
1839 IPCDhcpFreeIP(se->Ipc, &dhcp_ip);
1840 IPCProcessL3Events(se->Ipc);
1841 }
1842 }
1843 }
1844
1845 // Release the channel
1846 for (i = 0;i < OPENVPN_NUM_CHANNELS;i++)
1847 {
1848 OPENVPN_CHANNEL *c = se->Channels[i];
1849
1850 if (c != NULL)
1851 {
1852 OvsFreeChannel(c);
1853 }
1854 }
1855
1856 // Release the IPC
1857 if (se->Ipc != NULL)
1858 {
1859 FreeIPC(se->Ipc);
1860 }
1861
1862 if (se->IpcAsync != NULL)
1863 {
1864 FreeIPCAsync(se->IpcAsync);
1865 }
1866
1867 Free(se);
1868 }
1869
1870 // Search the session from the endpoint information
OvsSearchSession(OPENVPN_SERVER * s,IP * server_ip,UINT server_port,IP * client_ip,UINT client_port,UINT protocol)1871 OPENVPN_SESSION *OvsSearchSession(OPENVPN_SERVER *s, IP *server_ip, UINT server_port, IP *client_ip, UINT client_port, UINT protocol)
1872 {
1873 OPENVPN_SESSION *se;
1874 OPENVPN_SESSION t;
1875 // Validate arguments
1876 if (s == NULL || server_ip == NULL || server_port == 0 || client_ip == NULL || client_port == 0)
1877 {
1878 return NULL;
1879 }
1880
1881 Copy(&t.ClientIp, client_ip, sizeof(IP));
1882 t.ClientPort = client_port;
1883 Copy(&t.ServerIp, server_ip, sizeof(IP));
1884 t.ServerPort = server_port;
1885 t.Protocol = protocol;
1886
1887 se = Search(s->SessionList, &t);
1888
1889 return se;
1890 }
1891
1892 // Receive packets in the OpenVPN server
OvsRecvPacket(OPENVPN_SERVER * s,LIST * recv_packet_list,UINT protocol)1893 void OvsRecvPacket(OPENVPN_SERVER *s, LIST *recv_packet_list, UINT protocol)
1894 {
1895 UINT i, j;
1896 LIST *delete_session_list = NULL;
1897 // Validate arguments
1898 if (s == NULL || recv_packet_list == NULL)
1899 {
1900 return;
1901 }
1902
1903 s->Now = Tick64();
1904
1905 // Process for all sessions
1906 for (i = 0;i < LIST_NUM(s->SessionList);i++)
1907 {
1908 OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i);
1909
1910 if (se->Ipc != NULL)
1911 {
1912 if (se->Mode == OPENVPN_MODE_L3)
1913 {
1914 // Flush the ARP table of the IPC
1915 IPCFlushArpTableEx(se->Ipc, s->Now);
1916 }
1917 }
1918 }
1919
1920 // Process received packets
1921 for (i = 0;i < LIST_NUM(recv_packet_list);i++)
1922 {
1923 UDPPACKET *p = LIST_DATA(recv_packet_list, i);
1924
1925 OvsProceccRecvPacket(s, p, protocol);
1926 }
1927
1928 // Treat for all sessions and all channels
1929 for (i = 0;i < LIST_NUM(s->SessionList);i++)
1930 {
1931 OPENVPN_CHANNEL *latest_channel = NULL;
1932 UINT64 max_tick = 0;
1933 OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i);
1934 bool is_disconnected = false;
1935
1936 if (se->Ipc != NULL)
1937 {
1938 if (se->Mode == OPENVPN_MODE_L3)
1939 {
1940 IPCProcessL3Events(se->Ipc);
1941 }
1942 }
1943
1944 for (j = 0;j < OPENVPN_NUM_CHANNELS;j++)
1945 {
1946 OPENVPN_CHANNEL *c = se->Channels[j];
1947
1948 if (c != NULL)
1949 {
1950 if (c->RekeyInitiated == false && ((c->NextRekey <= s->Now && c->NextRekey != 0) || (c->LastDataPacketId >= OPENVPN_MAX_PACKET_ID_FOR_TRIGGER_REKEY)))
1951 {
1952 OPENVPN_CHANNEL *c2;
1953 // Send a soft reset by creating a new channel
1954 UINT next_channel_id = se->LastCreatedChannelIndex + 1;
1955 if (next_channel_id >= OPENVPN_NUM_CHANNELS)
1956 {
1957 next_channel_id = 1;
1958 }
1959 if (se->Channels[next_channel_id] != NULL)
1960 {
1961 // Release when there is a channel data already
1962 OvsFreeChannel(se->Channels[next_channel_id]);
1963 se->Channels[next_channel_id] = NULL;
1964 }
1965
1966 // Create a new channel
1967 c2 = OvsNewChannel(se, (UCHAR)next_channel_id);
1968 c2->IsInitiatorServer = true;
1969 se->Channels[next_channel_id] = c2;
1970 Debug("OpenVPN New Channel for Re-Keying :%u\n", next_channel_id);
1971 OvsLog(s, se, c, "LO_INITIATE_REKEY");
1972
1973 // Send a soft reset
1974 OvsSendControlPacket(c2, OPENVPN_P_CONTROL_SOFT_RESET_V1, NULL, 0);
1975
1976 c->RekeyInitiated = true;
1977 }
1978 }
1979
1980 if (c != NULL)
1981 {
1982 switch (c->Status)
1983 {
1984 case OPENVPN_CHANNEL_STATUS_TLS_VPN_CONNECTING:
1985 // Check whether the connection process completed if there is a channel running a VPN connection process
1986 if (se->IpcAsync != NULL)
1987 {
1988 if (se->IpcAsync->Done)
1989 {
1990 if (se->IpcAsync->Ipc != NULL)
1991 {
1992 char option_str[4096];
1993 char l3_options[MAX_SIZE];
1994
1995 // Successful in VPN connection
1996 Debug("OpenVPN Channel %u Established (new key).\n", j);
1997 OvsLog(s, se, c, "LO_CHANNEL_ESTABLISHED");
1998
1999 // Return the PUSH_REPLY
2000 Format(option_str, sizeof(option_str),
2001 "PUSH_REPLY,ping %u,ping-restart %u",
2002 (OPENVPN_PING_SEND_INTERVAL / 1000),
2003 (OPENVPN_RECV_TIMEOUT / 1000));
2004
2005 if (se->Mode == OPENVPN_MODE_L3)
2006 {
2007 // Add such as the IP address that was acquired from the DHCP server
2008 // if the L3 mode to the option character string
2009 DHCP_OPTION_LIST *cao = &se->IpcAsync->L3ClientAddressOption;
2010 char ip_client[64];
2011 char ip_tunnel_endpoint[64];
2012 UINT ip_tunnel_endpoint_32;
2013 char ip_network[64];
2014 char ip_subnet_mask[64];
2015 char ip_dns1[64];
2016 char ip_dns2[64];
2017 char ip_wins1[64];
2018 char ip_wins2[64];
2019 char ip_defgw[64];
2020
2021 ClearStr(ip_dns1, sizeof(ip_dns1));
2022 ClearStr(ip_dns2, sizeof(ip_dns2));
2023 ClearStr(ip_wins1, sizeof(ip_wins1));
2024 ClearStr(ip_wins2, sizeof(ip_wins2));
2025 ClearStr(ip_defgw, sizeof(ip_defgw));
2026
2027 IPToStr32(ip_client, sizeof(ip_client),
2028 cao->ClientAddress);
2029
2030 // Generate a virtual gateway address to be passed to the OpenVPN
2031 ip_tunnel_endpoint_32 = Endian32(cao->ClientAddress);
2032 ip_tunnel_endpoint_32++;
2033 ip_tunnel_endpoint_32 = Endian32(ip_tunnel_endpoint_32);
2034 IPToStr32(ip_tunnel_endpoint, sizeof(ip_tunnel_endpoint), ip_tunnel_endpoint_32);
2035
2036 // Create a subnet information for the LAN
2037 IPToStr32(ip_network, sizeof(ip_network),
2038 GetNetworkAddress(cao->ClientAddress,
2039 cao->SubnetMask));
2040
2041 IPToStr32(ip_subnet_mask, sizeof(ip_subnet_mask),
2042 cao->SubnetMask);
2043
2044 Format(l3_options, sizeof(l3_options),
2045 ",ifconfig %s %s",
2046 // ",ifconfig %s %s,route %s %s %s 1",
2047 ip_client, ip_tunnel_endpoint, ip_network, ip_subnet_mask,
2048 ip_tunnel_endpoint);
2049 StrCat(option_str, sizeof(option_str), l3_options);
2050
2051 // Domain name
2052 if (IsEmptyStr(cao->DomainName) == false)
2053 {
2054 Format(l3_options, sizeof(l3_options),
2055 ",dhcp-option DOMAIN %s", cao->DomainName);
2056 StrCat(option_str, sizeof(option_str), l3_options);
2057 }
2058
2059 // DNS server address 1
2060 if (cao->DnsServer != 0)
2061 {
2062 char ip_str[64];
2063 IPToStr32(ip_str, sizeof(ip_str), cao->DnsServer);
2064 Format(l3_options, sizeof(l3_options),
2065 ",dhcp-option DNS %s", ip_str);
2066 StrCat(option_str, sizeof(option_str), l3_options);
2067
2068 StrCpy(ip_dns1, sizeof(ip_dns1), ip_str);
2069 }
2070
2071 // DNS server address 2
2072 if (cao->DnsServer2 != 0)
2073 {
2074 char ip_str[64];
2075 IPToStr32(ip_str, sizeof(ip_str), cao->DnsServer2);
2076 Format(l3_options, sizeof(l3_options),
2077 ",dhcp-option DNS %s", ip_str);
2078 StrCat(option_str, sizeof(option_str), l3_options);
2079
2080 StrCpy(ip_dns2, sizeof(ip_dns2), ip_str);
2081 }
2082
2083 // WINS address 1
2084 if (cao->WinsServer != 0)
2085 {
2086 char ip_str[64];
2087 IPToStr32(ip_str, sizeof(ip_str), cao->WinsServer);
2088 Format(l3_options, sizeof(l3_options),
2089 ",dhcp-option WINS %s", ip_str);
2090 StrCat(option_str, sizeof(option_str), l3_options);
2091
2092 StrCpy(ip_wins1, sizeof(ip_wins1), ip_str);
2093 }
2094
2095 // WINS address 2
2096 if (cao->WinsServer2 != 0)
2097 {
2098 char ip_str[64];
2099 IPToStr32(ip_str, sizeof(ip_str), cao->WinsServer2);
2100 Format(l3_options, sizeof(l3_options),
2101 ",dhcp-option WINS %s", ip_str);
2102 StrCat(option_str, sizeof(option_str), l3_options);
2103
2104 StrCpy(ip_wins2, sizeof(ip_wins2), ip_str);
2105 }
2106
2107 // Default gateway
2108 if (cao->Gateway != 0)
2109 {
2110 Format(l3_options, sizeof(l3_options),
2111 ",route-gateway %s,redirect-gateway def1", ip_tunnel_endpoint);
2112 StrCat(option_str, sizeof(option_str), l3_options);
2113
2114 IPToStr32(ip_defgw, sizeof(ip_defgw), cao->Gateway);
2115 }
2116 else
2117 {
2118 #if 0 // Currently disabled
2119 // If the default gateway is not specified, add the static routing table
2120 // entry for the local IP subnet
2121 IP local_network;
2122 IP client_ip;
2123 IP subnet_mask;
2124
2125 UINTToIP(&client_ip, cao->ClientAddress);
2126 UINTToIP(&subnet_mask, cao->SubnetMask);
2127
2128 Zero(&local_network, sizeof(IP));
2129 IPAnd4(&local_network, &client_ip, &subnet_mask);
2130
2131 Format(l3_options, sizeof(l3_options),
2132 ",route %r %r vpn_gateway",
2133 &local_network,
2134 &cao->SubnetMask);
2135
2136 StrCat(option_str, sizeof(option_str), l3_options);
2137 #endif
2138 }
2139
2140 // Classless routing table
2141 if (cao->ClasslessRoute.NumExistingRoutes >= 1)
2142 {
2143 UINT i;
2144 for (i = 0;i < MAX_DHCP_CLASSLESS_ROUTE_ENTRIES;i++)
2145 {
2146 DHCP_CLASSLESS_ROUTE *r = &cao->ClasslessRoute.Entries[i];
2147
2148 if (r->Exists)
2149 {
2150 Format(l3_options, sizeof(l3_options),
2151 ",route %r %r vpn_gateway",
2152 &r->Network, &r->SubnetMask);
2153
2154 StrCat(option_str, sizeof(option_str), l3_options);
2155 }
2156 }
2157 }
2158
2159 OvsLog(s, se, c, "LP_SET_IPV4_PARAM",
2160 ip_client, ip_subnet_mask, ip_defgw, ip_dns1, ip_dns2, ip_wins1, ip_wins2);
2161 }
2162
2163 WriteFifo(c->SslPipe->SslInOut->SendFifo, option_str, StrSize(option_str));
2164
2165 Debug("Push Str: %s\n", option_str);
2166 OvsLog(s, se, c, "LO_PUSH_REPLY", option_str);
2167
2168 StrCpy(se->PushReplyStr, sizeof(se->PushReplyStr), option_str);
2169
2170 se->Ipc = se->IpcAsync->Ipc;
2171 se->IpcAsync->Ipc = NULL;
2172
2173 s->SessionEstablishedCount++;
2174
2175 // Set a Sock Event of IPC to Sock Event of the UDP Listener
2176 IPCSetSockEventWhenRecvL2Packet(se->Ipc, s->SockEvent);
2177
2178 // State transition
2179 c->Status = OPENVPN_CHANNEL_STATUS_ESTABLISHED;
2180 c->EstablishedTick = s->Now;
2181 se->Established = true;
2182 se->LastCommTick = Tick64();
2183 }
2184 else
2185 {
2186 char *str;
2187
2188 if (se->IpcAsync->DhcpAllocFailed)
2189 {
2190 OvsLog(s, se, c, "LP_DHCP_REQUEST_NG");
2191 }
2192
2193 // Failed to connect VPN
2194 Debug("OpenVPN Channel %u Failed.\n", j);
2195 OvsLog(s, se, c, "LO_CHANNEL_FAILED");
2196
2197 // Return the AUTH_FAILED
2198 str = "AUTH_FAILED";
2199 WriteFifo(c->SslPipe->SslInOut->SendFifo, str, StrSize(str));
2200
2201 s->SessionEstablishedCount++;
2202
2203 // State transition
2204 c->Status = OPENVPN_CHANNEL_STATUS_DISCONNECTED;
2205
2206 FreeIPCAsync(se->IpcAsync);
2207 se->IpcAsync = NULL;
2208 }
2209 }
2210 }
2211 break;
2212
2213 case OPENVPN_CHANNEL_STATUS_ESTABLISHED:
2214 // Monitor the IPC whether not disconnected when there is a VPN connection completed channel
2215 if (IsIPCConnected(se->Ipc) == false)
2216 {
2217 // Send the RESTART since IPC is disconnected
2218 char *str = "RESTART";
2219 Debug("OpenVPN Channel %u Disconnected by HUB.\n", j);
2220
2221 OvsLog(s, se, c, "LO_CHANNEL_DISCONNECTED_BY_HUB");
2222
2223 WriteFifo(c->SslPipe->SslInOut->SendFifo, str, StrSize(str));
2224
2225 // State transition
2226 c->Status = OPENVPN_CHANNEL_STATUS_DISCONNECTED;
2227
2228 // Set the session to disconnected state
2229 se->Established = false;
2230 se->LastCommTick = s->Now;
2231 }
2232 break;
2233 }
2234 }
2235
2236 if (c != NULL)
2237 {
2238 // If there is a packet to be transmitted physically in SSL, send it
2239 if (c->SslPipe != NULL && SyncSslPipe(c->SslPipe))
2240 {
2241 if (FifoSize(c->SslPipe->RawOut->RecvFifo) >= 1)
2242 {
2243 Debug("RawOut Fifo Size (c=%u): %u\n", c->KeyId, FifoSize(c->SslPipe->RawOut->RecvFifo));
2244
2245 OvsSendControlPacketWithAutoSplit(c, OPENVPN_P_CONTROL_V1,
2246 FifoPtr(c->SslPipe->RawOut->RecvFifo),
2247 FifoSize(c->SslPipe->RawOut->RecvFifo));
2248
2249 ReadFifo(c->SslPipe->RawOut->RecvFifo, NULL, FifoSize(c->SslPipe->RawOut->RecvFifo));
2250 }
2251 }
2252 }
2253
2254 if (c != NULL)
2255 {
2256 UINT num;
2257 UINT acks[OPENVPN_MAX_NUMACK];
2258 UINT k;
2259
2260 // Packet transmission
2261 for (k = 0;k < LIST_NUM(c->SendControlPacketList);k++)
2262 {
2263 OPENVPN_CONTROL_PACKET *cp = LIST_DATA(c->SendControlPacketList, k);
2264
2265 if (cp->NextSendTime <= s->Now)
2266 {
2267 if (cp->NoResend == false || cp->NumSent == 0) // To address the UDP reflection amplification attack: https://github.com/SoftEtherVPN/SoftEtherVPN/issues/1001
2268 {
2269 OPENVPN_PACKET *p;
2270
2271 cp->NumSent++;
2272
2273 num = OvsGetAckReplyList(c, acks);
2274
2275 p = OvsNewControlPacket(cp->OpCode, j, se->ServerSessionId, num, acks,
2276 se->ClientSessionId, cp->PacketId, cp->DataSize, cp->Data);
2277
2278 OvsSendPacketNow(s, se, p);
2279
2280 OvsFreePacket(p);
2281
2282 cp->NextSendTime = s->Now + (UINT64)OPENVPN_CONTROL_PACKET_RESEND_INTERVAL;
2283
2284 AddInterrupt(s->Interrupt, cp->NextSendTime);
2285 }
2286 }
2287 }
2288
2289 // If the response with an ACK-only packet is required, respond such that
2290 num = OvsGetAckReplyList(c, acks);
2291
2292 if (num >= 1)
2293 {
2294 OPENVPN_PACKET *p = OvsNewControlPacket(OPENVPN_P_ACK_V1, j, se->ServerSessionId,
2295 num, acks, se->ClientSessionId, 0, 0, NULL);
2296
2297 OvsSendPacketNow(s, se, p);
2298
2299 OvsFreePacket(p);
2300 }
2301 }
2302 }
2303
2304 if (se->Ipc != NULL)
2305 {
2306 if (se->Mode == OPENVPN_MODE_L3)
2307 {
2308 if (se->IpcAsync != NULL)
2309 {
2310 // Update DHCP address
2311 if (se->IpcAsync->L3NextDhcpRenewTick <= s->Now)
2312 {
2313 IP ip;
2314
2315 se->IpcAsync->L3NextDhcpRenewTick = s->Now + se->IpcAsync->L3DhcpRenewInterval;
2316
2317 UINTToIP(&ip, se->IpcAsync->L3ClientAddressOption.ServerAddress);
2318
2319 IPCDhcpRenewIP(se->Ipc, &ip);
2320 }
2321 }
2322
2323 IPCProcessL3Events(se->Ipc);
2324 }
2325
2326 IPCProcessInterrupts(se->Ipc);
2327 }
2328
2329 // Choose the latest channel in all established channels
2330 for (j = 0;j < OPENVPN_NUM_CHANNELS;j++)
2331 {
2332 OPENVPN_CHANNEL *c = se->Channels[j];
2333
2334 if (c != NULL)
2335 {
2336 if (c->Status == OPENVPN_CHANNEL_STATUS_ESTABLISHED)
2337 {
2338 if (max_tick <= c->EstablishedTick)
2339 {
2340 max_tick = c->EstablishedTick;
2341 latest_channel = c;
2342 }
2343 }
2344 }
2345 }
2346
2347 if (se->Established == false)
2348 {
2349 latest_channel = NULL;
2350 }
2351
2352 // Send the data using the latest channel (when there is no transmission channel, suck out the queue simply)
2353 if (se->Mode == OPENVPN_MODE_L2)
2354 {
2355 // Get an Ethernet frame from IPC
2356 while (true)
2357 {
2358 BLOCK *b = IPCRecvL2(se->Ipc);
2359 if (b == NULL)
2360 {
2361 break;
2362 }
2363
2364 if (latest_channel != NULL && s->SupressSendPacket == false)
2365 {
2366 OvsSendDataPacket(latest_channel, latest_channel->KeyId, ++latest_channel->LastDataPacketId, b->Buf, b->Size);
2367 }
2368
2369 FreeBlock(b);
2370 }
2371 }
2372 else
2373 {
2374 // Get an IPv4 packet from IPC
2375 while (true)
2376 {
2377 BLOCK *b = IPCRecvIPv4(se->Ipc);
2378 if (b == NULL)
2379 {
2380 break;
2381 }
2382
2383 if (latest_channel != NULL && s->SupressSendPacket == false)
2384 {
2385 OvsSendDataPacket(latest_channel, latest_channel->KeyId, ++latest_channel->LastDataPacketId, b->Buf, b->Size);
2386 }
2387
2388 FreeBlock(b);
2389 }
2390 }
2391
2392 // Send a Ping
2393 if (latest_channel != NULL)
2394 {
2395 if ((se->NextPingSendTick == 0) || (se->NextPingSendTick <= s->Now))
2396 {
2397 se->NextPingSendTick = s->Now + (UINT64)(OPENVPN_PING_SEND_INTERVAL);
2398
2399 OvsSendDataPacket(latest_channel, latest_channel->KeyId, ++latest_channel->LastDataPacketId,
2400 ping_signature, sizeof(ping_signature));
2401 //Debug(".");
2402
2403 AddInterrupt(s->Interrupt, se->NextPingSendTick);
2404 }
2405 }
2406
2407 if ((se->Established == false) && (s->Now >= (se->CreatedTick + (UINT64)OPENVPN_NEW_SESSION_DEADLINE_TIMEOUT)))
2408 {
2409 is_disconnected = true;
2410 }
2411
2412 if (se->Established && (s->Now >= (se->LastCommTick + (UINT64)OPENVPN_RECV_TIMEOUT)))
2413 {
2414 is_disconnected = true;
2415 }
2416
2417 if (is_disconnected)
2418 {
2419 if (delete_session_list == NULL)
2420 {
2421 delete_session_list = NewListFast(NULL);
2422 }
2423
2424 Add(delete_session_list, se);
2425 }
2426 }
2427
2428 if (delete_session_list != NULL)
2429 {
2430 UINT i;
2431
2432 for (i = 0;i < LIST_NUM(delete_session_list);i++)
2433 {
2434 OPENVPN_SESSION *se = LIST_DATA(delete_session_list, i);
2435
2436 Debug("Deleting Session %p\n", se);
2437 //OvsLog(s, se, NULL, "LO_DELETE_SESSION");
2438
2439 OvsFreeSession(se);
2440
2441 s->DisconnectCount++;
2442
2443 Delete(s->SessionList, se);
2444 }
2445
2446 ReleaseList(delete_session_list);
2447 }
2448 }
2449
2450 // Send the packet now
OvsSendPacketNow(OPENVPN_SERVER * s,OPENVPN_SESSION * se,OPENVPN_PACKET * p)2451 void OvsSendPacketNow(OPENVPN_SERVER *s, OPENVPN_SESSION *se, OPENVPN_PACKET *p)
2452 {
2453 BUF *b;
2454 UINT i;
2455 // Validate arguments
2456 if (s == NULL || se == NULL || p == NULL)
2457 {
2458 return;
2459 }
2460
2461 Debug("Sending Opcode=%u ", p->OpCode);
2462 if (p->NumAck >= 1)
2463 {
2464 Debug("Sending ACK Packet IDs (c=%u): ", p->KeyId);
2465 for (i = 0;i < p->NumAck;i++)
2466 {
2467 Debug("%u ", p->AckPacketId[i]);
2468 }
2469 }
2470 Debug("\n");
2471
2472 b = OvsBuildPacket(p);
2473
2474 OvsSendPacketRawNow(s, se, b->Buf, b->Size);
2475
2476 Free(b);
2477 }
OvsSendPacketRawNow(OPENVPN_SERVER * s,OPENVPN_SESSION * se,void * data,UINT size)2478 void OvsSendPacketRawNow(OPENVPN_SERVER *s, OPENVPN_SESSION *se, void *data, UINT size)
2479 {
2480 UDPPACKET *u;
2481
2482 // Validate arguments
2483 if (s == NULL || se == NULL || data == NULL || size == 0)
2484 {
2485 Free(data);
2486 return;
2487 }
2488
2489 u = NewUdpPacket(&se->ServerIp, se->ServerPort, &se->ClientIp, se->ClientPort,
2490 data, size);
2491
2492 Add(s->SendPacketList, u);
2493 }
2494 // Create a new OpenVPN control packet
OvsNewControlPacket(UCHAR opcode,UCHAR key_id,UINT64 my_channel_id,UINT num_ack,UINT * ack_packet_ids,UINT64 your_channel_id,UINT packet_id,UINT data_size,UCHAR * data)2495 OPENVPN_PACKET *OvsNewControlPacket(UCHAR opcode, UCHAR key_id, UINT64 my_channel_id, UINT num_ack,
2496 UINT *ack_packet_ids, UINT64 your_channel_id, UINT packet_id,
2497 UINT data_size, UCHAR *data)
2498 {
2499 OPENVPN_PACKET *p = ZeroMalloc(sizeof(OPENVPN_PACKET));
2500 UINT i;
2501
2502 p->OpCode = opcode;
2503 p->KeyId = key_id;
2504 p->MySessionId = my_channel_id;
2505 p->NumAck = num_ack;
2506
2507 for (i = 0;i < MIN(num_ack, OPENVPN_MAX_NUMACK);i++)
2508 {
2509 p->AckPacketId[i] = ack_packet_ids[i];
2510 }
2511
2512 p->YourSessionId = your_channel_id;
2513 p->PacketId = packet_id;
2514
2515 if (data_size != 0 && data != NULL)
2516 {
2517 p->Data = Clone(data, data_size);
2518 p->DataSize = data_size;
2519 }
2520
2521 return p;
2522 }
2523
2524 // Comparison function of the entries in the session list
OvsCompareSessionList(void * p1,void * p2)2525 int OvsCompareSessionList(void *p1, void *p2)
2526 {
2527 OPENVPN_SESSION *s1, *s2;
2528 int i;
2529 // Validate arguments
2530 if (p1 == NULL || p2 == NULL)
2531 {
2532 return 0;
2533 }
2534 s1 = *(OPENVPN_SESSION **)p1;
2535 s2 = *(OPENVPN_SESSION **)p2;
2536 if (s1 == NULL || s2 == NULL)
2537 {
2538 return 0;
2539 }
2540
2541 i = CmpIpAddr(&s1->Protocol, &s2->Protocol);
2542 if (i != 0)
2543 {
2544 return i;
2545 }
2546
2547 i = CmpIpAddr(&s1->ClientIp, &s2->ClientIp);
2548 if (i != 0)
2549 {
2550 return i;
2551 }
2552
2553 i = COMPARE_RET(s1->ClientPort, s2->ClientPort);
2554 if (i != 0)
2555 {
2556 return i;
2557 }
2558
2559 i = CmpIpAddr(&s1->ServerIp, &s2->ServerIp);
2560 if (i != 0)
2561 {
2562 return i;
2563 }
2564
2565 i = COMPARE_RET(s1->ServerPort, s2->ServerPort);
2566 if (i != 0)
2567 {
2568 return i;
2569 }
2570
2571 return 0;
2572 }
2573
2574 // Identify whether the IP address is compatible to the tun device of OpenVPN
OvsIsCompatibleL3IP(UINT ip)2575 bool OvsIsCompatibleL3IP(UINT ip)
2576 {
2577 IP p;
2578
2579 UINTToIP(&p, ip);
2580 if ((p.addr[3] % 4) == 1)
2581 {
2582 return true;
2583 }
2584
2585 return false;
2586 }
2587
2588 // Get an IP address that is compatible to tun device of the OpenVPN after the specified IP address
OvsGetCompatibleL3IPNext(UINT ip)2589 UINT OvsGetCompatibleL3IPNext(UINT ip)
2590 {
2591 ip = Endian32(ip);
2592
2593 while (true)
2594 {
2595 if (OvsIsCompatibleL3IP(Endian32(ip)))
2596 {
2597 return Endian32(ip);
2598 }
2599
2600 ip++;
2601 }
2602 }
2603
2604 // Create a new OpenVPN server
NewOpenVpnServer(CEDAR * cedar,INTERRUPT_MANAGER * interrupt,SOCK_EVENT * sock_event)2605 OPENVPN_SERVER *NewOpenVpnServer(CEDAR *cedar, INTERRUPT_MANAGER *interrupt, SOCK_EVENT *sock_event)
2606 {
2607 OPENVPN_SERVER *s;
2608 // Validate arguments
2609 if (cedar == NULL)
2610 {
2611 return NULL;
2612 }
2613
2614 s = ZeroMalloc(sizeof(OPENVPN_SERVER));
2615
2616 s->Cedar = cedar;
2617
2618 AddRef(s->Cedar->ref);
2619
2620 s->Interrupt = interrupt;
2621
2622 s->SessionList = NewList(OvsCompareSessionList);
2623 s->SendPacketList = NewListFast(NULL);
2624
2625 s->Now = Tick64();
2626
2627 s->NextSessionId = 1;
2628
2629 if (sock_event != NULL)
2630 {
2631 s->SockEvent = sock_event;
2632 AddRef(s->SockEvent->ref);
2633 }
2634
2635 OvsLog(s, NULL, NULL, "LO_START");
2636
2637 s->Dh = DhNewGroup2();
2638
2639 return s;
2640 }
2641
2642 // Release the OpenVPN server
FreeOpenVpnServer(OPENVPN_SERVER * s)2643 void FreeOpenVpnServer(OPENVPN_SERVER *s)
2644 {
2645 UINT i;
2646 // Validate arguments
2647 if (s == NULL)
2648 {
2649 return;
2650 }
2651
2652 OvsLog(s, NULL, NULL, "LO_STOP");
2653
2654 // Release the session list
2655 for (i = 0;i < LIST_NUM(s->SessionList);i++)
2656 {
2657 OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i);
2658
2659 OvsFreeSession(se);
2660 }
2661
2662 ReleaseList(s->SessionList);
2663
2664 // Release the packet which is attempting to send
2665 for (i = 0;i < LIST_NUM(s->SendPacketList);i++)
2666 {
2667 UDPPACKET *p = LIST_DATA(s->SendPacketList, i);
2668
2669 FreeUdpPacket(p);
2670 }
2671
2672 ReleaseList(s->SendPacketList);
2673
2674 ReleaseCedar(s->Cedar);
2675
2676 if (s->SockEvent != NULL)
2677 {
2678 ReleaseSockEvent(s->SockEvent);
2679 }
2680
2681 DhFree(s->Dh);
2682
2683 Free(s);
2684 }
2685
2686 // UDP reception procedure
OpenVpnServerUdpListenerProc(UDPLISTENER * u,LIST * packet_list)2687 void OpenVpnServerUdpListenerProc(UDPLISTENER *u, LIST *packet_list)
2688 {
2689 OPENVPN_SERVER_UDP *us;
2690 UINT64 now = Tick64();
2691 // Validate arguments
2692 if (u == NULL || packet_list == NULL)
2693 {
2694 return;
2695 }
2696
2697 us = (OPENVPN_SERVER_UDP *)u->Param;
2698
2699 if (OvsGetNoOpenVpnUdp())
2700 {
2701 // OpenVPN over UDP is disabled
2702 return;
2703 }
2704
2705 if (us->OpenVpnServer != NULL)
2706 {
2707 {
2708 u->PollMyIpAndPort = false;
2709
2710 ClearStr(us->Cedar->OpenVPNPublicPorts, sizeof(us->Cedar->OpenVPNPublicPorts));
2711 }
2712
2713 OvsRecvPacket(us->OpenVpnServer, packet_list, OPENVPN_PROTOCOL_UDP);
2714
2715 UdpListenerSendPackets(u, us->OpenVpnServer->SendPacketList);
2716 DeleteAll(us->OpenVpnServer->SendPacketList);
2717 }
2718 }
2719
2720 // Create an OpenVPN server (UDP mode)
NewOpenVpnServerUdp(CEDAR * cedar)2721 OPENVPN_SERVER_UDP *NewOpenVpnServerUdp(CEDAR *cedar)
2722 {
2723 OPENVPN_SERVER_UDP *u;
2724 // Validate arguments
2725 if (cedar == NULL)
2726 {
2727 return NULL;
2728 }
2729
2730 u = ZeroMalloc(sizeof(OPENVPN_SERVER_UDP));
2731
2732 u->Cedar = cedar;
2733
2734 AddRef(u->Cedar->ref);
2735
2736 // Create a UDP listener
2737 u->UdpListener = NewUdpListener(OpenVpnServerUdpListenerProc, u);
2738
2739 // Create an OpenVPN server
2740 u->OpenVpnServer = NewOpenVpnServer(cedar, u->UdpListener->Interrupts, u->UdpListener->Event);
2741
2742 return u;
2743 }
2744
2745 // Apply the port list to the OpenVPN server
OvsApplyUdpPortList(OPENVPN_SERVER_UDP * u,char * port_list)2746 void OvsApplyUdpPortList(OPENVPN_SERVER_UDP *u, char *port_list)
2747 {
2748 LIST *o;
2749 UINT i;
2750 // Validate arguments
2751 if (u == NULL)
2752 {
2753 return;
2754 }
2755
2756 DeleteAllPortFromUdpListener(u->UdpListener);
2757
2758 o = StrToIntList(port_list, true);
2759
2760 for (i = 0;i < LIST_NUM(o);i++)
2761 {
2762 UINT port = *((UINT *)LIST_DATA(o, i));
2763
2764 if (port >= 1 && port <= 65535)
2765 {
2766 AddPortToUdpListener(u->UdpListener, port);
2767 }
2768 }
2769
2770 ReleaseIntList(o);
2771 }
2772
2773 // Release the OpenVPN server (UDP mode)
FreeOpenVpnServerUdp(OPENVPN_SERVER_UDP * u)2774 void FreeOpenVpnServerUdp(OPENVPN_SERVER_UDP *u)
2775 {
2776 // Validate arguments
2777 if (u == NULL)
2778 {
2779 return;
2780 }
2781
2782 // Stop the UDP listener
2783 FreeUdpListener(u->UdpListener);
2784
2785 // Release the OpenVPN server
2786 FreeOpenVpnServer(u->OpenVpnServer);
2787
2788 ReleaseCedar(u->Cedar);
2789
2790 Free(u);
2791 }
2792
2793 // Check whether it's OpenSSL protocol by looking the first receive buffer of the TCP
OvsCheckTcpRecvBufIfOpenVPNProtocol(UCHAR * buf,UINT size)2794 bool OvsCheckTcpRecvBufIfOpenVPNProtocol(UCHAR *buf, UINT size)
2795 {
2796 if (buf == NULL || size != 2)
2797 {
2798 return false;
2799 }
2800
2801 if (buf[0] == 0x00 && buf[1] == 0x0E)
2802 {
2803 return true;
2804 }
2805
2806 return false;
2807 }
2808
2809 // Run the OpenVPN server in TCP mode
OvsPerformTcpServer(CEDAR * cedar,SOCK * sock)2810 bool OvsPerformTcpServer(CEDAR *cedar, SOCK *sock)
2811 {
2812 OPENVPN_SERVER *s;
2813 INTERRUPT_MANAGER *im;
2814 SOCK_EVENT *se;
2815 FIFO *tcp_recv_fifo;
2816 FIFO *tcp_send_fifo;
2817 UINT buf_size = (128 * 1024);
2818 UCHAR *buf;
2819 UINT64 giveup_time = Tick64() + (UINT64)OPENVPN_NEW_SESSION_DEADLINE_TIMEOUT;
2820 LIST *ovs_recv_packet;
2821 UINT i;
2822 bool ret = false;
2823 // Validate arguments
2824 if (cedar == NULL || sock == NULL)
2825 {
2826 return false;
2827 }
2828
2829 // Initialize
2830 buf = Malloc(buf_size);
2831 im = NewInterruptManager();
2832 se = NewSockEvent();
2833 SetTimeout(sock, TIMEOUT_INFINITE);
2834 JoinSockToSockEvent(sock, se);
2835
2836 tcp_recv_fifo = NewFifoFast();
2837 tcp_send_fifo = NewFifoFast();
2838
2839 ovs_recv_packet = NewListFast(NULL);
2840
2841 // Create an OpenVPN server
2842 s = NewOpenVpnServer(cedar, im, se);
2843
2844 // Main loop
2845 Debug("Entering OpenVPN TCP Server Main Loop.\n");
2846 while (true)
2847 {
2848 UINT next_interval;
2849 bool disconnected = false;
2850 UINT64 now = Tick64();
2851
2852 // Receive data from a TCP socket
2853 while (true)
2854 {
2855 UINT r = Recv(sock, buf, buf_size, false);
2856 if (r == SOCK_LATER)
2857 {
2858 // Can not read any more
2859 break;
2860 }
2861 else if (r == 0)
2862 {
2863 // Disconnected
2864 disconnected = true;
2865 break;
2866 }
2867 else
2868 {
2869 // Read
2870 WriteFifo(tcp_recv_fifo, buf, r);
2871 }
2872 }
2873
2874 // Separate to a list of datagrams by interpreting the data received from the TCP socket
2875 while (true)
2876 {
2877 UINT r = FifoSize(tcp_recv_fifo);
2878 if (r >= sizeof(USHORT))
2879 {
2880 void *ptr = FifoPtr(tcp_recv_fifo);
2881 USHORT packet_size = READ_USHORT(ptr);
2882 if (packet_size != 0 && packet_size <= OPENVPN_TCP_MAX_PACKET_SIZE)
2883 {
2884 UINT total_len = (UINT)packet_size + sizeof(USHORT);
2885 if (r >= total_len)
2886 {
2887 if (ReadFifo(tcp_recv_fifo, buf, total_len) != total_len)
2888 {
2889 // Mismatch
2890 disconnected = true;
2891 break;
2892 }
2893 else
2894 {
2895 // Read one packet
2896 UINT payload_len = packet_size;
2897 UCHAR *payload_ptr = buf + sizeof(USHORT);
2898
2899 // Pass the packet to the OpenVPN server
2900 Add(ovs_recv_packet, NewUdpPacket(&sock->RemoteIP, sock->RemotePort,
2901 &sock->LocalIP, sock->LocalPort,
2902 Clone(payload_ptr, payload_len), payload_len));
2903 }
2904 }
2905 else
2906 {
2907 // Non-arrival
2908 break;
2909 }
2910 }
2911 else
2912 {
2913 // Invalid packet size
2914 disconnected = true;
2915 break;
2916 }
2917 }
2918 else
2919 {
2920 // Non-arrival
2921 break;
2922 }
2923 }
2924
2925 // Pass a list of received datagrams to the OpenVPN server
2926 OvsRecvPacket(s, ovs_recv_packet, OPENVPN_PROTOCOL_TCP);
2927
2928 // Release the received packet list
2929 for (i = 0;i < LIST_NUM(ovs_recv_packet);i++)
2930 {
2931 UDPPACKET *p = LIST_DATA(ovs_recv_packet, i);
2932
2933 FreeUdpPacket(p);
2934 }
2935
2936 DeleteAll(ovs_recv_packet);
2937
2938 // Store in the queue by getting a list of the datagrams to be transmitted from the OpenVPN server
2939 for (i = 0;i < LIST_NUM(s->SendPacketList);i++)
2940 {
2941 UDPPACKET *p = LIST_DATA(s->SendPacketList, i);
2942 // Store the size to the TCP send queue first
2943 USHORT us = (USHORT)p->Size;
2944 //Debug(" *** TCP SEND %u\n", us);
2945 us = Endian16(us);
2946 WriteFifo(tcp_send_fifo, &us, sizeof(USHORT));
2947
2948 // Write the data body
2949 WriteFifo(tcp_send_fifo, p->Data, p->Size);
2950
2951 // Packet release
2952 FreeUdpPacket(p);
2953 }
2954 DeleteAll(s->SendPacketList);
2955
2956 // Send data to the TCP socket
2957 while (FifoSize(tcp_send_fifo) >= 1)
2958 {
2959 UINT r = Send(sock, FifoPtr(tcp_send_fifo), FifoSize(tcp_send_fifo), false);
2960
2961 if (r == SOCK_LATER)
2962 {
2963 // Can not write any more
2964 break;
2965 }
2966 else if (r == 0)
2967 {
2968 // Disconnected
2969 disconnected = true;
2970 break;
2971 }
2972 else
2973 {
2974 // Wrote out
2975 ReadFifo(tcp_send_fifo, NULL, r);
2976 }
2977 }
2978
2979 if (FifoSize(tcp_send_fifo) > MAX_BUFFERING_PACKET_SIZE)
2980 {
2981 s->SupressSendPacket = true;
2982 }
2983 else
2984 {
2985 s->SupressSendPacket = false;
2986 }
2987
2988 if (s->DisconnectCount >= 1)
2989 {
2990 // Session disconnection has occurred on OpenVPN server-side
2991 disconnected = true;
2992 }
2993
2994 if (giveup_time <= now)
2995 {
2996 UINT i;
2997 UINT num_established_sessions = 0;
2998 for (i = 0;i < LIST_NUM(s->SessionList);i++)
2999 {
3000 OPENVPN_SESSION *se = LIST_DATA(s->SessionList, i);
3001
3002 if (se->Established)
3003 {
3004 num_established_sessions++;
3005 }
3006 }
3007
3008 if (num_established_sessions == 0)
3009 {
3010 // If the number of sessions is 0 even if wait a certain period of time after the start of server, abort
3011 disconnected = true;
3012 }
3013 }
3014
3015 if (disconnected)
3016 {
3017 // Error or disconnect occurs
3018 Debug("Breaking OpenVPN TCP Server Main Loop.\n");
3019 break;
3020 }
3021
3022 // Wait until the next event occurs
3023 next_interval = GetNextIntervalForInterrupt(im);
3024 next_interval = MIN(next_interval, UDPLISTENER_WAIT_INTERVAL);
3025 WaitSockEvent(se, next_interval);
3026 }
3027
3028 if (s != NULL && s->SessionEstablishedCount != 0)
3029 {
3030 ret = true;
3031 }
3032
3033 // Release the OpenVPN server
3034 FreeOpenVpnServer(s);
3035
3036 // Release object
3037 FreeInterruptManager(im);
3038 ReleaseSockEvent(se);
3039 ReleaseFifo(tcp_recv_fifo);
3040 ReleaseFifo(tcp_send_fifo);
3041 Free(buf);
3042
3043 // Release the received packet list
3044 for (i = 0;i < LIST_NUM(ovs_recv_packet);i++)
3045 {
3046 UDPPACKET *p = LIST_DATA(ovs_recv_packet, i);
3047
3048 FreeUdpPacket(p);
3049 }
3050
3051 ReleaseList(ovs_recv_packet);
3052
3053 return ret;
3054 }
3055
3056
3057
3058