1 // SoftEther VPN Source Code - Developer Edition Master Branch
2 // Cedar Communication Module
3 // © 2020 Nokia
4 
5 // Protocol.c
6 // SoftEther protocol related routines
7 
8 #include "Protocol.h"
9 
10 #include "Admin.h"
11 #include "Client.h"
12 #include "CM.h"
13 #include "DDNS.h"
14 #include "Hub.h"
15 #include "IPC.h"
16 #include "Link.h"
17 #include "Logging.h"
18 #include "Proto_IPsec.h"
19 #include "Proto_OpenVPN.h"
20 #include "Proto_PPP.h"
21 #include "Proto_SSTP.h"
22 #include "Radius.h"
23 #include "Sam.h"
24 #include "Server.h"
25 #include "UdpAccel.h"
26 #include "VLanUnix.h"
27 #include "WaterMark.h"
28 #include "WebUI.h"
29 #include "WinUi.h"
30 #include "Wpc.h"
31 
32 #include "Mayaqua/Cfg.h"
33 #include "Mayaqua/DNS.h"
34 #include "Mayaqua/FileIO.h"
35 #include "Mayaqua/Internat.h"
36 #include "Mayaqua/Memory.h"
37 #include "Mayaqua/Microsoft.h"
38 #include "Mayaqua/Object.h"
39 #include "Mayaqua/OS.h"
40 #include "Mayaqua/Pack.h"
41 #include "Mayaqua/Secure.h"
42 #include "Mayaqua/Str.h"
43 #include "Mayaqua/Table.h"
44 #include "Mayaqua/Tick64.h"
45 
46 // Download and save intermediate certificates if necessary
DownloadAndSaveIntermediateCertificatesIfNecessary(X * x)47 bool DownloadAndSaveIntermediateCertificatesIfNecessary(X *x)
48 {
49 	LIST *o;
50 	bool ret = false;
51 	// Validate arguments
52 	if (x == NULL)
53 	{
54 		return false;
55 	}
56 
57 	if (x->root_cert)
58 	{
59 		return true;
60 	}
61 
62 	o = NewCertList(true);
63 
64 	ret = TryGetRootCertChain(o, x, true, NULL);
65 
66 	FreeCertList(o);
67 
68 	return ret;
69 }
70 
71 // Attempt to fetch the full chain of the specified cert
TryGetRootCertChain(LIST * o,X * x,bool auto_save,X ** found_root_x)72 bool TryGetRootCertChain(LIST *o, X *x, bool auto_save, X **found_root_x)
73 {
74 	bool ret = false;
75 	LIST *chain = NULL;
76 	LIST *current_chain_dir = NULL;
77 	// Validate arguments
78 	if (o == NULL || x == NULL)
79 	{
80 		return false;
81 	}
82 
83 	chain = NewCertList(false);
84 
85 	ret = TryGetParentCertFromCertList(o, x, chain);
86 
87 	if (ret)
88 	{
89 		UINT i;
90 		DIRLIST *dir;
91 		wchar_t dirname[MAX_SIZE];
92 		wchar_t exedir[MAX_SIZE];
93 
94 		GetDbDirW(exedir, sizeof(exedir));
95 		CombinePathW(dirname, sizeof(dirname), exedir, L"chain_certs");
96 		MakeDirExW(dirname);
97 
98 		if (auto_save)
99 		{
100 			// delete the current auto_save files
101 			dir = EnumDirW(dirname);
102 			if (dir != NULL)
103 			{
104 				for (i = 0;i < dir->NumFiles;i++)
105 				{
106 					DIRENT *e = dir->File[i];
107 
108 					if (e->Folder == false)
109 					{
110 						if (UniStartWith(e->FileNameW, AUTO_DOWNLOAD_CERTS_PREFIX))
111 						{
112 							wchar_t tmp[MAX_SIZE];
113 
114 							CombinePathW(tmp, sizeof(tmp), dirname, e->FileNameW);
115 
116 							FileDeleteW(tmp);
117 						}
118 					}
119 				}
120 
121 				FreeDir(dir);
122 			}
123 		}
124 
125 		current_chain_dir = NewCertList(false);
126 		AddAllChainCertsToCertList(current_chain_dir);
127 
128 		for (i = 0;i < LIST_NUM(chain);i++)
129 		{
130 			wchar_t tmp[MAX_SIZE];
131 			X *xx = LIST_DATA(chain, i);
132 
133 			GetAllNameFromName(tmp, sizeof(tmp), xx->subject_name);
134 
135 			Debug("depth = %u, subject = %S\n", i, tmp);
136 
137 			if (auto_save && CompareX(x, xx) == false && IsXInCertList(current_chain_dir, xx) == false)
138 			{
139 				wchar_t fn[MAX_PATH];
140 				char hex_a[128];
141 				wchar_t hex[128];
142 				UCHAR hash[SHA1_SIZE];
143 				wchar_t tmp[MAX_SIZE];
144 				BUF *b;
145 
146 				GetXDigest(xx, hash, true);
147 				BinToStr(hex_a, sizeof(hex_a), hash, SHA1_SIZE);
148 				StrToUni(hex, sizeof(hex), hex_a);
149 
150 				UniStrCpy(fn, sizeof(fn), AUTO_DOWNLOAD_CERTS_PREFIX);
151 				UniStrCat(fn, sizeof(fn), hex);
152 				UniStrCat(fn, sizeof(fn), L".cer");
153 
154 				CombinePathW(tmp, sizeof(tmp), dirname, fn);
155 
156 				b = XToBuf(xx, true);
157 
158 				DumpBufW(b, tmp);
159 
160 				FreeBuf(b);
161 			}
162 
163 			if (xx->root_cert)
164 			{
165 				if (found_root_x != NULL)
166 				{
167 					*found_root_x = CloneX(xx);
168 				}
169 			}
170 		}
171 	}
172 
173 	FreeCertList(chain);
174 
175 	FreeCertList(current_chain_dir);
176 
177 	return ret;
178 }
179 
180 // Try get the parent cert
TryGetParentCertFromCertList(LIST * o,X * x,LIST * found_chain)181 bool TryGetParentCertFromCertList(LIST *o, X *x, LIST *found_chain)
182 {
183 	bool ret = false;
184 	X *r;
185 	bool do_free = false;
186 	// Validate arguments
187 	if (o == NULL || x == NULL || found_chain == NULL)
188 	{
189 		return false;
190 	}
191 
192 	if (LIST_NUM(found_chain) >= FIND_CERT_CHAIN_MAX_DEPTH)
193 	{
194 		return false;
195 	}
196 
197 	Add(found_chain, CloneX(x));
198 
199 	if (x->root_cert)
200 	{
201 		return true;
202 	}
203 
204 	r = FindCertIssuerFromCertList(o, x);
205 
206 	if (r == NULL)
207 	{
208 		if (IsEmptyStr(x->issuer_url) == false)
209 		{
210 			r = DownloadCert(x->issuer_url);
211 
212 			if (CheckXEx(x, r, true, true) && CompareX(x, r) == false)
213 			{
214 				// found
215 				do_free = true;
216 			}
217 			else
218 			{
219 				// invalid
220 				FreeX(r);
221 				r = NULL;
222 			}
223 		}
224 	}
225 
226 	if (r != NULL)
227 	{
228 		ret = TryGetParentCertFromCertList(o, r, found_chain);
229 	}
230 
231 	if (do_free)
232 	{
233 		FreeX(r);
234 	}
235 
236 	return ret;
237 }
238 
239 // Find the issuer of the cert from the cert list
FindCertIssuerFromCertList(LIST * o,X * x)240 X *FindCertIssuerFromCertList(LIST *o, X *x)
241 {
242 	UINT i;
243 	// Validate arguments
244 	if (o == NULL || x == NULL)
245 	{
246 		return NULL;
247 	}
248 
249 	if (x->root_cert)
250 	{
251 		return NULL;
252 	}
253 
254 	for (i = 0;i < LIST_NUM(o);i++)
255 	{
256 		X *xx = LIST_DATA(o, i);
257 
258 		if (CheckXEx(x, xx, true, true))
259 		{
260 			if (CompareX(x, xx) == false)
261 			{
262 				return xx;
263 			}
264 		}
265 	}
266 
267 	return NULL;
268 }
269 
270 // Download a cert by using HTTP
DownloadCert(char * url)271 X *DownloadCert(char *url)
272 {
273 	BUF *b;
274 	URL_DATA url_data;
275 	X *ret = NULL;
276 	// Validate arguments
277 	if (IsEmptyStr(url))
278 	{
279 		return NULL;
280 	}
281 
282 	Debug("Trying to download a cert from %s ...\n", url);
283 
284 	if (ParseUrl(&url_data, url, false, NULL) == false)
285 	{
286 		Debug("Download failed.\n");
287 		return NULL;
288 	}
289 
290 	b = HttpRequestEx(&url_data, NULL, CERT_HTTP_DOWNLOAD_TIMEOUT, CERT_HTTP_DOWNLOAD_TIMEOUT,
291 		NULL, false, NULL, NULL, NULL, NULL, NULL, CERT_HTTP_DOWNLOAD_MAXSIZE);
292 
293 	if (b == NULL)
294 	{
295 		Debug("Download failed.\n");
296 		return NULL;
297 	}
298 
299 	ret = BufToX(b, IsBase64(b));
300 
301 	FreeBuf(b);
302 
303 	Debug("Download ok.\n");
304 	return ret;
305 }
306 
307 // New cert list
NewCertList(bool load_root_and_chain)308 LIST *NewCertList(bool load_root_and_chain)
309 {
310 	LIST *o;
311 
312 	o = NewList(NULL);
313 
314 	if (load_root_and_chain)
315 	{
316 		AddAllRootCertsToCertList(o);
317 		AddAllChainCertsToCertList(o);
318 	}
319 
320 	return o;
321 }
322 
323 // Free cert list
FreeCertList(LIST * o)324 void FreeCertList(LIST *o)
325 {
326 	UINT i;
327 	// Validate arguments
328 	if (o == NULL)
329 	{
330 		return;
331 	}
332 
333 	for (i = 0;i < LIST_NUM(o);i++)
334 	{
335 		X *x = LIST_DATA(o, i);
336 
337 		FreeX(x);
338 	}
339 
340 	ReleaseList(o);
341 }
342 
343 // Check whether the cert is in the cert list
IsXInCertList(LIST * o,X * x)344 bool IsXInCertList(LIST *o, X *x)
345 {
346 	UINT i;
347 	// Validate arguments
348 	if (o == NULL || x == NULL)
349 	{
350 		return false;
351 	}
352 
353 	for (i = 0;i < LIST_NUM(o);i++)
354 	{
355 		X *xx = LIST_DATA(o, i);
356 
357 		if (CompareX(x, xx))
358 		{
359 			return true;
360 		}
361 	}
362 
363 	return false;
364 }
365 
366 // Add a cert to the cert list
AddXToCertList(LIST * o,X * x)367 void AddXToCertList(LIST *o, X *x)
368 {
369 	// Validate arguments
370 	if (o == NULL || x == NULL)
371 	{
372 		return;
373 	}
374 
375 	if (IsXInCertList(o, x))
376 	{
377 		return;
378 	}
379 
380 	if (CheckXDateNow(x) == false)
381 	{
382 		return;
383 	}
384 
385 	Add(o, CloneX(x));
386 }
387 
388 // Add all chain certs to the cert list
AddAllChainCertsToCertList(LIST * o)389 void AddAllChainCertsToCertList(LIST *o)
390 {
391 	wchar_t dirname[MAX_SIZE];
392 	wchar_t exedir[MAX_SIZE];
393 	DIRLIST *dir;
394 	// Validate arguments
395 	if (o == NULL)
396 	{
397 		return;
398 	}
399 
400 	GetDbDirW(exedir, sizeof(exedir));
401 
402 	CombinePathW(dirname, sizeof(dirname), exedir, L"chain_certs");
403 
404 	MakeDirExW(dirname);
405 
406 	dir = EnumDirW(dirname);
407 
408 	if (dir != NULL)
409 	{
410 		UINT i;
411 
412 		for (i = 0;i < dir->NumFiles;i++)
413 		{
414 			DIRENT *e = dir->File[i];
415 
416 			if (e->Folder == false)
417 			{
418 				wchar_t tmp[MAX_SIZE];
419 				X *x;
420 
421 				CombinePathW(tmp, sizeof(tmp), dirname, e->FileNameW);
422 
423 				x = FileToXW(tmp);
424 
425 				if (x != NULL)
426 				{
427 					AddXToCertList(o, x);
428 
429 					FreeX(x);
430 				}
431 			}
432 		}
433 
434 		FreeDir(dir);
435 	}
436 }
437 
438 // Add all root certs to the cert list
AddAllRootCertsToCertList(LIST * o)439 void AddAllRootCertsToCertList(LIST *o)
440 {
441 	BUF *buf;
442 	PACK *p;
443 	UINT num_ok = 0, num_error = 0;
444 	// Validate arguments
445 	if (o == NULL)
446 	{
447 		return;
448 	}
449 
450 	buf = ReadDump(ROOT_CERTS_FILENAME);
451 	if (buf == NULL)
452 	{
453 		return;
454 	}
455 
456 	p = BufToPack(buf);
457 
458 	if (p != NULL)
459 	{
460 		UINT num = PackGetIndexCount(p, "cert");
461 		UINT i;
462 
463 		for (i = 0;i < num;i++)
464 		{
465 			bool ok = false;
466 			BUF *b = PackGetBufEx(p, "cert", i);
467 
468 			if (b != NULL)
469 			{
470 				X *x = BufToX(b, false);
471 
472 				if (x != NULL)
473 				{
474 					AddXToCertList(o, x);
475 
476 					ok = true;
477 
478 					FreeX(x);
479 				}
480 
481 				FreeBuf(b);
482 			}
483 
484 			if (ok)
485 			{
486 				num_ok++;
487 			}
488 			else
489 			{
490 				num_error++;
491 			}
492 		}
493 
494 		FreePack(p);
495 	}
496 
497 	FreeBuf(buf);
498 
499 	Debug("AddAllRootCertsToCertList: ok=%u error=%u total_list_len=%u\n", num_ok, num_error, LIST_NUM(o));
500 }
501 
502 // Convert the date of YYYYMMDD format to a number
ShortStrToDate64(char * str)503 UINT64 ShortStrToDate64(char *str)
504 {
505 	UINT v;
506 	SYSTEMTIME st;
507 	// Validate arguments
508 	if (str == NULL)
509 	{
510 		return 0;
511 	}
512 
513 	v = ToInt(str);
514 
515 	Zero(&st, sizeof(st));
516 
517 	st.wYear = (v % 100000000) / 10000;
518 	st.wMonth = (v % 10000) / 100;
519 	st.wDay = v % 100;
520 
521 	return SystemToUINT64(&st);
522 }
523 
524 // Handle the response that is returned from the server in the update client
UpdateClientThreadProcessResults(UPDATE_CLIENT * c,BUF * b)525 void UpdateClientThreadProcessResults(UPDATE_CLIENT *c, BUF *b)
526 {
527 	bool exit = false;
528 	// Validate arguments
529 	if (c == NULL || b == NULL)
530 	{
531 		return;
532 	}
533 
534 	SeekBufToBegin(b);
535 
536 	while (true)
537 	{
538 		char *line = CfgReadNextLine(b);
539 		if (line == NULL)
540 		{
541 			break;
542 		}
543 
544 		Trim(line);
545 
546 		if (StartWith(line, "#") == false && IsEmptyStr(line) == false)
547 		{
548 			TOKEN_LIST *t = ParseTokenWithNullStr(line, " \t");
549 
550 			if (t != NULL)
551 			{
552 				if (t->NumTokens >= 5)
553 				{
554 					if (StrCmpi(t->Token[0], c->FamilyName) == 0)
555 					{
556 						// Match
557 						UINT64 date = ShortStrToDate64(t->Token[1]);
558 						if (date != 0)
559 						{
560 							UINT build = ToInt(t->Token[2]);
561 							if (build != 0)
562 							{
563 								if (build > c->MyBuild && build > c->LatestBuild && build > c->Setting.LatestIgnoreBuild)
564 								{
565 									c->Callback(c, build, date, t->Token[3], t->Token[4], &c->HaltFlag, c->Param);
566 
567 									c->LatestBuild = build;
568 
569 									exit = true;
570 								}
571 							}
572 						}
573 					}
574 				}
575 
576 				FreeToken(t);
577 			}
578 		}
579 
580 		Free(line);
581 
582 		if (exit)
583 		{
584 			break;
585 		}
586 	}
587 }
588 
589 // Update client main process
UpdateClientThreadMain(UPDATE_CLIENT * c)590 void UpdateClientThreadMain(UPDATE_CLIENT *c)
591 {
592 	char url[MAX_SIZE];
593 	char id[MAX_SIZE];
594 	URL_DATA data;
595 	BUF *cert_hash;
596 	UINT ret = 0;
597 	BUF *recv;
598 	// Validate arguments
599 	if (c == NULL)
600 	{
601 		return;
602 	}
603 
604 	// Generate the URL
605 	Format(url, sizeof(url), IsUseAlternativeHostname() ? UPDATE_SERVER_URL_CHINA : UPDATE_SERVER_URL_GLOBAL, c->FamilyName, c->SoftwareName, c->MyBuild, c->MyLanguage);
606 
607 	if (IsEmptyStr(c->ClientId) == false)
608 	{
609 		Format(id, sizeof(id), "&id=%s", c->ClientId);
610 		StrCat(url, sizeof(url), id);
611 	}
612 
613 	// Get a text file at this URL
614 	if (ParseUrl(&data, url, false, NULL) == false)
615 	{
616 		return;
617 	}
618 
619 	cert_hash = StrToBin(UPDATE_SERVER_CERT_HASH);
620 
621 	StrCpy(data.SniString, sizeof(data.SniString), DDNS_SNI_VER_STRING);
622 
623 	recv = HttpRequestEx3(&data, NULL, UPDATE_CONNECT_TIMEOUT, UPDATE_COMM_TIMEOUT, &ret, false, NULL, NULL,
624 		NULL, ((cert_hash != NULL && (cert_hash->Size % SHA1_SIZE) == 0) ? cert_hash->Buf : NULL),
625 		(cert_hash != NULL ? (cert_hash->Size / SHA1_SIZE) : 0),
626 		(bool *)&c->HaltFlag, 0, NULL, NULL);
627 
628 	FreeBuf(cert_hash);
629 
630 	if (recv != NULL)
631 	{
632 		UpdateClientThreadProcessResults(c, recv);
633 
634 		FreeBuf(recv);
635 	}
636 }
637 
638 // Update client main thread
UpdateClientThreadProc(THREAD * thread,void * param)639 void UpdateClientThreadProc(THREAD *thread, void *param)
640 {
641 	UPDATE_CLIENT *c = (UPDATE_CLIENT *)param;
642 	bool first_loop = true;
643 	// Validate arguments
644 	if (thread == NULL || param == NULL)
645 	{
646 		return;
647 	}
648 
649 	while (true)
650 	{
651 		// Termination check
652 		if (c->HaltFlag)
653 		{
654 			break;
655 		}
656 
657 		if (first_loop == false)
658 		{
659 			// Wait for the foreground
660 			if (c->IsForegroundCb != NULL)
661 			{
662 				while (true)
663 				{
664 					if (c->HaltFlag)
665 					{
666 						break;
667 					}
668 
669 					if (c->IsForegroundCb(c, c->Param))
670 					{
671 						break;
672 					}
673 
674 					Wait(c->HaltEvent, 1000);
675 				}
676 			}
677 		}
678 
679 		first_loop = false;
680 
681 		if (c->HaltFlag)
682 		{
683 			break;
684 		}
685 
686 		if (c->Setting.DisableCheck == false)
687 		{
688 			UpdateClientThreadMain(c);
689 		}
690 
691 		// Wait until the next attempt
692 		Wait(c->HaltEvent, GenRandInterval(UPDATE_CHECK_INTERVAL_MIN, UPDATE_CHECK_INTERVAL_MAX));
693 	}
694 }
695 
696 // Update the configuration of the update client
SetUpdateClientSetting(UPDATE_CLIENT * c,UPDATE_CLIENT_SETTING * s)697 void SetUpdateClientSetting(UPDATE_CLIENT *c, UPDATE_CLIENT_SETTING *s)
698 {
699 	// Validate arguments
700 	if (c == NULL || s == NULL)
701 	{
702 		return;
703 	}
704 
705 	Copy(&c->Setting, s, sizeof(UPDATE_CLIENT_SETTING));
706 
707 	Set(c->HaltEvent);
708 }
709 
710 // Start the update client
NewUpdateClient(UPDATE_NOTIFY_PROC * cb,UPDATE_ISFOREGROUND_PROC * isforeground_cb,void * param,char * family_name,char * software_name,wchar_t * software_title,UINT my_build,UINT64 my_date,char * my_lang,UPDATE_CLIENT_SETTING * current_setting,char * client_id)711 UPDATE_CLIENT *NewUpdateClient(UPDATE_NOTIFY_PROC *cb, UPDATE_ISFOREGROUND_PROC *isforeground_cb, void *param, char *family_name, char *software_name, wchar_t *software_title, UINT my_build, UINT64 my_date, char *my_lang, UPDATE_CLIENT_SETTING *current_setting, char *client_id)
712 {
713 	UPDATE_CLIENT *c;
714 	// Validate arguments
715 	if (family_name == NULL || software_title == NULL || software_name == NULL || my_build == 0 ||
716 		my_lang == NULL || current_setting == NULL || cb == NULL)
717 	{
718 		return NULL;
719 	}
720 
721 	c = ZeroMalloc(sizeof(UPDATE_CLIENT));
722 
723 	c->Callback = cb;
724 	c->IsForegroundCb = isforeground_cb;
725 
726 	StrCpy(c->ClientId, sizeof(c->ClientId), client_id);
727 	StrCpy(c->FamilyName, sizeof(c->FamilyName), family_name);
728 	StrCpy(c->SoftwareName, sizeof(c->SoftwareName), software_name);
729 	UniStrCpy(c->SoftwareTitle, sizeof(c->SoftwareTitle), software_title);
730 	c->MyBuild = my_build;
731 	c->MyDate = my_date;
732 	StrCpy(c->MyLanguage, sizeof(c->MyLanguage), my_lang);
733 
734 	Copy(&c->Setting, current_setting, sizeof(c->Setting));
735 
736 	c->Param = param;
737 
738 	c->HaltEvent = NewEvent();
739 
740 	// Create a thread
741 	c->Thread = NewThread(UpdateClientThreadProc, c);
742 
743 	return c;
744 }
745 
746 // Terminate the update client
FreeUpdateClient(UPDATE_CLIENT * c)747 void FreeUpdateClient(UPDATE_CLIENT *c)
748 {
749 	// Validate arguments
750 	if (c == NULL)
751 	{
752 		return;
753 	}
754 
755 	// Thread stop
756 	c->HaltFlag = true;
757 	Set(c->HaltEvent);
758 
759 	// Wait for thread termination
760 	WaitThread(c->Thread, INFINITE);
761 
762 	ReleaseThread(c->Thread);
763 	ReleaseEvent(c->HaltEvent);
764 
765 	Free(c);
766 }
767 
768 // Generate unique IDs for each machine
GenerateMachineUniqueHash(void * data)769 void GenerateMachineUniqueHash(void *data)
770 {
771 	BUF *b;
772 	char name[64];
773 	OS_INFO *osinfo;
774 	UINT64 iphash = 0;
775 	// Validate arguments
776 	if (data == NULL)
777 	{
778 		return;
779 	}
780 
781 	iphash = GetHostIPAddressListHash();
782 
783 	b = NewBuf();
784 	GetMachineName(name, sizeof(name));
785 
786 	osinfo = GetOsInfo();
787 
788 	WriteBuf(b, name, StrLen(name));
789 
790 	WriteBufInt64(b, iphash);
791 
792 	WriteBuf(b, &osinfo->OsType, sizeof(osinfo->OsType));
793 	WriteBuf(b, osinfo->KernelName, StrLen(osinfo->KernelName));
794 	WriteBuf(b, osinfo->KernelVersion, StrLen(osinfo->KernelVersion));
795 	WriteBuf(b, osinfo->OsProductName, StrLen(osinfo->OsProductName));
796 	WriteBuf(b, &osinfo->OsServicePack, sizeof(osinfo->OsServicePack));
797 	WriteBuf(b, osinfo->OsSystemName, StrLen(osinfo->OsSystemName));
798 	WriteBuf(b, osinfo->OsVendorName, StrLen(osinfo->OsVendorName));
799 	WriteBuf(b, osinfo->OsVersion, StrLen(osinfo->OsVersion));
800 
801 	Sha0(data, b->Buf, b->Size);
802 
803 	FreeBuf(b);
804 }
805 
806 // Convert a node information to a string
NodeInfoToStr(wchar_t * str,UINT size,NODE_INFO * info)807 void NodeInfoToStr(wchar_t *str, UINT size, NODE_INFO *info)
808 {
809 	char client_ip[128], server_ip[128], proxy_ip[128], unique_id[128];
810 	// Validate arguments
811 	if (str == NULL || info == NULL)
812 	{
813 		return;
814 	}
815 
816 	IPToStr4or6(client_ip, sizeof(client_ip), info->ClientIpAddress, info->ClientIpAddress6);
817 	IPToStr4or6(server_ip, sizeof(server_ip), info->ServerIpAddress, info->ServerIpAddress6);
818 	IPToStr4or6(proxy_ip, sizeof(proxy_ip), info->ProxyIpAddress, info->ProxyIpAddress6);
819 	BinToStr(unique_id, sizeof(unique_id), info->UniqueId, sizeof(info->UniqueId));
820 
821 	UniFormat(str, size, _UU("LS_NODE_INFO_TAG"), info->ClientProductName,
822 		Endian32(info->ClientProductVer), Endian32(info->ClientProductBuild),
823 		info->ServerProductName, Endian32(info->ServerProductVer), Endian32(info->ServerProductBuild),
824 		info->ClientOsName, info->ClientOsVer, info->ClientOsProductId,
825 		info->ClientHostname, client_ip, Endian32(info->ClientPort),
826 		info->ServerHostname, server_ip, Endian32(info->ServerPort),
827 		info->ProxyHostname, proxy_ip, Endian32(info->ProxyPort),
828 		info->HubName, unique_id);
829 }
830 
831 // Accept the password change
ChangePasswordAccept(CONNECTION * c,PACK * p)832 UINT ChangePasswordAccept(CONNECTION *c, PACK *p)
833 {
834 	CEDAR *cedar;
835 	UCHAR random[SHA1_SIZE];
836 	char hubname[MAX_HUBNAME_LEN + 1];
837 	char username[MAX_USERNAME_LEN + 1];
838 	UCHAR secure_old_password[SHA1_SIZE];
839 	UCHAR new_password[SHA1_SIZE];
840 	UCHAR new_password_ntlm[SHA1_SIZE];
841 	UCHAR check_secure_old_password[SHA1_SIZE];
842 	UINT ret = ERR_NO_ERROR;
843 	HUB *hub;
844 	// Validate arguments
845 	if (c == NULL || p == NULL)
846 	{
847 		return ERR_INTERNAL_ERROR;
848 	}
849 
850 	Copy(random, c->Random, SHA1_SIZE);
851 	if (PackGetStr(p, "hubname", hubname, sizeof(hubname)) == false ||
852 		PackGetStr(p, "username", username, sizeof(username)) == false ||
853 		PackGetData2(p, "secure_old_password", secure_old_password, sizeof(secure_old_password)) == false ||
854 		PackGetData2(p, "new_password", new_password, sizeof(new_password)) == false)
855 	{
856 		return ERR_PROTOCOL_ERROR;
857 	}
858 
859 	if (PackGetData2(p, "new_password_ntlm", new_password_ntlm, MD5_SIZE) == false)
860 	{
861 		Zero(new_password_ntlm, sizeof(new_password_ntlm));
862 	}
863 
864 	cedar = c->Cedar;
865 
866 	LockHubList(cedar);
867 	{
868 		hub = GetHub(cedar, hubname);
869 	}
870 	UnlockHubList(cedar);
871 
872 	if (hub == NULL)
873 	{
874 		ret = ERR_HUB_NOT_FOUND;
875 	}
876 	else
877 	{
878 		char tmp[MAX_SIZE];
879 
880 		if (GetHubAdminOption(hub, "deny_change_user_password") != 0)
881 		{
882 			ReleaseHub(hub);
883 			return ERR_NOT_ENOUGH_RIGHT;
884 		}
885 
886 		IPToStr(tmp, sizeof(tmp), &c->FirstSock->RemoteIP);
887 		HLog(hub, "LH_CHANGE_PASSWORD_1", c->Name, tmp);
888 
889 		AcLock(hub);
890 		{
891 			USER *u = AcGetUser(hub, username);
892 			if (u == NULL)
893 			{
894 				HLog(hub, "LH_CHANGE_PASSWORD_2", c->Name, username);
895 				ret = ERR_OLD_PASSWORD_WRONG;
896 			}
897 			else
898 			{
899 				Lock(u->lock);
900 				{
901 					if (u->AuthType	!= AUTHTYPE_PASSWORD)
902 					{
903 						// Not a password authentication
904 						HLog(hub, "LH_CHANGE_PASSWORD_3", c->Name, username);
905 						ret = ERR_USER_AUTHTYPE_NOT_PASSWORD;
906 					}
907 					else
908 					{
909 						bool fix_password = false;
910 						if (u->Policy != NULL)
911 						{
912 							fix_password = u->Policy->FixPassword;
913 						}
914 						else
915 						{
916 							if (u->Group != NULL)
917 							{
918 								if (u->Group->Policy != NULL)
919 								{
920 									fix_password = u->Group->Policy->FixPassword;
921 								}
922 							}
923 						}
924 						if (fix_password == false)
925 						{
926 							// Confirmation of the old password
927 							AUTHPASSWORD *pw = (AUTHPASSWORD *)u->AuthData;
928 
929 							SecurePassword(check_secure_old_password, pw->HashedKey, random);
930 							if (Cmp(check_secure_old_password, secure_old_password, SHA1_SIZE) != 0)
931 							{
932 								// Old password is incorrect
933 								ret = ERR_OLD_PASSWORD_WRONG;
934 								HLog(hub, "LH_CHANGE_PASSWORD_4", c->Name, username);
935 							}
936 							else
937 							{
938 								// Write a new password
939 								if (Cmp(pw->HashedKey, new_password, SHA1_SIZE) != 0 || IsZero(pw->NtLmSecureHash, MD5_SIZE))
940 								{
941 									Copy(pw->HashedKey, new_password, SHA1_SIZE);
942 									Copy(pw->NtLmSecureHash, new_password_ntlm, MD5_SIZE);
943 								}
944 								HLog(hub, "LH_CHANGE_PASSWORD_5", c->Name, username);
945 							}
946 						}
947 						else
948 						{
949 							// Password change is prohibited
950 							ret = ERR_NOT_ENOUGH_RIGHT;
951 						}
952 					}
953 				}
954 				Unlock(u->lock);
955 
956 				ReleaseUser(u);
957 			}
958 		}
959 		AcUnlock(hub);
960 		ReleaseHub(hub);
961 	}
962 
963 	return ret;
964 }
965 
966 // Change the password
ChangePassword(CEDAR * cedar,CLIENT_OPTION * o,char * hubname,char * username,char * old_pass,char * new_pass)967 UINT ChangePassword(CEDAR *cedar, CLIENT_OPTION *o, char *hubname, char *username, char *old_pass, char *new_pass)
968 {
969 	UINT ret = ERR_NO_ERROR;
970 	UCHAR old_password[SHA1_SIZE];
971 	UCHAR secure_old_password[SHA1_SIZE];
972 	UCHAR new_password[SHA1_SIZE];
973 	UCHAR new_password_ntlm[MD5_SIZE];
974 	SOCK *sock;
975 	SESSION *s;
976 	// Validate arguments
977 	if (cedar == NULL || o == NULL || hubname == NULL || username == NULL || old_pass == NULL || new_pass == NULL)
978 	{
979 		return ERR_INTERNAL_ERROR;
980 	}
981 
982 
983 	// Create a session
984 	s = NewRpcSessionEx(cedar, o, &ret, NULL);
985 
986 	if (s != NULL)
987 	{
988 		PACK *p = NewPack();
989 
990 		sock = s->Connection->FirstSock;
991 
992 		HashPassword(old_password, username, old_pass);
993 		SecurePassword(secure_old_password, old_password, s->Connection->Random);
994 		HashPassword(new_password, username, new_pass);
995 		GenerateNtPasswordHash(new_password_ntlm, new_pass);
996 
997 		PackAddClientVersion(p, s->Connection);
998 
999 		PackAddStr(p, "method", "password");
1000 		PackAddStr(p, "hubname", hubname);
1001 		PackAddStr(p, "username", username);
1002 		PackAddData(p, "secure_old_password", secure_old_password, SHA1_SIZE);
1003 		PackAddData(p, "new_password", new_password, SHA1_SIZE);
1004 		PackAddData(p, "new_password_ntlm", new_password_ntlm, MD5_SIZE);
1005 
1006 		if (HttpClientSend(sock, p))
1007 		{
1008 			PACK *p = HttpClientRecv(sock);
1009 			if (p == NULL)
1010 			{
1011 				ret = ERR_DISCONNECTED;
1012 			}
1013 			else
1014 			{
1015 				ret = GetErrorFromPack(p);
1016 			}
1017 			FreePack(p);
1018 		}
1019 		else
1020 		{
1021 			ret = ERR_DISCONNECTED;
1022 		}
1023 		FreePack(p);
1024 
1025 		ReleaseSession(s);
1026 	}
1027 
1028 	return ret;
1029 }
1030 
1031 // Enumerate HUBs
EnumHub(SESSION * s)1032 TOKEN_LIST *EnumHub(SESSION *s)
1033 {
1034 	SOCK *sock;
1035 	TOKEN_LIST *ret;
1036 	PACK *p;
1037 	UINT num;
1038 	UINT i;
1039 	// Validate arguments
1040 	if (s == NULL || s->Connection == NULL)
1041 	{
1042 		return NULL;
1043 	}
1044 
1045 	sock = s->Connection->FirstSock;
1046 	if (sock == NULL)
1047 	{
1048 		return NULL;
1049 	}
1050 
1051 	// Set the Timeout
1052 	SetTimeout(sock, 10000);
1053 
1054 	p = NewPack();
1055 	PackAddStr(p, "method", "enum_hub");
1056 
1057 	PackAddClientVersion(p, s->Connection);
1058 
1059 	if (HttpClientSend(sock, p) == false)
1060 	{
1061 		FreePack(p);
1062 		return NULL;
1063 	}
1064 	FreePack(p);
1065 
1066 	p = HttpClientRecv(sock);
1067 	if (p == NULL)
1068 	{
1069 		return NULL;
1070 	}
1071 
1072 	num = PackGetInt(p, "NumHub");
1073 	ret = ZeroMalloc(sizeof(TOKEN_LIST));
1074 	ret->NumTokens = num;
1075 	ret->Token = ZeroMalloc(sizeof(char *) * num);
1076 	for (i = 0;i < num;i++)
1077 	{
1078 		char tmp[MAX_SIZE];
1079 		if (PackGetStrEx(p, "HubName", tmp, sizeof(tmp), i))
1080 		{
1081 			ret->Token[i] = CopyStr(tmp);
1082 		}
1083 	}
1084 	FreePack(p);
1085 
1086 	return ret;
1087 }
1088 
1089 // Server accepts a connection from client
ServerAccept(CONNECTION * c)1090 bool ServerAccept(CONNECTION *c)
1091 {
1092 	bool ret = false;
1093 	UINT err;
1094 	PACK *p;
1095 	char username_real[MAX_SIZE];
1096 	char method[MAX_SIZE];
1097 	char hubname[MAX_SIZE];
1098 	char username[MAX_SIZE];
1099 	char groupname[MAX_SIZE];
1100 	UCHAR session_key[SHA1_SIZE];
1101 	UCHAR ticket[SHA1_SIZE];
1102 	UINT authtype;
1103 	POLICY *policy;
1104 	UINT assigned_vlan_id = 0;
1105 	UCHAR assigned_ipc_mac_address[6];
1106 	HUB *hub;
1107 	SESSION *s = NULL;
1108 	UINT64 user_expires = 0;
1109 	bool use_encrypt;
1110 	bool use_compress;
1111 	bool half_connection;
1112 	UINT adjust_mss;
1113 	bool use_udp_acceleration_client;
1114 	UINT client_udp_acceleration_max_version = 1;
1115 	UINT udp_acceleration_version = 1;
1116 	UINT client_rudp_bulk_max_version = 1;
1117 	UINT rudp_bulk_version = 1;
1118 	bool support_hmac_on_udp_acceleration_client = false;
1119 	bool support_udp_accel_fast_disconnect_detect;
1120 	bool use_hmac_on_udp_acceleration = false;
1121 	bool supress_return_pack_error = false;
1122 	IP udp_acceleration_client_ip;
1123 	UCHAR udp_acceleration_client_key[UDP_ACCELERATION_COMMON_KEY_SIZE_V1];
1124 	UCHAR udp_acceleration_client_key_v2[UDP_ACCELERATION_COMMON_KEY_SIZE_V2];
1125 	UINT udp_acceleration_client_port;
1126 	bool admin_mode = false;
1127 	UINT direction;
1128 	UINT max_connection;
1129 	UINT timeout;
1130 	bool no_reconnect_to_session = false;
1131 	bool farm_controller = false;
1132 	bool farm_member = false;
1133 	bool farm_mode = false;
1134 	bool require_bridge_routing_mode;
1135 	bool require_monitor_mode;
1136 	bool support_bulk_on_rudp = false;
1137 	bool support_hmac_on_bulk_of_rudp = false;
1138 	bool support_udp_recovery = false;
1139 	bool enable_bulk_on_rudp = false;
1140 	bool enable_udp_recovery = false;
1141 	bool enable_hmac_on_bulk_of_rudp = false;
1142 	bool use_client_license = false, use_bridge_license = false;
1143 	bool local_host_session = false;
1144 	char sessionname[MAX_SESSION_NAME_LEN + 1];
1145 	bool is_server_or_bridge = false;
1146 	bool qos = false;
1147 	bool cluster_dynamic_secure_nat = false;
1148 	bool no_save_password = false;
1149 	NODE_INFO node;
1150 	wchar_t *msg = NULL;
1151 	bool suppress_client_update_notification = false;
1152 	USER *loggedin_user_object = NULL;
1153 	FARM_MEMBER *f = NULL;
1154 	SERVER *server = NULL;
1155 	POLICY ticketed_policy;
1156 	UCHAR unique[SHA1_SIZE], unique2[SHA1_SIZE];
1157 	CEDAR *cedar;
1158 	RPC_WINVER winver;
1159 	UINT client_id;
1160 	bool no_more_users_in_server = false;
1161 	UCHAR mschap_v2_server_response_20[20];
1162 	UINT ms_chap_error = 0;
1163 	bool is_empty_password = false;
1164 	char *error_detail = NULL;
1165 	char *error_detail_2 = NULL;
1166 	char ctoken_hash_str[64];
1167 	EAP_CLIENT *release_me_eap_client = NULL;
1168 
1169 	// Validate arguments
1170 	if (c == NULL)
1171 	{
1172 		return false;
1173 	}
1174 
1175 	GenerateMachineUniqueHash(unique2);
1176 
1177 	Zero(ctoken_hash_str, sizeof(ctoken_hash_str));
1178 
1179 	Zero(assigned_ipc_mac_address, sizeof(assigned_ipc_mac_address));
1180 
1181 	Zero(mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20));
1182 
1183 	Zero(&udp_acceleration_client_ip, sizeof(udp_acceleration_client_ip));
1184 	udp_acceleration_client_port = 0;
1185 	Zero(udp_acceleration_client_key, sizeof(udp_acceleration_client_key));
1186 	Zero(udp_acceleration_client_key_v2, sizeof(udp_acceleration_client_key_v2));
1187 
1188 	Zero(&winver, sizeof(winver));
1189 
1190 	StrCpy(groupname, sizeof(groupname), "");
1191 	StrCpy(sessionname, sizeof(sessionname), "");
1192 
1193 	if (IsZero(c->CToken_Hash, SHA1_SIZE) == false)
1194 	{
1195 		BinToStr(ctoken_hash_str, sizeof(ctoken_hash_str), c->CToken_Hash, SHA1_SIZE);
1196 	}
1197 
1198 	cedar = c->Cedar;
1199 
1200 	// Get the license status
1201 
1202 	no_more_users_in_server = SiTooManyUserObjectsInServer(cedar->Server, true);
1203 
1204 	c->Status = CONNECTION_STATUS_NEGOTIATION;
1205 
1206 	if (c->Cedar->Server != NULL)
1207 	{
1208 		SERVER *s = c->Cedar->Server;
1209 		server = s;
1210 
1211 		if (s->ServerType == SERVER_TYPE_FARM_MEMBER)
1212 		{
1213 			farm_member = true;
1214 			farm_mode = true;
1215 		}
1216 
1217 		if (s->ServerType == SERVER_TYPE_FARM_CONTROLLER)
1218 		{
1219 			farm_controller = true;
1220 			farm_mode = true;
1221 		}
1222 	}
1223 
1224 	// Receive the signature
1225 	Debug("Downloading Signature...\n");
1226 	error_detail_2 = NULL;
1227 	if (ServerDownloadSignature(c, &error_detail_2) == false)
1228 	{
1229 		if (c->Type == CONNECTION_TYPE_ADMIN_RPC)
1230 		{
1231 			c->Err = ERR_NO_ERROR;
1232 		}
1233 
1234 		if (error_detail_2 == NULL)
1235 		{
1236 			error_detail = "ServerDownloadSignature";
1237 		}
1238 		else
1239 		{
1240 			error_detail = error_detail_2;
1241 		}
1242 
1243 		supress_return_pack_error = true;
1244 
1245 		goto CLEANUP;
1246 	}
1247 
1248 	// Send a Hello packet
1249 	Debug("Uploading Hello...\n");
1250 	if (ServerUploadHello(c) == false)
1251 	{
1252 		error_detail = "ServerUploadHello";
1253 		goto CLEANUP;
1254 	}
1255 
1256 	// Receive the authentication data
1257 	Debug("Auth...\n");
1258 
1259 	p = HttpServerRecv(c->FirstSock);
1260 	if (p == NULL)
1261 	{
1262 		// The connection disconnected
1263 		c->Err = ERR_DISCONNECTED;
1264 		error_detail = "RecvAuth1";
1265 		goto CLEANUP;
1266 	}
1267 
1268 	if (err = GetErrorFromPack(p))
1269 	{
1270 		// An error has occured
1271 		FreePack(p);
1272 		c->Err = err;
1273 		error_detail = "RecvAuth2";
1274 		goto CLEANUP;
1275 	}
1276 
1277 	// Get the method
1278 	if (GetMethodFromPack(p, method, sizeof(method)) == false)
1279 	{
1280 		// Protocol error
1281 		FreePack(p);
1282 		c->Err = ERR_PROTOCOL_ERROR;
1283 		error_detail = "GetMethodFromPack";
1284 		goto CLEANUP;
1285 	}
1286 
1287 	// Brand string for the connection limit
1288 	{
1289 		char tmp[20];
1290 		char *branded_ctos = _SS("BRANDED_C_TO_S");
1291 		PackGetStr(p, "branded_ctos", tmp, sizeof(tmp));
1292 
1293 		if(StrCmpi(method, "login") == 0 && StrLen(branded_ctos) > 0 && StrCmpi(branded_ctos, tmp) != 0)
1294 		{
1295 			FreePack(p);
1296 			c->Err = ERR_BRANDED_C_TO_S;
1297 			goto CLEANUP;
1298 		}
1299 	}
1300 
1301 	// Get the client version
1302 	PackGetStr(p, "client_str", c->ClientStr, sizeof(c->ClientStr));
1303 	c->ClientVer = PackGetInt(p, "client_ver");
1304 	c->ClientBuild = PackGetInt(p, "client_build");
1305 
1306 	if (SearchStrEx(c->ClientStr, "server", 0, false) != INFINITE ||
1307 		SearchStrEx(c->ClientStr, "bridge", 0, false) != INFINITE)
1308 	{
1309 		is_server_or_bridge = true;
1310 	}
1311 
1312 	// Get the client Windows version
1313 	InRpcWinVer(&winver, p);
1314 
1315 	DecrementNoSsl(c->Cedar, &c->FirstSock->RemoteIP, 2);
1316 
1317 	if (StrCmpi(method, "login") == 0)
1318 	{
1319 		bool auth_ret = false;
1320 
1321 		Debug("Login...\n");
1322 		c->Status = CONNECTION_STATUS_USERAUTH;
1323 
1324 		c->Type = CONNECTION_TYPE_LOGIN;
1325 
1326 		if (no_more_users_in_server)
1327 		{
1328 			// There are many users than are allowed in the VPN Server
1329 			FreePack(p);
1330 			c->Err = ERR_TOO_MANY_USER;
1331 			error_detail = "ERR_TOO_MANY_USER";
1332 			goto CLEANUP;
1333 		}
1334 
1335 		// Such as the client name
1336 		if (PackGetStr(p, "hello", c->ClientStr, sizeof(c->ClientStr)) == false)
1337 		{
1338 			StrCpy(c->ClientStr, sizeof(c->ClientStr), "Unknown");
1339 		}
1340 		c->ServerVer = GetCedarVersionNumber();
1341 		c->ServerBuild = CEDAR_VERSION_BUILD;
1342 
1343 		// Get the NODE_INFO
1344 		Zero(&node, sizeof(node));
1345 		InRpcNodeInfo(&node, p);
1346 
1347 		// Protocol
1348 		c->Protocol = GetProtocolFromPack(p);
1349 		if (c->Protocol == CONNECTION_UDP)
1350 		{
1351 			// Release the structure of the TCP connection
1352 			if (c->Tcp)
1353 			{
1354 				ReleaseList(c->Tcp->TcpSockList);
1355 				Free(c->Tcp);
1356 			}
1357 		}
1358 
1359 		if (GetServerCapsBool(c->Cedar->Server, "b_vpn_client_connect") == false)
1360 		{
1361 			// VPN client is unable to connect
1362 			FreePack(p);
1363 			c->Err = ERR_NOT_SUPPORTED;
1364 			goto CLEANUP;
1365 		}
1366 
1367 		// Get authentication method and initiate login process
1368 		authtype = GetAuthTypeFromPack(p);
1369 		if (authtype == AUTHTYPE_WIREGUARD_KEY)
1370 		{
1371 			WGK *wgk, tmp;
1372 			bool ok = false;
1373 
1374 			if (PackGetStr(p, "key", tmp.Key, sizeof(tmp.Key)) == false)
1375 			{
1376 				FreePack(p);
1377 				c->Err = ERR_PROTOCOL_ERROR;
1378 				error_detail = "GetWireGuardKeyFromPack";
1379 				goto CLEANUP;
1380 			}
1381 
1382 			LockList(c->Cedar->WgkList);
1383 			{
1384 				wgk = Search(c->Cedar->WgkList, &tmp);
1385 				if (wgk != NULL)
1386 				{
1387 					ok = true;
1388 					StrCpy(hubname, sizeof(hubname), wgk->Hub);
1389 					StrCpy(username, sizeof(username), wgk->User);
1390 					StrCpy(node.HubName, sizeof(node.HubName), hubname);
1391 				}
1392 			}
1393 			UnlockList(c->Cedar->WgkList);
1394 
1395 			if (ok == false)
1396 			{
1397 				FreePack(p);
1398 				c->Err = ERR_AUTH_FAILED;
1399 				SLog(c->Cedar, "LS_WG_KEY_NOT_FOUND", c->Name, hubname);
1400 				error_detail = "ERR_AUTH_FAILED";
1401 				goto CLEANUP;
1402 			}
1403 		}
1404 		else if (GetHubnameAndUsernameFromPack(p, username, sizeof(username), hubname, sizeof(hubname)) == false)
1405 		{
1406 			FreePack(p);
1407 			c->Err = ERR_PROTOCOL_ERROR;
1408 			error_detail = "GetHubnameAndUsernameFromPack";
1409 			goto CLEANUP;
1410 		}
1411 
1412 		if (farm_member)
1413 		{
1414 			bool ok = false;
1415 
1416 			if (StrCmpi(username, ADMINISTRATOR_USERNAME) == 0 &&
1417 				authtype == AUTHTYPE_PASSWORD)
1418 			{
1419 				ok = true;
1420 			}
1421 
1422 			if (authtype == AUTHTYPE_TICKET)
1423 			{
1424 				ok = true;
1425 			}
1426 
1427 			if (ok == false)
1428 			{
1429 				// Logging on directly to server farm members by
1430 				// non-Administrators are prohibited
1431 				FreePack(p);
1432 				SLog(c->Cedar, "LS_FARMMEMBER_NOT_ADMIN", c->Name, hubname, ADMINISTRATOR_USERNAME, username);
1433 				c->Err = ERR_ACCESS_DENIED;
1434 				goto CLEANUP;
1435 			}
1436 		}
1437 
1438 		Debug("Username = %s, HubName = %s\n", username, hubname);
1439 		LockHubList(c->Cedar);
1440 		{
1441 			hub = GetHub(c->Cedar, hubname);
1442 		}
1443 		UnlockHubList(c->Cedar);
1444 		if (hub == NULL)
1445 		{
1446 			// The HUB does not exist
1447 			FreePack(p);
1448 			c->Err = ERR_HUB_NOT_FOUND;
1449 			SLog(c->Cedar, "LS_HUB_NOT_FOUND", c->Name, hubname);
1450 			error_detail = "ERR_HUB_NOT_FOUND";
1451 			goto CLEANUP;
1452 		}
1453 
1454 		if (hub->ForceDisableComm)
1455 		{
1456 			// Communication function is disabled
1457 			FreePack(p);
1458 			c->Err = ERR_SERVER_CANT_ACCEPT;
1459 			error_detail = "ERR_COMM_DISABLED";
1460 			ReleaseHub(hub);
1461 			goto CLEANUP;
1462 		}
1463 
1464 		if (GetGlobalServerFlag(GSF_DISABLE_AC) == 0)
1465 		{
1466 			if (hub->HubDb != NULL && c->FirstSock != NULL)
1467 			{
1468 				IP ip;
1469 
1470 				Copy(&ip, &c->FirstSock->RemoteIP, sizeof(IP));
1471 
1472 				if (IsIpDeniedByAcList(&ip, hub->HubDb->AcList))
1473 				{
1474 					char ip_str[64];
1475 					// Access denied
1476 					ReleaseHub(hub);
1477 					hub = NULL;
1478 					FreePack(p);
1479 					c->Err = ERR_IP_ADDRESS_DENIED;
1480 					IPToStr(ip_str, sizeof(ip_str), &ip);
1481 					SLog(c->Cedar, "LS_IP_DENIED", c->Name, ip_str);
1482 					goto CLEANUP;
1483 				}
1484 			}
1485 		}
1486 
1487 		Lock(hub->lock);
1488 		{
1489 			UINT cert_size = 0;
1490 			void *cert_buf = NULL;
1491 			USER *user;
1492 			USERGROUP *group;
1493 			char plain_password[MAX_PASSWORD_LEN + 1];
1494 			RADIUS_LOGIN_OPTION radius_login_opt;
1495 
1496 			if (hub->Halt || hub->Offline)
1497 			{
1498 				// HUB is off-line
1499 				FreePack(p);
1500 				Unlock(hub->lock);
1501 				ReleaseHub(hub);
1502 				c->Err = ERR_HUB_STOPPING;
1503 				goto CLEANUP;
1504 			}
1505 
1506 			Zero(&radius_login_opt, sizeof(radius_login_opt));
1507 
1508 			if (hub->Option != NULL)
1509 			{
1510 				radius_login_opt.In_CheckVLanId = hub->Option->AssignVLanIdByRadiusAttribute;
1511 				radius_login_opt.In_DenyNoVlanId = hub->Option->DenyAllRadiusLoginWithNoVlanAssign;
1512 				if (hub->Option->UseHubNameAsRadiusNasId)
1513 				{
1514 					StrCpy(radius_login_opt.NasId, sizeof(radius_login_opt.NasId), hubname);
1515 				}
1516 			}
1517 
1518 			// Get the various flags
1519 			use_encrypt = PackGetInt(p, "use_encrypt") == 0 ? false : true;
1520 			use_compress = PackGetInt(p, "use_compress") == 0 ? false : true;
1521 			max_connection = PackGetInt(p, "max_connection");
1522 			half_connection = PackGetInt(p, "half_connection") == 0 ? false : true;
1523 			qos = PackGetInt(p, "qos") ? true : false;
1524 			client_id = PackGetInt(p, "client_id");
1525 			adjust_mss = PackGetInt(p, "adjust_mss");
1526 			use_udp_acceleration_client = PackGetBool(p, "use_udp_acceleration");
1527 			client_udp_acceleration_max_version = PackGetInt(p, "udp_acceleration_max_version");
1528 			if (client_udp_acceleration_max_version == 0)
1529 			{
1530 				client_udp_acceleration_max_version = 1;
1531 			}
1532 			client_rudp_bulk_max_version = PackGetInt(p, "rudp_bulk_max_version");
1533 			if (client_rudp_bulk_max_version == 0)
1534 			{
1535 				client_rudp_bulk_max_version = 1;
1536 			}
1537 			support_hmac_on_udp_acceleration_client = PackGetBool(p, "support_hmac_on_udp_acceleration");
1538 			support_udp_accel_fast_disconnect_detect = PackGetBool(p, "support_udp_accel_fast_disconnect_detect");
1539 			support_bulk_on_rudp = PackGetBool(p, "support_bulk_on_rudp");
1540 			support_hmac_on_bulk_of_rudp = PackGetBool(p, "support_hmac_on_bulk_of_rudp");
1541 			support_udp_recovery = PackGetBool(p, "support_udp_recovery");
1542 
1543 			if (c->IsInProc)
1544 			{
1545 				char tmp[MAX_SIZE];
1546 				UINT64 ptr;
1547 
1548 				ptr = PackGetInt64(p, "release_me_eap_client");
1549 				if (ptr != 0)
1550 				{
1551 					release_me_eap_client = (EAP_CLIENT *)ptr;
1552 				}
1553 
1554 				PackGetStr(p, "inproc_postfix", c->InProcPrefix, sizeof(c->InProcPrefix));
1555 				Zero(tmp, sizeof(tmp));
1556 				PackGetStr(p, "inproc_cryptname", tmp, sizeof(tmp));
1557 				c->InProcLayer = PackGetInt(p, "inproc_layer");
1558 
1559 				if (c->FirstSock != NULL)
1560 				{
1561 					if (IsEmptyStr(c->InProcPrefix) == false)
1562 					{
1563 						Format(c->FirstSock->UnderlayProtocol, sizeof(c->FirstSock->UnderlayProtocol), SOCK_UNDERLAY_INPROC_EX, c->InProcPrefix);
1564 						AddProtocolDetailsStr(c->FirstSock->UnderlayProtocol, sizeof(c->FirstSock->UnderlayProtocol), c->InProcPrefix);
1565 					}
1566 				}
1567 
1568 				if (c->CipherName != NULL)
1569 				{
1570 					Free(c->CipherName);
1571 				}
1572 
1573 				c->CipherName = NULL;
1574 
1575 				if (IsEmptyStr(tmp) == false)
1576 				{
1577 					c->CipherName = CopyStr(tmp);
1578 					use_encrypt = true;
1579 				}
1580 
1581 				use_udp_acceleration_client = false;
1582 
1583 				Format(radius_login_opt.In_VpnProtocolState, sizeof(radius_login_opt.In_VpnProtocolState),
1584 					"L%u:%s", c->InProcLayer, c->InProcPrefix);
1585 			}
1586 			else
1587 			{
1588 				if (c->CipherName != NULL)
1589 				{
1590 					Free(c->CipherName);
1591 				}
1592 				c->CipherName = NULL;
1593 
1594 				if (c->FirstSock != NULL && IsEmptyStr(c->FirstSock->CipherName) == false)
1595 				{
1596 					c->CipherName = CopyStr(c->FirstSock->CipherName);
1597 				}
1598 
1599 				Format(radius_login_opt.In_VpnProtocolState, sizeof(radius_login_opt.In_VpnProtocolState),
1600 					"L%u:%s", IPC_LAYER_2, "SEVPN");
1601 			}
1602 
1603 			if (support_bulk_on_rudp && c->FirstSock != NULL && c->FirstSock->IsRUDPSocket &&
1604 				c->FirstSock->BulkRecvKey != NULL && c->FirstSock->BulkSendKey != NULL)
1605 			{
1606 				// Allow UDP bulk transfer if the client side supports
1607 				// in the case of using R-UDP Socket
1608 				enable_bulk_on_rudp = true;
1609 
1610 				enable_hmac_on_bulk_of_rudp = support_hmac_on_bulk_of_rudp;
1611 			}
1612 
1613 			if (support_udp_recovery && c->FirstSock != NULL && c->FirstSock->IsRUDPSocket)
1614 			{
1615 				// Allow UDP recovery
1616 				enable_udp_recovery = true;
1617 			}
1618 
1619 			if (use_udp_acceleration_client)
1620 			{
1621 				PackGetData2(p, "udp_acceleration_client_key", udp_acceleration_client_key, UDP_ACCELERATION_COMMON_KEY_SIZE_V1);
1622 				PackGetData2(p, "udp_acceleration_client_key_v2", udp_acceleration_client_key_v2, UDP_ACCELERATION_COMMON_KEY_SIZE_V2);
1623 
1624 				// Get the parameters for the UDP acceleration function
1625 				if (PackGetIp(p, "udp_acceleration_client_ip", &udp_acceleration_client_ip) == false)
1626 				{
1627 					use_udp_acceleration_client = false;
1628 				}
1629 				else
1630 				{
1631 					if (IsZeroIp(&udp_acceleration_client_ip))
1632 					{
1633 						Copy(&udp_acceleration_client_ip, &c->FirstSock->RemoteIP, sizeof(IP));
1634 					}
1635 					udp_acceleration_client_port = PackGetInt(p, "udp_acceleration_client_port");
1636 					if (udp_acceleration_client_port == 0)
1637 					{
1638 						use_udp_acceleration_client = false;
1639 					}
1640 				}
1641 
1642 				use_hmac_on_udp_acceleration = support_hmac_on_udp_acceleration_client;
1643 			}
1644 
1645 			Debug("use_udp_acceleration_client = %u\n", use_udp_acceleration_client);
1646 			Debug("use_hmac_on_udp_acceleration = %u\n", use_hmac_on_udp_acceleration);
1647 
1648 			// Request mode
1649 			require_bridge_routing_mode = PackGetBool(p, "require_bridge_routing_mode");
1650 			require_monitor_mode = PackGetBool(p, "require_monitor_mode");
1651 			if (require_monitor_mode)
1652 			{
1653 				qos = false;
1654 			}
1655 
1656 			if (is_server_or_bridge)
1657 			{
1658 				require_bridge_routing_mode = true;
1659 			}
1660 
1661 			// Client unique ID
1662 			Zero(unique, sizeof(unique));
1663 			if (PackGetDataSize(p, "unique_id") == SHA1_SIZE)
1664 			{
1665 				PackGetData(p, "unique_id", unique);
1666 			}
1667 
1668 			if (1)
1669 			{
1670 				// Log
1671 				char ip1[64], ip2[64], verstr[64];
1672 				wchar_t *authtype_str = _UU("LH_AUTH_UNKNOWN");
1673 				switch (authtype)
1674 				{
1675 				case CLIENT_AUTHTYPE_ANONYMOUS:
1676 					authtype_str = _UU("LH_AUTH_ANONYMOUS");
1677 					break;
1678 				case CLIENT_AUTHTYPE_PASSWORD:
1679 					authtype_str = _UU("LH_AUTH_PASSWORD");
1680 					break;
1681 				case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
1682 					authtype_str = _UU("LH_AUTH_PLAIN_PASSWORD");
1683 					break;
1684 				case CLIENT_AUTHTYPE_CERT:
1685 					authtype_str = _UU("LH_AUTH_CERT");
1686 					break;
1687 				case AUTHTYPE_WIREGUARD_KEY:
1688 					authtype_str = _UU("LH_AUTH_WIREGUARD_KEY");
1689 					break;
1690 				case AUTHTYPE_OPENVPN_CERT:
1691 					authtype_str = _UU("LH_AUTH_OPENVPN_CERT");
1692 					break;
1693 				case AUTHTYPE_TICKET:
1694 					authtype_str = _UU("LH_AUTH_TICKET");
1695 					break;
1696 				}
1697 				IPToStr(ip1, sizeof(ip1), &c->FirstSock->RemoteIP);
1698 				IPToStr(ip2, sizeof(ip2), &c->FirstSock->LocalIP);
1699 
1700 				Format(verstr, sizeof(verstr), "%u.%02u", c->ClientVer / 100, c->ClientVer % 100);
1701 
1702 				HLog(hub, "LH_CONNECT_CLIENT", c->Name, ip1, c->FirstSock->RemoteHostname, c->FirstSock->RemotePort,
1703 					c->ClientStr, verstr, c->ClientBuild, authtype_str, username);
1704 			}
1705 
1706 			// Attempt an anonymous authentication first
1707 			auth_ret = SamAuthUserByAnonymous(hub, username);
1708 			if (auth_ret)
1709 			{
1710 				if (c->IsInProc)
1711 				{
1712 					IPC_MSCHAP_V2_AUTHINFO mschap;
1713 					char password_tmp[MAX_SIZE];
1714 
1715 					Zero(&mschap, sizeof(mschap));
1716 
1717 					Zero(password_tmp, sizeof(password_tmp));
1718 					PackGetStr(p, "plain_password", password_tmp, sizeof(password_tmp));
1719 
1720 					if (ParseAndExtractMsChapV2InfoFromPassword(&mschap, password_tmp))
1721 					{
1722 						// Because the server don't know the NTLM hashed password, the bet to the possibility of
1723 						// the same character to the user name and empty, search a password of different
1724 						// versions of the upper and lower case characters in the case of anonymous authentication.
1725 						// Returns the MS-CHAPv2 response by using the password if there is a match.
1726 						// Fail the authentication if no match is found.
1727 						// (Because, if return a false MS-CHAPv2 Response, PPP client cause an error)
1728 						LIST *o = NewListFast(NULL);
1729 						char tmp1[MAX_SIZE];
1730 						char tmp2[MAX_SIZE];
1731 						char tmp3[MAX_SIZE];
1732 						char tmp4[MAX_SIZE];
1733 						char *response_pw;
1734 						char psk[MAX_SIZE];
1735 
1736 						ParseNtUsername(mschap.MsChapV2_PPPUsername, tmp1, sizeof(tmp1), tmp2, sizeof(tmp2), false);
1737 						ParseNtUsername(mschap.MsChapV2_PPPUsername, tmp3, sizeof(tmp3), tmp4, sizeof(tmp4), true);
1738 
1739 						Add(o, "");
1740 						Add(o, "-");
1741 						Add(o, ".");
1742 						Add(o, "*");
1743 						Add(o, "?");
1744 						Add(o, " ");
1745 						Add(o, "p");
1746 						Add(o, "guest");
1747 						Add(o, "anony");
1748 						Add(o, "anonymous");
1749 						Add(o, "password");
1750 						Add(o, "passwd");
1751 						Add(o, "pass");
1752 						Add(o, "pw");
1753 						Add(o, mschap.MsChapV2_PPPUsername);
1754 						Add(o, tmp1);
1755 						Add(o, tmp2);
1756 						Add(o, tmp3);
1757 						Add(o, tmp4);
1758 
1759 						Zero(psk, sizeof(psk));
1760 
1761 						if (c->Cedar->Server != NULL)
1762 						{
1763 							SERVER *s = c->Cedar->Server;
1764 
1765 							if (s->IPsecServer != NULL)
1766 							{
1767 								StrCpy(psk, sizeof(psk), s->IPsecServer->Services.IPsec_Secret);
1768 
1769 								Add(o, psk);
1770 							}
1771 						}
1772 
1773 						response_pw = MsChapV2DoBruteForce(&mschap, o);
1774 
1775 						ReleaseList(o);
1776 
1777 						if (response_pw != NULL)
1778 						{
1779 							UCHAR challenge8[8];
1780 							UCHAR nt_hash[16];
1781 							UCHAR nt_hash_hash[16];
1782 
1783 							GenerateNtPasswordHash(nt_hash, response_pw);
1784 							GenerateNtPasswordHashHash(nt_hash_hash, nt_hash);
1785 							MsChapV2_GenerateChallenge8(challenge8, mschap.MsChapV2_ClientChallenge, mschap.MsChapV2_ServerChallenge,
1786 								mschap.MsChapV2_PPPUsername);
1787 							MsChapV2Server_GenerateResponse(mschap_v2_server_response_20, nt_hash_hash,
1788 								mschap.MsChapV2_ClientResponse, challenge8);
1789 
1790 							Free(response_pw);
1791 						}
1792 						else
1793 						{
1794 							auth_ret = false;
1795 						}
1796 					}
1797 				}
1798 
1799 				if (auth_ret)
1800 				{
1801 					is_empty_password = true;
1802 				}
1803 			}
1804 
1805 			if (auth_ret == false)
1806 			{
1807 				// Attempt other authentication methods if anonymous authentication fails
1808 				switch (authtype)
1809 				{
1810 				case CLIENT_AUTHTYPE_ANONYMOUS:
1811 					// Anonymous authentication (this have been already attempted)
1812 					break;
1813 
1814 				case AUTHTYPE_TICKET:
1815 					// Ticket authentication
1816 					if (PackGetDataSize(p, "ticket") == SHA1_SIZE)
1817 					{
1818 						PackGetData(p, "ticket", ticket);
1819 
1820 						auth_ret = SiCheckTicket(hub, ticket, username, sizeof(username), username_real, sizeof(username_real),
1821 							&ticketed_policy, sessionname, sizeof(sessionname), groupname, sizeof(groupname));
1822 					}
1823 					break;
1824 
1825 				case CLIENT_AUTHTYPE_PASSWORD:
1826 					// Password authentication
1827 					if (PackGetDataSize(p, "secure_password") == SHA1_SIZE)
1828 					{
1829 						POLICY *pol = NULL;
1830 						UCHAR secure_password[SHA1_SIZE];
1831 						Zero(secure_password, sizeof(secure_password));
1832 						if (PackGetDataSize(p, "secure_password") == SHA1_SIZE)
1833 						{
1834 							PackGetData(p, "secure_password", secure_password);
1835 						}
1836 						auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password, NULL, NULL, NULL);
1837 
1838 						pol = SamGetUserPolicy(hub, username);
1839 						if (pol != NULL)
1840 						{
1841 							no_save_password = pol->NoSavePassword;
1842 							Free(pol);
1843 						}
1844 
1845 						if(auth_ret){
1846 							// Check whether the password was empty
1847 							UCHAR hashed_empty_password[SHA1_SIZE];
1848 							UCHAR secure_empty_password[SHA1_SIZE];
1849 							HashPassword(hashed_empty_password, username, "");
1850 							SecurePassword(secure_empty_password, hashed_empty_password, c->Random);
1851 							if(Cmp(secure_password, secure_empty_password, SHA1_SIZE)==0){
1852 								is_empty_password = true;
1853 							}
1854 						}
1855 					}
1856 					break;
1857 
1858 				case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
1859 					{
1860 						POLICY *pol = NULL;
1861 
1862 						// Plaintext password authentication
1863 						Zero(plain_password, sizeof(plain_password));
1864 						PackGetStr(p, "plain_password", plain_password, sizeof(plain_password));
1865 						if (c->IsInProc == false && StartWith(plain_password, IPC_PASSWORD_MSCHAPV2_TAG))
1866 						{
1867 							// Do not allow the MS-CHAPv2 authentication other than IPC sessions
1868 							Zero(plain_password, sizeof(plain_password));
1869 						}
1870 
1871 						if (auth_ret == false)
1872 						{
1873 							// Attempt a password authentication of normal user
1874 							UCHAR secure_password[SHA1_SIZE];
1875 							UCHAR hash_password[SHA1_SIZE];
1876 							bool is_mschap = StartWith(plain_password, IPC_PASSWORD_MSCHAPV2_TAG);
1877 
1878 							HashPassword(hash_password, username, plain_password);
1879 							SecurePassword(secure_password, hash_password, c->Random);
1880 
1881 							if (is_mschap == false)
1882 							{
1883 								auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password, NULL, NULL, NULL);
1884 							}
1885 							else
1886 							{
1887 								auth_ret = SamAuthUserByPassword(hub, username, c->Random, secure_password,
1888 									plain_password, mschap_v2_server_response_20, &ms_chap_error);
1889 							}
1890 
1891 							if (auth_ret && pol == NULL)
1892 							{
1893 								pol = SamGetUserPolicy(hub, username);
1894 							}
1895 						}
1896 
1897 						if (auth_ret == false)
1898 						{
1899 							// Attempt external authentication registered users
1900 							bool fail_ext_user_auth = false;
1901 							if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
1902 							{
1903 								fail_ext_user_auth = true;
1904 							}
1905 
1906 							if (fail_ext_user_auth == false)
1907 							{
1908 								auth_ret = SamAuthUserByPlainPassword(c, hub, username, plain_password, false, mschap_v2_server_response_20, &radius_login_opt);
1909 							}
1910 
1911 							if (auth_ret && pol == NULL)
1912 							{
1913 								pol = SamGetUserPolicy(hub, username);
1914 							}
1915 						}
1916 
1917 						if (auth_ret == false)
1918 						{
1919 							// Attempt external authentication asterisk user
1920 							bool b = false;
1921 							bool fail_ext_user_auth = false;
1922 
1923 							if (GetGlobalServerFlag(GSF_DISABLE_RADIUS_AUTH) != 0)
1924 							{
1925 								fail_ext_user_auth = true;
1926 							}
1927 
1928 							if (fail_ext_user_auth == false)
1929 							{
1930 								AcLock(hub);
1931 								{
1932 									b = AcIsUser(hub, "*");
1933 								}
1934 								AcUnlock(hub);
1935 
1936 								// If there is asterisk user, log on as the user
1937 								if (b)
1938 								{
1939 									auth_ret = SamAuthUserByPlainPassword(c, hub, username, plain_password, true, mschap_v2_server_response_20, &radius_login_opt);
1940 									if (auth_ret && pol == NULL)
1941 									{
1942 										pol = SamGetUserPolicy(hub, "*");
1943 									}
1944 								}
1945 							}
1946 						}
1947 
1948 						if (pol != NULL)
1949 						{
1950 							no_save_password = pol->NoSavePassword;
1951 							Free(pol);
1952 						}
1953 
1954 						if(auth_ret){
1955 							// Check whether the password was empty
1956 							if(IsEmptyStr(plain_password)){
1957 								is_empty_password = true;
1958 							}
1959 						}
1960 					}
1961 					break;
1962 
1963 				case CLIENT_AUTHTYPE_CERT:
1964 					if (GetGlobalServerFlag(GSF_DISABLE_CERT_AUTH) == 0)
1965 					{
1966 						// Certificate authentication
1967 						cert_size = PackGetDataSize(p, "cert");
1968 						if (cert_size >= 1 && cert_size <= 100000)
1969 						{
1970 							cert_buf = ZeroMalloc(cert_size);
1971 							if (PackGetData(p, "cert", cert_buf))
1972 							{
1973 								UCHAR sign[4096 / 8];
1974 								UINT sign_size = PackGetDataSize(p, "sign");
1975 								if (sign_size <= sizeof(sign) && sign_size >= 1)
1976 								{
1977 									if (PackGetData(p, "sign", sign))
1978 									{
1979 										BUF *b = NewBuf();
1980 										X *x;
1981 										WriteBuf(b, cert_buf, cert_size);
1982 										x = BufToX(b, false);
1983 										if (x != NULL && x->is_compatible_bit &&
1984 											sign_size == (x->bits / 8))
1985 										{
1986 											K *k = GetKFromX(x);
1987 											// Verify the signature received from the client
1988 											if (RsaVerifyEx(c->Random, SHA1_SIZE, sign, k, x->bits))
1989 											{
1990 												// Confirmed that the client has had this certificate
1991 												// certainly because the signature matched.
1992 												// Check whether the certificate is valid.
1993 												auth_ret = SamAuthUserByCert(hub, username, x);
1994 												if (auth_ret)
1995 												{
1996 													// Copy the certificate
1997 													c->ClientX = CloneX(x);
1998 												}
1999 											}
2000 											else
2001 											{
2002 												// Authentication failure
2003 											}
2004 											FreeK(k);
2005 										}
2006 										FreeX(x);
2007 										FreeBuf(b);
2008 									}
2009 								}
2010 							}
2011 							Free(cert_buf);
2012 						}
2013 					}
2014 					else
2015 					{
2016 						// Certificate authentication is not supported in the open source version
2017 						HLog(hub, "LH_AUTH_CERT_NOT_SUPPORT_ON_OPEN_SOURCE", c->Name, username);
2018 						Unlock(hub->lock);
2019 						ReleaseHub(hub);
2020 						FreePack(p);
2021 						c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
2022 						goto CLEANUP;
2023 					}
2024 					break;
2025 
2026 				case AUTHTYPE_WIREGUARD_KEY:
2027 					// We already retrieved the hubname and username associated with the key.
2028 					// Now we only have to verify that the user effectively exists.
2029 					if (c->IsInProc)
2030 					{
2031 						auth_ret = SamIsUser(hub, username);
2032 					}
2033 					else
2034 					{
2035 						// WireGuard public key authentication cannot be used directly by external clients.
2036 						Unlock(hub->lock);
2037 						ReleaseHub(hub);
2038 						FreePack(p);
2039 						c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
2040 						goto CLEANUP;
2041 					}
2042 					break;
2043 
2044 				case AUTHTYPE_OPENVPN_CERT:
2045 					// For OpenVPN; mostly same as CLIENT_AUTHTYPE_CERT, but without
2046 					// signature verification, because it was already performed during TLS handshake.
2047 					if (c->IsInProc)
2048 					{
2049 						// Certificate authentication
2050 						cert_size = PackGetDataSize(p, "cert");
2051 						if (cert_size >= 1 && cert_size <= 100000)
2052 						{
2053 							cert_buf = ZeroMalloc(cert_size);
2054 							if (PackGetData(p, "cert", cert_buf))
2055 							{
2056 								BUF *b = NewBuf();
2057 								X *x;
2058 								WriteBuf(b, cert_buf, cert_size);
2059 								x = BufToX(b, false);
2060 								if (x != NULL && x->is_compatible_bit)
2061 								{
2062 									Debug("Got to SamAuthUserByCert %s\n", username); // XXX
2063 									// Check whether the certificate is valid.
2064 									auth_ret = SamAuthUserByCert(hub, username, x);
2065 									if (auth_ret)
2066 									{
2067 										// Copy the certificate
2068 										c->ClientX = CloneX(x);
2069 									}
2070 								}
2071 								FreeX(x);
2072 								FreeBuf(b);
2073 							}
2074 							Free(cert_buf);
2075 						}
2076 					}
2077 					else
2078 					{
2079 						// OpenVPN certificate authentication cannot be used directly by external clients
2080 						Unlock(hub->lock);
2081 						ReleaseHub(hub);
2082 						FreePack(p);
2083 						c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
2084 						goto CLEANUP;
2085 					}
2086 					break;
2087 
2088 				default:
2089 					// Unknown authentication method
2090 					Unlock(hub->lock);
2091 					ReleaseHub(hub);
2092 					FreePack(p);
2093 					c->Err = ERR_AUTHTYPE_NOT_SUPPORTED;
2094 					error_detail = "ERR_AUTHTYPE_NOT_SUPPORTED";
2095 					goto CLEANUP;
2096 				}
2097 			}
2098 
2099 			if (auth_ret == false)
2100 			{
2101 				char ip[64];
2102 				IPToStr(ip, sizeof(ip), &c->FirstSock->RemoteIP);
2103 				HLog(hub, "LH_AUTH_NG", c->Name, username, ip);
2104 
2105 				Unlock(hub->lock);
2106 				ReleaseHub(hub);
2107 				FreePack(p);
2108 				c->Err = ERR_AUTH_FAILED;
2109 				if (ms_chap_error != 0)
2110 				{
2111 					c->Err = ms_chap_error;
2112 				}
2113 				error_detail = "ERR_AUTH_FAILED";
2114 				goto CLEANUP;
2115 			}
2116 			else
2117 			{
2118 				if (is_empty_password)
2119 				{
2120 					const SOCK *s = c->FirstSock;
2121 					if (s != NULL && IsLocalHostIP(&s->RemoteIP) == false)
2122 					{
2123 						if (StrCmpi(username, ADMINISTRATOR_USERNAME) == 0 || GetHubAdminOption(hub, "deny_empty_password") != 0)
2124 						{
2125 							// When the password is empty, remote connection is not acceptable
2126 							HLog(hub, "LH_LOCAL_ONLY", c->Name, username);
2127 
2128 							Unlock(hub->lock);
2129 							ReleaseHub(hub);
2130 							FreePack(p);
2131 							c->Err = ERR_NULL_PASSWORD_LOCAL_ONLY;
2132 							error_detail = "ERR_NULL_PASSWORD_LOCAL_ONLY";
2133 							goto CLEANUP;
2134 						}
2135 					}
2136 				}
2137 
2138 				HLog(hub, "LH_AUTH_OK", c->Name, username);
2139 			}
2140 
2141 			policy = NULL;
2142 
2143 			// Authentication success
2144 			FreePack(p);
2145 
2146 			// Check the assigned VLAN ID
2147 			if (radius_login_opt.Out_IsRadiusLogin)
2148 			{
2149 				if (radius_login_opt.In_CheckVLanId)
2150 				{
2151 					if (radius_login_opt.Out_VLanId != 0)
2152 					{
2153 						assigned_vlan_id = radius_login_opt.Out_VLanId;
2154 					}
2155 
2156 					if (radius_login_opt.In_DenyNoVlanId && assigned_vlan_id == 0 || assigned_vlan_id >= 4096)
2157 					{
2158 						// Deny this session
2159 						Unlock(hub->lock);
2160 						ReleaseHub(hub);
2161 						c->Err = ERR_ACCESS_DENIED;
2162 						error_detail = "In_DenyNoVlanId";
2163 						goto CLEANUP;
2164 					}
2165 				}
2166 			}
2167 
2168 			// Check the assigned MAC Address
2169 			if (radius_login_opt.Out_IsRadiusLogin)
2170 			{
2171 				Copy(assigned_ipc_mac_address, radius_login_opt.Out_VirtualMacAddress, 6);
2172 			}
2173 
2174 			if (StrCmpi(username, ADMINISTRATOR_USERNAME) != 0)
2175 			{
2176 				// Get the policy
2177 				if (farm_member == false)
2178 				{
2179 					bool is_asterisk_user = false;
2180 
2181 					// In the case of not a farm member
2182 					user = AcGetUser(hub, username);
2183 					if (user == NULL)
2184 					{
2185 						user = AcGetUser(hub, "*");
2186 						if (user == NULL)
2187 						{
2188 							// User acquisition failure
2189 							Unlock(hub->lock);
2190 							ReleaseHub(hub);
2191 							c->Err = ERR_ACCESS_DENIED;
2192 							error_detail = "AcGetUser";
2193 							goto CLEANUP;
2194 						}
2195 
2196 						is_asterisk_user = true;
2197 					}
2198 
2199 					policy = NULL;
2200 
2201 					Lock(user->lock);
2202 					{
2203 						if (is_asterisk_user == false)
2204 						{
2205 							UCHAR associated_mac_address[6];
2206 
2207 							// Get the associated virtual MAC address
2208 							if (GetUserMacAddressFromUserNote(associated_mac_address, user->Note))
2209 							{
2210 								if (IsZero(assigned_ipc_mac_address, 6))
2211 								{
2212 									WHERE;
2213 									Copy(assigned_ipc_mac_address, associated_mac_address, 6);
2214 								}
2215 							}
2216 						}
2217 
2218 						// Get the expiration date
2219 						user_expires = user->ExpireTime;
2220 
2221 						StrCpy(username_real, sizeof(username_real), user->Name);
2222 						group = user->Group;
2223 						if (group != NULL)
2224 						{
2225 							AddRef(group->ref);
2226 
2227 							Lock(group->lock);
2228 							{
2229 								// Get the group name
2230 								StrCpy(groupname, sizeof(groupname), group->Name);
2231 							}
2232 							Unlock(group->lock);
2233 						}
2234 
2235 						if (user->Policy != NULL)
2236 						{
2237 							policy = ClonePolicy(user->Policy);
2238 						}
2239 						else
2240 						{
2241 							if (group)
2242 							{
2243 								Lock(group->lock);
2244 								{
2245 									if (group->Policy != NULL)
2246 									{
2247 										policy = ClonePolicy(group->Policy);
2248 									}
2249 								}
2250 								Unlock(group->lock);
2251 							}
2252 						}
2253 
2254 						if (group != NULL)
2255 						{
2256 							ReleaseGroup(group);
2257 						}
2258 					}
2259 					Unlock(user->lock);
2260 					loggedin_user_object = user;
2261 				}
2262 				else
2263 				{
2264 					// In the case of farm member
2265 					policy = ClonePolicy(&ticketed_policy);
2266 				}
2267 			}
2268 			else
2269 			{
2270 				// Administrator mode
2271 				admin_mode = true;
2272 				StrCpy(username_real, sizeof(username_real), ADMINISTRATOR_USERNAME);
2273 
2274 				policy = ClonePolicy(GetDefaultPolicy());
2275 				policy->NoBroadcastLimiter = true;
2276 				policy->MonitorPort = true;
2277 			}
2278 
2279 			if (policy == NULL)
2280 			{
2281 				// Use the default policy
2282 				policy = ClonePolicy(GetDefaultPolicy());
2283 			}
2284 
2285 			if (policy->MaxConnection == 0)
2286 			{
2287 				policy->MaxConnection = MAX_TCP_CONNECTION;
2288 			}
2289 
2290 			if (policy->TimeOut == 0)
2291 			{
2292 				policy->TimeOut = 20;
2293 			}
2294 
2295 			if (qos)
2296 			{
2297 				// VoIP / QoS
2298 				if (policy->NoQoS)
2299 				{
2300 					// Policy does not allow QoS
2301 					qos = false;
2302 				}
2303 				if (GetServerCapsBool(c->Cedar->Server, "b_support_qos") == false)
2304 				{
2305 					// Server does not support QoS
2306 					qos = false;
2307 					policy->NoQoS = true;
2308 				}
2309 				if (GetHubAdminOption(hub, "deny_qos") != 0)
2310 				{
2311 					// It is prohibited in the management options
2312 					qos = false;
2313 					policy->NoQoS = true;
2314 				}
2315 			}
2316 
2317 			if (GetHubAdminOption(hub, "max_bitrates_download") != 0)
2318 			{
2319 				if (policy->MaxDownload == 0)
2320 				{
2321 					policy->MaxDownload = GetHubAdminOption(hub, "max_bitrates_download");
2322 				}
2323 				else
2324 				{
2325 					UINT r = GetHubAdminOption(hub, "max_bitrates_download");
2326 					policy->MaxDownload = MIN(policy->MaxDownload, r);
2327 				}
2328 			}
2329 
2330 			if (GetHubAdminOption(hub, "max_bitrates_upload") != 0)
2331 			{
2332 				if (policy->MaxUpload == 0)
2333 				{
2334 					policy->MaxUpload = GetHubAdminOption(hub, "max_bitrates_upload");
2335 				}
2336 				else
2337 				{
2338 					UINT r = GetHubAdminOption(hub, "max_bitrates_upload");
2339 					policy->MaxUpload = MIN(policy->MaxUpload, r);
2340 				}
2341 			}
2342 
2343 			if (GetHubAdminOption(hub, "deny_bridge") != 0)
2344 			{
2345 				policy->NoBridge = true;
2346 			}
2347 
2348 			if (GetHubAdminOption(hub, "deny_routing") != 0)
2349 			{
2350 				policy->NoRouting = true;
2351 			}
2352 
2353 			if (c->IsInProc)
2354 			{
2355 				policy->NoBridge = false;
2356 				policy->NoRouting = false;
2357 			}
2358 
2359 			if (hub->Option->ClientMinimumRequiredBuild > c->ClientBuild &&
2360 				 InStrEx(c->ClientStr, "client", false))
2361 			{
2362 				// Build number of the client is too small
2363 				HLog(hub, "LH_CLIENT_VERSION_OLD", c->Name, c->ClientBuild, hub->Option->ClientMinimumRequiredBuild);
2364 
2365 				Unlock(hub->lock);
2366 				ReleaseHub(hub);
2367 				c->Err = ERR_VERSION_INVALID;
2368 				Free(policy);
2369 				error_detail = "ERR_VERSION_INVALID";
2370 				goto CLEANUP;
2371 			}
2372 
2373 			if (hub->Option->RequiredClientId != 0 &&
2374 				hub->Option->RequiredClientId != client_id &&
2375 				InStrEx(c->ClientStr, "client", false))
2376 			{
2377 				// Build number of the client is too small
2378 				HLog(hub, "LH_CLIENT_ID_REQUIRED", c->Name, client_id, hub->Option->RequiredClientId);
2379 
2380 				Unlock(hub->lock);
2381 				ReleaseHub(hub);
2382 				c->Err = ERR_CLIENT_ID_REQUIRED;
2383 				error_detail = "ERR_CLIENT_ID_REQUIRED";
2384 				Free(policy);
2385 				goto CLEANUP;
2386 			}
2387 
2388 			if ((policy->NoSavePassword) || (policy->AutoDisconnect != 0))
2389 			{
2390 				if (c->ClientBuild < 6560 && InStrEx(c->ClientStr, "client", false))
2391 				{
2392 					// If NoSavePassword policy is specified,
2393 					// only supported client can connect
2394 					HLog(hub, "LH_CLIENT_VERSION_OLD", c->Name, c->ClientBuild, 6560);
2395 
2396 					Unlock(hub->lock);
2397 					ReleaseHub(hub);
2398 					c->Err = ERR_VERSION_INVALID;
2399 					error_detail = "ERR_VERSION_INVALID";
2400 					Free(policy);
2401 					goto CLEANUP;
2402 				}
2403 			}
2404 
2405 			if (user_expires != 0 && user_expires <= SystemTime64())
2406 			{
2407 				// User expired
2408 				HLog(hub, "LH_USER_EXPIRES", c->Name, username);
2409 
2410 				Unlock(hub->lock);
2411 				ReleaseHub(hub);
2412 				c->Err = ERR_ACCESS_DENIED;
2413 				error_detail = "LH_USER_EXPIRES";
2414 				Free(policy);
2415 				goto CLEANUP;
2416 			}
2417 
2418 			if (policy->Access == false)
2419 			{
2420 				// Access is denied
2421 				HLog(hub, "LH_POLICY_ACCESS_NG", c->Name, username);
2422 
2423 				Unlock(hub->lock);
2424 				ReleaseHub(hub);
2425 				error_detail = "LH_POLICY_ACCESS_NG";
2426 				c->Err = ERR_ACCESS_DENIED;
2427 				Free(policy);
2428 				goto CLEANUP;
2429 			}
2430 
2431 			// Determine the contents of the policy by comparing to
2432 			// option presented by client or deny the connection.
2433 			// Confirm the connectivity in the monitor-mode first
2434 			if (require_monitor_mode && policy->MonitorPort == false)
2435 			{
2436 				// Can not connect in the monitor port mode
2437 				HLog(hub, "LH_POLICY_MONITOR_MODE", c->Name);
2438 
2439 				Unlock(hub->lock);
2440 				ReleaseHub(hub);
2441 				c->Err = ERR_MONITOR_MODE_DENIED;
2442 				Free(policy);
2443 				error_detail = "ERR_MONITOR_MODE_DENIED";
2444 				goto CLEANUP;
2445 			}
2446 
2447 			if (policy->MonitorPort)
2448 			{
2449 				if (require_monitor_mode == false)
2450 				{
2451 					policy->MonitorPort = false;
2452 				}
2453 			}
2454 
2455 			if (policy->MonitorPort)
2456 			{
2457 				qos = false;
2458 			}
2459 
2460 			// Determine whether it can be connected by a bridge / routing mode next
2461 			if (require_bridge_routing_mode &&
2462 				(policy->NoBridge && policy->NoRouting))
2463 			{
2464 				// Can not be connected by a bridge / routing mode
2465 				HLog(hub, "LH_POLICY_BRIDGE_MODE", c->Name);
2466 
2467 				Unlock(hub->lock);
2468 				ReleaseHub(hub);
2469 				c->Err = ERR_BRIDGE_MODE_DENIED;
2470 				error_detail = "ERR_BRIDGE_MODE_DENIED";
2471 				Free(policy);
2472 				goto CLEANUP;
2473 			}
2474 
2475 			if (require_bridge_routing_mode == false)
2476 			{
2477 				policy->NoBridge = true;
2478 				policy->NoRouting = true;
2479 			}
2480 
2481 			if (Cmp(unique, unique2, SHA1_SIZE) == 0)
2482 			{
2483 				// It's a localhost session
2484 				local_host_session = true;
2485 			}
2486 
2487 			if (local_host_session == false)
2488 			{
2489 				// Make further judgment whether localhost session
2490 				SOCK *s = c->FirstSock;
2491 
2492 				if (s != NULL)
2493 				{
2494 					if (IsIPMyHost(&s->RemoteIP))
2495 					{
2496 						// It's a localhost session
2497 						local_host_session = true;
2498 					}
2499 				}
2500 			}
2501 
2502 			if (local_host_session)
2503 			{
2504 				// Permit routing or bridging in the case of localhost session
2505 				policy->NoBridge = false;
2506 				policy->NoRouting = false;
2507 			}
2508 
2509 			if (local_host_session == false)
2510 			{
2511 
2512 				if (policy->NoBridge == false || policy->NoRouting == false)
2513 				{
2514 					use_bridge_license = true;
2515 				}
2516 				else
2517 				{
2518 					use_client_license = true;
2519 				}
2520 			}
2521 
2522 
2523 			if (server != NULL && server->ServerType != SERVER_TYPE_FARM_MEMBER &&
2524 				policy != NULL)
2525 			{
2526 				if (GetServerCapsBool(hub->Cedar->Server, "b_support_limit_multilogin"))
2527 				{
2528 					// Check if the number of concurrent multiple logins limit is specified in the policy
2529 					RPC_ENUM_SESSION t;
2530 					UINT i, num;
2531 					UINT max_logins = policy->MultiLogins;
2532 					UINT ao = GetHubAdminOption(hub, "max_multilogins_per_user");
2533 
2534 					if (ao != 0)
2535 					{
2536 						if (max_logins != 0)
2537 						{
2538 							max_logins = MIN(max_logins, ao);
2539 						}
2540 						else
2541 						{
2542 							max_logins = ao;
2543 						}
2544 					}
2545 
2546 					if (max_logins != 0)
2547 					{
2548 						Zero(&t, sizeof(t));
2549 						StrCpy(t.HubName, sizeof(t.HubName), hub->Name);
2550 
2551 						Unlock(hub->lock);
2552 
2553 						SiEnumSessionMain(server, &t);
2554 
2555 						Lock(hub->lock);
2556 
2557 						num = 0;
2558 
2559 						for (i = 0;i < t.NumSession;i++)
2560 						{
2561 							RPC_ENUM_SESSION_ITEM *e = &t.Sessions[i];
2562 
2563 							if (e->BridgeMode == false && e->Layer3Mode == false && e->LinkMode == false && e->CurrentNumTcp != 0)
2564 							{
2565 								if (StrCmpi(e->Username, username) == 0 &&
2566 									(IsZero(e->UniqueId, 16) || Cmp(e->UniqueId, node.UniqueId, 16) != 0))
2567 								{
2568 									num++;
2569 								}
2570 							}
2571 						}
2572 
2573 						FreeRpcEnumSession(&t);
2574 
2575 						if (num >= max_logins)
2576 						{
2577 							// Can not connect any more
2578 							Unlock(hub->lock);
2579 
2580 							// Dump a detailed error log
2581 							HLog(hub, "LH_TOO_MANY_MULTILOGINS",
2582 								c->Name,
2583 								username, max_logins, num);
2584 
2585 							ReleaseHub(hub);
2586 							c->Err = ERR_TOO_MANY_USER_SESSION;
2587 							Free(policy);
2588 							goto CLEANUP;
2589 						}
2590 					}
2591 				}
2592 			}
2593 
2594 			if (loggedin_user_object != NULL)
2595 			{
2596 				// Update the user information
2597 				Lock(loggedin_user_object->lock);
2598 				{
2599 					loggedin_user_object->LastLoginTime = SystemTime64();
2600 				}
2601 				Unlock(loggedin_user_object->lock);
2602 			}
2603 
2604 			// Update the number of log-ins
2605 			hub->LastCommTime = hub->LastLoginTime = SystemTime64();
2606 
2607 			if (farm_controller)
2608 			{
2609 				wchar_t *msg = GetHubMsg(hub);
2610 
2611 				Unlock(hub->lock);
2612 
2613 				Lock(cedar->CedarSuperLock);
2614 
2615 				// In the case of farm controller, choose a farm members to host this HUB
2616 				LockList(server->FarmMemberList);
2617 				{
2618 					HLog(hub, "LH_FARM_SELECT_1", c->Name);
2619 					f = SiGetHubHostingMember(server, hub, admin_mode, c);
2620 
2621 					if (f == NULL)
2622 					{
2623 						// Failed in the selection
2624 						HLog(hub, "LH_FARM_SELECT_2", c->Name);
2625 						UnlockList(server->FarmMemberList);
2626 						Unlock(cedar->CedarSuperLock);
2627 						ReleaseHub(hub);
2628 						c->Err = ERR_COULD_NOT_HOST_HUB_ON_FARM;
2629 						Free(policy);
2630 						Free(msg);
2631 						goto CLEANUP;
2632 					}
2633 					else
2634 					{
2635 						if (f->Me == false)
2636 						{
2637 							UCHAR ticket[SHA1_SIZE];
2638 							PACK *p;
2639 							BUF *b;
2640 							UINT i;
2641 
2642 							SLog(c->Cedar, "LH_FARM_SELECT_4", c->Name, f->hostname);
2643 
2644 							// Create a session on the selected server farm member
2645 							Rand(ticket, sizeof(ticket));
2646 							SiCallCreateTicket(server, f, hub->Name,
2647 								username, username_real, policy, ticket, Inc(hub->SessionCounter), groupname);
2648 
2649 							p = NewPack();
2650 							PackAddInt(p, "Redirect", 1);
2651 							PackAddIp32(p, "Ip", f->Ip);
2652 							for (i = 0;i < f->NumPort;i++)
2653 							{
2654 								PackAddIntEx(p, "Port", f->Ports[i], i, f->NumPort);
2655 							}
2656 							PackAddData(p, "Ticket", ticket, sizeof(ticket));
2657 
2658 							if (true)
2659 							{
2660 								char *utf = CopyUniToUtf(msg);
2661 
2662 								PackAddData(p, "Msg", utf, StrLen(utf));
2663 
2664 								Free(utf);
2665 							}
2666 
2667 							b = XToBuf(f->ServerCert, false);
2668 							PackAddBuf(p, "Cert", b);
2669 							FreeBuf(b);
2670 
2671 							UnlockList(server->FarmMemberList);
2672 							Unlock(cedar->CedarSuperLock);
2673 							ReleaseHub(hub);
2674 
2675 							HttpServerSend(c->FirstSock, p);
2676 							FreePack(p);
2677 
2678 							c->Err = 0;
2679 							Free(policy);
2680 
2681 							FreePack(HttpServerRecv(c->FirstSock));
2682 							Free(msg);
2683 							goto CLEANUP;
2684 						}
2685 						else
2686 						{
2687 							HLog(hub, "LH_FARM_SELECT_3", c->Name);
2688 							// Continue the process because myself was selected
2689 							UnlockList(server->FarmMemberList);
2690 							Unlock(cedar->CedarSuperLock);
2691 							f->Point = SiGetPoint(server);
2692 							Lock(hub->lock);
2693 							Free(msg);
2694 						}
2695 					}
2696 				}
2697 			}
2698 
2699 			if (admin_mode == false)
2700 			{
2701 				// Check the maximum number of connections of the HUB
2702 				if (hub->Option->MaxSession != 0 &&
2703 					hub->Option->MaxSession <= Count(hub->NumSessions))
2704 				{
2705 					// Can not connect any more
2706 					Unlock(hub->lock);
2707 
2708 					HLog(hub, "LH_MAX_SESSION", c->Name, hub->Option->MaxSession);
2709 
2710 					ReleaseHub(hub);
2711 					c->Err = ERR_HUB_IS_BUSY;
2712 					Free(policy);
2713 					error_detail = "ERR_HUB_IS_BUSY";
2714 					goto CLEANUP;
2715 				}
2716 			}
2717 
2718 			if (use_encrypt == false && c->FirstSock->IsReverseAcceptedSocket)
2719 			{
2720 				// On VPN Azure, SSL encryption is mandated.
2721 				use_encrypt = true;
2722 			}
2723 
2724 			if (use_client_license || use_bridge_license)
2725 			{
2726 				// Examine whether not to conflict with the limit of simultaneous connections
2727 				// number of sessions defined by the Virtual HUB management options
2728 				if (
2729 					(GetHubAdminOption(hub, "max_sessions") != 0 &&
2730 					(Count(hub->NumSessionsClient) + Count(hub->NumSessionsBridge)) >= GetHubAdminOption(hub, "max_sessions"))
2731 					||
2732 					(hub->Option->MaxSession != 0 &&
2733 					(Count(hub->NumSessionsClient) + Count(hub->NumSessionsBridge)) >= hub->Option->MaxSession))
2734 				{
2735 					// Can not connect any more
2736 					Unlock(hub->lock);
2737 
2738 					HLog(hub, "LH_MAX_SESSION", c->Name, GetHubAdminOption(hub, "max_sessions"));
2739 
2740 					ReleaseHub(hub);
2741 					c->Err = ERR_HUB_IS_BUSY;
2742 					Free(policy);
2743 					goto CLEANUP;
2744 				}
2745 			}
2746 
2747 			if (use_client_license)
2748 			{
2749 				// Examine whether not to conflict with the limit of simultaneous connections
2750 				// number of sessions(client) defined by the Virtual HUB management options
2751 				if (((GetHubAdminOption(hub, "max_sessions_client_bridge_apply") != 0
2752 					) &&
2753 					Count(hub->NumSessionsClient) >= GetHubAdminOption(hub, "max_sessions_client") && hub->Cedar->Server != NULL && hub->Cedar->Server->ServerType != SERVER_TYPE_FARM_MEMBER)
2754 					||
2755 					(hub->FarmMember_MaxSessionClientBridgeApply &&
2756 					Count(hub->NumSessionsClient) >= hub->FarmMember_MaxSessionClient))
2757 				{
2758 					// Can not connect any more
2759 					Unlock(hub->lock);
2760 
2761 					HLog(hub, "LH_MAX_SESSION_CLIENT", c->Name, GetHubAdminOption(hub, "max_sessions_client"));
2762 
2763 					ReleaseHub(hub);
2764 					c->Err = ERR_HUB_IS_BUSY;
2765 					Free(policy);
2766 					goto CLEANUP;
2767 				}
2768 			}
2769 
2770 			if (use_bridge_license)
2771 			{
2772 				// Examine whether not to conflict with the limit of simultaneous connections
2773 				// number of sessions(bridge) defined by the Virtual HUB management options
2774 				if (((GetHubAdminOption(hub, "max_sessions_client_bridge_apply") != 0
2775 					) &&
2776 					Count(hub->NumSessionsBridge) >= GetHubAdminOption(hub, "max_sessions_bridge") && hub->Cedar->Server != NULL && hub->Cedar->Server->ServerType != SERVER_TYPE_FARM_MEMBER)
2777 					||
2778 					(hub->FarmMember_MaxSessionClientBridgeApply &&
2779 					Count(hub->NumSessionsBridge) >= hub->FarmMember_MaxSessionBridge))
2780 				{
2781 					// Can not connect any more
2782 					Unlock(hub->lock);
2783 
2784 					HLog(hub, "LH_MAX_SESSION_BRIDGE", c->Name, GetHubAdminOption(hub, "max_sessions_bridge"));
2785 
2786 					ReleaseHub(hub);
2787 					c->Err = ERR_HUB_IS_BUSY;
2788 					Free(policy);
2789 					goto CLEANUP;
2790 				}
2791 			}
2792 
2793 			if (Count(hub->Cedar->CurrentSessions) >= GetServerCapsInt(hub->Cedar->Server, "i_max_sessions"))
2794 			{
2795 				// Can not connect any more
2796 				Unlock(hub->lock);
2797 
2798 				HLog(hub, "LH_MAX_SESSION_2", c->Name, GetServerCapsInt(hub->Cedar->Server, "i_max_sessions"));
2799 
2800 				ReleaseHub(hub);
2801 				c->Err = ERR_HUB_IS_BUSY;
2802 				Free(policy);
2803 				goto CLEANUP;
2804 			}
2805 
2806 			// Increment the current number of connections
2807 			Inc(hub->NumSessions);
2808 			if (use_bridge_license)
2809 			{
2810 				Inc(hub->NumSessionsBridge);
2811 			}
2812 
2813 			if (use_client_license)
2814 			{
2815 				Inc(hub->NumSessionsClient);
2816 			}
2817 			Inc(hub->Cedar->CurrentSessions);
2818 
2819 			// Calculate the time-out period
2820 			timeout = policy->TimeOut * 1000;	// Convert milliseconds to seconds
2821 			if (timeout == 0)
2822 			{
2823 				timeout = TIMEOUT_DEFAULT;
2824 			}
2825 			timeout = MIN(timeout, TIMEOUT_MAX);
2826 			timeout = MAX(timeout, TIMEOUT_MIN);
2827 
2828 			// Update the max_connection according to the policy
2829 			max_connection = MIN(max_connection, policy->MaxConnection);
2830 			max_connection = MIN(max_connection, MAX_TCP_CONNECTION);
2831 			max_connection = MAX(max_connection, 1);
2832 
2833 			if (c->FirstSock->IsRUDPSocket)
2834 			{
2835 				// In the case of TCP-over-UDP
2836 				half_connection = false;
2837 
2838 				// Disable the QoS
2839 				qos = false;
2840 
2841 				if (enable_udp_recovery == false)
2842 				{
2843 					// Disable the session reconnection feature
2844 					no_reconnect_to_session = true;
2845 					max_connection = 1;
2846 				}
2847 				else
2848 				{
2849 					// If the UDP recovery is enabled, permit the session re-connection feature (for 2)
2850 					no_reconnect_to_session = false;
2851 					max_connection = NUM_TCP_CONNECTION_FOR_UDP_RECOVERY;
2852 				}
2853 			}
2854 
2855 			if (half_connection)
2856 			{
2857 				// Number of connections should be more than 2 in the case of Half Connection
2858 				max_connection = MAX(max_connection, 2);
2859 			}
2860 
2861 			if (qos)
2862 			{
2863 				// Number of connections is set to 2 or more when using the VoIP / QoS
2864 				max_connection = MAX(max_connection, 2);
2865 				if (half_connection)
2866 				{
2867 					max_connection = MAX(max_connection, 4);
2868 				}
2869 			}
2870 
2871 			c->Status = CONNECTION_STATUS_ESTABLISHED;
2872 
2873 			// Remove the connection from Cedar
2874 			DelConnection(c->Cedar, c);
2875 
2876 			// VLAN ID
2877 			if (assigned_vlan_id != 0)
2878 			{
2879 				if (policy->VLanId == 0)
2880 				{
2881 					policy->VLanId = assigned_vlan_id;
2882 				}
2883 			}
2884 
2885 			// Create a Session
2886 			StrLower(username);
2887 			s = NewServerSessionEx(c->Cedar, c, hub, username, policy, c->IsInProc,
2888 				(c->IsInProc && IsZero(assigned_ipc_mac_address, 6) == false) ? assigned_ipc_mac_address : NULL);
2889 
2890 			s->EnableUdpRecovery = enable_udp_recovery;
2891 			s->LocalHostSession = local_host_session;
2892 			s->NormalClient = true;
2893 
2894 			IPToStr(s->ClientIP, sizeof(s->ClientIP), &c->ClientIp);
2895 
2896 			if (c->FirstSock->IsRUDPSocket)
2897 			{
2898 				// R-UDP session
2899 				s->IsRUDPSession = true;
2900 				s->RUdpMss = c->FirstSock->RUDP_OptimizedMss;
2901 				Debug("ServerAccept(): Optimized MSS Value for R-UDP: %u\n", s->RUdpMss);
2902 				AddProtocolDetailsKeyValueInt(s->ProtocolDetails, sizeof(s->ProtocolDetails), "RUDP_MSS", s->RUdpMss);
2903 			}
2904 
2905 			if (enable_bulk_on_rudp)
2906 			{
2907 				// Allow bulk transfer on R-UDP
2908 				s->EnableBulkOnRUDP = true;
2909 				s->EnableHMacOnBulkOfRUDP = enable_hmac_on_bulk_of_rudp;
2910 			}
2911 
2912 			s->IsAzureSession = c->FirstSock->IsReverseAcceptedSocket;
2913 
2914 			StrCpy(s->UnderlayProtocol, sizeof(s->UnderlayProtocol), c->FirstSock->UnderlayProtocol);
2915 
2916 			AddProtocolDetailsStr(s->ProtocolDetails, sizeof(s->ProtocolDetails), c->FirstSock->ProtocolDetails);
2917 
2918 			if (server != NULL)
2919 			{
2920 				s->NoSendSignature = server->NoSendSignature;
2921 			}
2922 
2923 			if (c->IsInProc)
2924 			{
2925 				s->NoSendSignature = true;
2926 			}
2927 
2928 			if (c->IsInProc && StrCmpi(c->InProcPrefix, OPENVPN_IPC_POSTFIX_L3) == 0)
2929 			{
2930 				// OpenVPN L3 session
2931 				s->IsOpenVPNL3Session = true;
2932 			}
2933 
2934 			if (c->IsInProc && StrCmpi(c->InProcPrefix, OPENVPN_IPC_POSTFIX_L2) == 0)
2935 			{
2936 				// OpenVPN L2 session
2937 				s->IsOpenVPNL2Session = true;
2938 			}
2939 
2940 			// Determine whether the use of UDP acceleration mode
2941 			if (use_udp_acceleration_client)
2942 			{
2943 				s->UseUdpAcceleration = true;
2944 
2945 				s->UdpAccelFastDisconnectDetect = support_udp_accel_fast_disconnect_detect;
2946 
2947 				udp_acceleration_version = 1;
2948 				if (client_udp_acceleration_max_version >= 2)
2949 				{
2950 					udp_acceleration_version = 2;
2951 				}
2952 			}
2953 
2954 			if (client_rudp_bulk_max_version >= 2)
2955 			{
2956 				rudp_bulk_version = 2;
2957 			}
2958 
2959 			if (s->EnableBulkOnRUDP)
2960 			{
2961 				AddProtocolDetailsKeyValueInt(s->ProtocolDetails, sizeof(s->ProtocolDetails), "RUDP_Bulk_Ver", s->BulkOnRUDPVersion);
2962 			}
2963 
2964 			if (hub->Option != NULL && hub->Option->DisableUdpAcceleration)
2965 			{
2966 				s->UseUdpAcceleration = false;
2967 			}
2968 
2969 			if (IsZeroIP(&c->FirstSock->Reverse_MyServerGlobalIp) == false &&
2970 				CmpIpAddr(&c->FirstSock->Reverse_MyServerGlobalIp, &c->FirstSock->RemoteIP) == 0)
2971 			{
2972 				// Disable forcibly the UDP acceleration mode if VPN Server and VPN Client
2973 				// are in same LAN in the case of using VPN Azure.
2974 				// (Or this may cause infinite loop of packet)
2975 				s->UseUdpAcceleration = false;
2976 			}
2977 
2978 			if (s->UseUdpAcceleration)
2979 			{
2980 				s->UseHMacOnUdpAcceleration = use_hmac_on_udp_acceleration;
2981 			}
2982 
2983 			Debug("UseUdpAcceleration = %u\n", s->UseUdpAcceleration);
2984 			Debug("UseHMacOnUdpAcceleration = %u\n", s->UseHMacOnUdpAcceleration);
2985 			Debug("UdpAccelerationVersion = %u\n", s->UdpAccelerationVersion);
2986 
2987 			if (s->UseUdpAcceleration)
2988 			{
2989 				bool no_nat_t = false;
2990 
2991 
2992 				// Initialize the UDP acceleration function
2993 				s->UdpAccel = NewUdpAccel(c->Cedar, (c->FirstSock->IsRUDPSocket ? NULL : &c->FirstSock->LocalIP), false, c->FirstSock->IsRUDPSocket, no_nat_t);
2994 				if (s->UdpAccel == NULL)
2995 				{
2996 					s->UseUdpAcceleration = false;
2997 					Debug("NewUdpAccel Failed.\n");
2998 				}
2999 				else
3000 				{
3001 					s->UdpAccel->Version = udp_acceleration_version;
3002 
3003 					if (UdpAccelInitServer(s->UdpAccel,
3004 						s->UdpAccel->Version == 2 ? udp_acceleration_client_key_v2 : udp_acceleration_client_key,
3005 						&c->FirstSock->RemoteIP, &udp_acceleration_client_ip, udp_acceleration_client_port) == false)
3006 					{
3007 						Debug("UdpAccelInitServer Failed.\n");
3008 						s->UseUdpAcceleration = false;
3009 					}
3010 
3011 					s->UdpAccel->FastDetect = s->UdpAccelFastDisconnectDetect;
3012 
3013 					if (use_encrypt == false)
3014 					{
3015 						s->UdpAccel->PlainTextMode = true;
3016 					}
3017 
3018 					s->UdpAccel->UseHMac = s->UseHMacOnUdpAcceleration;
3019 
3020 					AddProtocolDetailsKeyValueInt(s->ProtocolDetails, sizeof(s->ProtocolDetails), "UDPAccel_Ver", s->UdpAccel->Version);
3021 
3022 					AddProtocolDetailsStr(s->ProtocolDetails, sizeof(s->ProtocolDetails), s->UdpAccel->Version > 1 ? "ChaCha20-Poly1305" : "RC4");
3023 
3024 					AddProtocolDetailsKeyValueInt(s->ProtocolDetails, sizeof(s->ProtocolDetails), "UDPAccel_MSS", UdpAccelCalcMss(s->UdpAccel));
3025 				}
3026 			}
3027 
3028 			s->UseClientLicense = use_client_license;
3029 			s->UseBridgeLicense = use_bridge_license;
3030 
3031 			s->AdjustMss = adjust_mss;
3032 			if (s->AdjustMss != 0)
3033 			{
3034 				Debug("AdjustMSS: %u\n", s->AdjustMss);
3035 				AddProtocolDetailsKeyValueInt(s->ProtocolDetails, sizeof(s->ProtocolDetails), "AdjustMSS", s->AdjustMss);
3036 			}
3037 
3038 			s->IsBridgeMode = (policy->NoBridge == false) || (policy->NoRouting == false);
3039 			s->IsMonitorMode = policy->MonitorPort;
3040 
3041 			// Decide whether IPv6 session
3042 			s->IPv6Session = false;
3043 
3044 			if (node.ClientIpAddress == 0)
3045 			{
3046 				s->IPv6Session = true;
3047 			}
3048 
3049 			if (use_bridge_license)
3050 			{
3051 				Inc(s->Cedar->AssignedBridgeLicense);
3052 			}
3053 
3054 			if (use_client_license)
3055 			{
3056 				Inc(s->Cedar->AssignedClientLicense);
3057 			}
3058 
3059 			if (server != NULL)
3060 			{
3061 				// Update the total allocation of the number of licenses for Server structure
3062 				if (server->ServerType == SERVER_TYPE_STANDALONE)
3063 				{
3064 					// Update only stand-alone mode
3065 					// (Periodically poll in the cluster controller mode)
3066 					server->CurrentAssignedClientLicense = Count(s->Cedar->AssignedClientLicense);
3067 					server->CurrentAssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense);
3068 				}
3069 			}
3070 
3071 			if (StrLen(sessionname) != 0)
3072 			{
3073 				// Specify the session name
3074 				Free(s->Name);
3075 				s->Name = CopyStr(sessionname);
3076 			}
3077 
3078 			{
3079 				char ip[128];
3080 				IPToStr(ip, sizeof(ip), &c->FirstSock->RemoteIP);
3081 				HLog(hub, "LH_NEW_SESSION", c->Name, s->Name, ip, c->FirstSock->RemotePort, c->FirstSock->UnderlayProtocol, c->FirstSock->ProtocolDetails);
3082 			}
3083 
3084 			c->Session = s;
3085 			s->AdministratorMode = admin_mode;
3086 			StrCpy(s->UserNameReal, sizeof(s->UserNameReal), username_real);
3087 			StrCpy(s->GroupName, sizeof(s->GroupName), groupname);
3088 
3089 			// Get the session key
3090 			Copy(session_key, s->SessionKey, SHA1_SIZE);
3091 
3092 			// Set the parameters
3093 			s->MaxConnection = max_connection;
3094 			s->UseEncrypt = use_encrypt;
3095 			s->UseCompress = use_compress;
3096 			s->HalfConnection = half_connection;
3097 			s->Timeout = timeout;
3098 			s->QoS = qos;
3099 			s->NoReconnectToSession = no_reconnect_to_session;
3100 			s->VLanId = policy->VLanId;
3101 
3102 			// User name
3103 			s->Username = CopyStr(username);
3104 
3105 			HLog(hub, "LH_SET_SESSION", s->Name, s->MaxConnection,
3106 				s->UseEncrypt ? _UU("L_YES") : _UU("L_NO"),
3107 				s->UseCompress ? _UU("L_YES") : _UU("L_NO"),
3108 				s->HalfConnection ? _UU("L_YES") : _UU("L_NO"),
3109 				s->Timeout / 1000);
3110 
3111 			msg = GetHubMsg(hub);
3112 
3113 			// Suppress client update notification flag
3114 			if (hub->Option != NULL)
3115 			{
3116 				suppress_client_update_notification = hub->Option->SuppressClientUpdateNotification;
3117 			}
3118 		}
3119 		Unlock(hub->lock);
3120 
3121 		// Send a Welcome packet to the client
3122 		p = PackWelcome(s);
3123 
3124 		PackAddBool(p, "suppress_client_update_notification", suppress_client_update_notification);
3125 
3126 		if (s != NULL && s->InProcMode)
3127 		{
3128 			if (IsZero(mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20)) == false)
3129 			{
3130 				// MS-CHAPv2 Response
3131 				PackAddData(p, "IpcMsChapV2ServerResponse", mschap_v2_server_response_20, sizeof(mschap_v2_server_response_20));
3132 			}
3133 		}
3134 
3135 		if (true)
3136 		{
3137 			// A message to be displayed in the VPN Client (Will not be displayed if the VPN Gate Virtual HUB)
3138 			char *utf;
3139 			wchar_t winver_msg_client[3800];
3140 			wchar_t winver_msg_server[3800];
3141 			UINT tmpsize;
3142 			wchar_t *tmp;
3143 			RPC_WINVER server_winver;
3144 
3145 			GetWinVer(&server_winver);
3146 
3147 			Zero(winver_msg_client, sizeof(winver_msg_client));
3148 			Zero(winver_msg_server, sizeof(winver_msg_server));
3149 
3150 			if (IsSupportedWinVer(&winver) == false)
3151 			{
3152 				SYSTEMTIME st;
3153 
3154 				LocalTime(&st);
3155 
3156 				UniFormat(winver_msg_client, sizeof(winver_msg_client), _UU("WINVER_ERROR_FORMAT"),
3157 					_UU("WINVER_ERROR_PC_LOCAL"),
3158 					winver.Title,
3159 					_UU("WINVER_ERROR_VPNSERVER"),
3160 					SUPPORTED_WINDOWS_LIST,
3161 					_UU("WINVER_ERROR_PC_LOCAL"),
3162 					_UU("WINVER_ERROR_VPNSERVER"),
3163 					_UU("WINVER_ERROR_VPNSERVER"),
3164 					_UU("WINVER_ERROR_VPNSERVER"),
3165 					st.wYear, st.wMonth);
3166 			}
3167 
3168 			if (IsSupportedWinVer(&server_winver) == false)
3169 			{
3170 				SYSTEMTIME st;
3171 
3172 				LocalTime(&st);
3173 
3174 				UniFormat(winver_msg_server, sizeof(winver_msg_server), _UU("WINVER_ERROR_FORMAT"),
3175 					_UU("WINVER_ERROR_PC_REMOTE"),
3176 					server_winver.Title,
3177 					_UU("WINVER_ERROR_VPNSERVER"),
3178 					SUPPORTED_WINDOWS_LIST,
3179 					_UU("WINVER_ERROR_PC_REMOTE"),
3180 					_UU("WINVER_ERROR_VPNSERVER"),
3181 					_UU("WINVER_ERROR_VPNSERVER"),
3182 					_UU("WINVER_ERROR_VPNSERVER"),
3183 					st.wYear, st.wMonth);
3184 			}
3185 
3186 			tmpsize = UniStrSize(winver_msg_client) + UniStrSize(winver_msg_server) + UniStrSize(msg) + (16000 + 3000) * sizeof(wchar_t);
3187 
3188 			tmp = ZeroMalloc(tmpsize);
3189 
3190 			if (IsURLMsg(msg, NULL, 0) == false)
3191 			{
3192 
3193 				if (s != NULL && s->IsRUDPSession && c != NULL)
3194 				{
3195 					// Show the warning message if the connection is made by NAT-T
3196 					wchar_t *tmp2;
3197 					UINT tmp2_size = 2400 * sizeof(wchar_t);
3198 					char local_name[128];
3199 					wchar_t local_name_2[128];
3200 					char local_name_3[128];
3201 
3202 					Zero(local_name, sizeof(local_name));
3203 					Zero(local_name_2, sizeof(local_name_2));
3204 					Zero(local_name_3, sizeof(local_name_3));
3205 
3206 					GetMachineName(local_name, sizeof(local_name));
3207 
3208 #ifdef	OS_WIN32
3209 					MsGetComputerNameFullEx(local_name_2, sizeof(local_name_2), true);
3210 
3211 					UniToStr(local_name_3, sizeof(local_name_3), local_name_2);
3212 
3213 					if (IsEmptyStr(local_name_3) == false)
3214 					{
3215 						StrCpy(local_name, sizeof(local_name), local_name_3);
3216 					}
3217 #endif	// OS_WIN32
3218 
3219 					tmp2 = ZeroMalloc(tmp2_size);
3220 					UniFormat(tmp2, tmp2_size, _UU(c->ClientBuild >= 9428 ? "NATT_MSG" : "NATT_MSG2"), local_name);
3221 
3222 					UniStrCat(tmp, tmpsize, tmp2);
3223 
3224 					Free(tmp2);
3225 				}
3226 
3227 				{
3228 					if (GetGlobalServerFlag(GSF_SHOW_OSS_MSG) != 0)
3229 					{
3230 						UniStrCat(tmp, tmpsize, _UU("OSS_MSG"));
3231 					}
3232 				}
3233 
3234 				{
3235 					UniStrCat(tmp, tmpsize, winver_msg_client);
3236 					UniStrCat(tmp, tmpsize, winver_msg_server);
3237 				}
3238 			}
3239 			UniStrCat(tmp, tmpsize, msg);
3240 
3241 			utf = CopyUniToUtf(tmp);
3242 
3243 			PackAddData(p, "Msg", utf, StrLen(utf));
3244 
3245 			Free(tmp);
3246 			Free(utf);
3247 		}
3248 
3249 		Free(msg);
3250 
3251 		// Brand string for the connection limit
3252 		{
3253 			char *branded_cfroms = _SS("BRANDED_C_FROM_S");
3254 			if(StrLen(branded_cfroms) > 0)
3255 			{
3256 				PackAddStr(p, "branded_cfroms", branded_cfroms);
3257 			}
3258 		}
3259 
3260 		HttpServerSend(c->FirstSock, p);
3261 		FreePack(p);
3262 
3263 		// Receive a signature
3264 		Copy(&c->Session->NodeInfo, &node, sizeof(NODE_INFO));
3265 
3266 
3267 		{
3268 			wchar_t tmp[MAX_SIZE * 2];
3269 			NodeInfoToStr(tmp, sizeof(tmp), &s->NodeInfo);
3270 
3271 			HLog(hub, "LH_NODE_INFO", s->Name, tmp);
3272 
3273 			if (s->VLanId != 0)
3274 			{
3275 				HLog(hub, "LH_VLAN_ID", s->Name, s->VLanId);
3276 			}
3277 		}
3278 
3279 		// Shift the connection to the tunneling mode
3280 		StartTunnelingMode(c);
3281 
3282 		// Processing of half-connection mode
3283 		if (s->HalfConnection)
3284 		{
3285 			// The direction of the first socket is client to server
3286 			TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
3287 			ts->Direction = TCP_CLIENT_TO_SERVER;
3288 		}
3289 
3290 		if (s->Hub->Type == HUB_TYPE_FARM_DYNAMIC && s->Cedar->Server != NULL && s->Cedar->Server->ServerType == SERVER_TYPE_FARM_CONTROLLER)
3291 		{
3292 			if (s->Hub->BeingOffline == false)
3293 			{
3294 				// Start the SecureNAT on the dynamic Virtual HUB
3295 				EnableSecureNATEx(s->Hub, false, true);
3296 
3297 				cluster_dynamic_secure_nat = true;
3298 			}
3299 		}
3300 
3301 		if (s->LocalHostSession)
3302 		{
3303 			// Update the local MAC address list
3304 			RefreshLocalMacAddressList();
3305 		}
3306 
3307 		// Discard the user list cache
3308 		DeleteAllUserListCache(hub->UserList);
3309 
3310 
3311 		// Main routine of the session
3312 		Debug("SessionMain()\n");
3313 		s->NumLoginIncrementUserObject = loggedin_user_object;
3314 		s->NumLoginIncrementHubObject = s->Hub;
3315 		s->NumLoginIncrementTick = Tick64() + (UINT64)NUM_LOGIN_INCREMENT_INTERVAL;
3316 		SessionMain(s);
3317 
3318 
3319 		// Discard the user list cache
3320 		DeleteAllUserListCache(hub->UserList);
3321 
3322 		// Decrement the current number of connections
3323 		Lock(s->Hub->lock);
3324 		{
3325 			if (use_bridge_license)
3326 			{
3327 				Dec(hub->NumSessionsBridge);
3328 			}
3329 
3330 			if (use_client_license)
3331 			{
3332 				Dec(hub->NumSessionsClient);
3333 			}
3334 
3335 			Dec(s->Hub->NumSessions);
3336 			Dec(s->Hub->Cedar->CurrentSessions);
3337 
3338 			// Decrement the number of licenses
3339 			if (use_bridge_license)
3340 			{
3341 				Dec(s->Cedar->AssignedBridgeLicense);
3342 			}
3343 
3344 			if (use_client_license)
3345 			{
3346 				Dec(s->Cedar->AssignedClientLicense);
3347 			}
3348 
3349 			if (server != NULL)
3350 			{
3351 				// Update the total allocation of the number of licenses for Server structure
3352 				if (server->ServerType == SERVER_TYPE_STANDALONE)
3353 				{
3354 					// Update only stand-alone mode
3355 					// (Periodically polled in the cluster controller mode)
3356 					server->CurrentAssignedClientLicense = Count(s->Cedar->AssignedClientLicense);
3357 					server->CurrentAssignedBridgeLicense = Count(s->Cedar->AssignedBridgeLicense);
3358 				}
3359 			}
3360 		}
3361 		Unlock(s->Hub->lock);
3362 
3363 		PrintSessionTotalDataSize(s);
3364 
3365 		HLog(s->Hub, "LH_END_SESSION", s->Name, s->TotalSendSizeReal, s->TotalRecvSizeReal);
3366 
3367 		if (cluster_dynamic_secure_nat && s->Hub->BeingOffline == false)
3368 		{
3369 			// Stop the SecureNAT on the dynamic Virtual HUB
3370 			EnableSecureNATEx(s->Hub, false, true);
3371 		}
3372 
3373 		if (s->UdpAccel != NULL)
3374 		{
3375 			// Release the UDP acceleration
3376 			FreeUdpAccel(s->UdpAccel);
3377 			s->UdpAccel = NULL;
3378 		}
3379 
3380 		ReleaseSession(s);
3381 
3382 		ret = true;
3383 		c->Err = ERR_SESSION_REMOVED;
3384 
3385 		ReleaseHub(hub);
3386 
3387 		goto CLEANUP;
3388 	}
3389 	else if (StrCmpi(method, "additional_connect") == 0)
3390 	{
3391 		SOCK *sock;
3392 		TCPSOCK *ts;
3393 		UINT dummy;
3394 
3395 		c->Type = CONNECTION_TYPE_ADDITIONAL;
3396 
3397 		// Additional connection
3398 		// Read the session key
3399 		if (GetSessionKeyFromPack(p, session_key, &dummy) == false)
3400 		{
3401 			FreePack(p);
3402 			c->Err = ERR_PROTOCOL_ERROR;
3403 			goto CLEANUP;
3404 		}
3405 
3406 		FreePack(p);
3407 
3408 		// Get the session from the session key
3409 		s = GetSessionFromKey(c->Cedar, session_key);
3410 		if (s == NULL || s->Halt || s->NoReconnectToSession)
3411 		{
3412 			// Session can not be found, or re-connection is prohibited
3413 			Debug("Session Not Found.\n");
3414 			c->Err = ERR_SESSION_TIMEOUT;
3415 			goto CLEANUP;
3416 		}
3417 
3418 		// Session is found
3419 		Debug("Session Found: %s\n", s->Name);
3420 		// Check the protocol of session
3421 		c->Err = 0;
3422 		Lock(s->lock);
3423 		{
3424 			if (s->Connection->Protocol != CONNECTION_TCP)
3425 			{
3426 				c->Err = ERR_INVALID_PROTOCOL;
3427 			}
3428 		}
3429 		Unlock(s->lock);
3430 		// Check the current number of connections of the session
3431 		Lock(s->Connection->lock);
3432 		if (c->Err == 0)
3433 		{
3434 			if (Count(s->Connection->CurrentNumConnection) > s->MaxConnection)
3435 			{
3436 				c->Err = ERR_TOO_MANY_CONNECTION;
3437 			}
3438 		}
3439 		if (c->Err != 0)
3440 		{
3441 			Unlock(s->Connection->lock);
3442 			if (c->Err == ERR_TOO_MANY_CONNECTION)
3443 			{
3444 				Debug("Session TOO MANY CONNECTIONS !!: %u\n",
3445 					Count(s->Connection->CurrentNumConnection));
3446 			}
3447 			else
3448 			{
3449 				Debug("Session Invalid Protocol.\n");
3450 			}
3451 			ReleaseSession(s);
3452 			goto CLEANUP;
3453 		}
3454 
3455 		// Add the socket of this connection to the connection list of the session (TCP)
3456 		sock = c->FirstSock;
3457 
3458 		if (sock->IsRUDPSocket && sock->BulkRecvKey != NULL && sock->BulkSendKey != NULL)
3459 		{
3460 			if (s->BulkRecvKeySize != 0 && s->BulkSendKeySize != 0)
3461 			{
3462 				// Restore R-UDP bulk send/recv keys for additional connections
3463 				Copy(sock->BulkRecvKey->Data, s->BulkRecvKey, s->BulkRecvKeySize);
3464 				sock->BulkRecvKey->Size = s->BulkRecvKeySize;
3465 				Copy(sock->BulkSendKey->Data, s->BulkSendKey, s->BulkSendKeySize);
3466 				sock->BulkSendKey->Size = s->BulkSendKeySize;
3467 			}
3468 		}
3469 
3470 		ts = NewTcpSock(sock);
3471 		SetTimeout(sock, CONNECTING_TIMEOUT);
3472 		direction = TCP_BOTH;
3473 		LockList(s->Connection->Tcp->TcpSockList);
3474 		{
3475 			if (s->HalfConnection)
3476 			{
3477 				// In half-connection, directions of the TCP connections are automatically
3478 				// adjusted by examining all current direction of the TCP connections
3479 				UINT i, c2s, s2c;
3480 				c2s = s2c = 0;
3481 				for (i = 0;i < LIST_NUM(s->Connection->Tcp->TcpSockList);i++)
3482 				{
3483 					TCPSOCK *ts = (TCPSOCK *)LIST_DATA(s->Connection->Tcp->TcpSockList, i);
3484 					if (ts->Direction == TCP_SERVER_TO_CLIENT)
3485 					{
3486 						s2c++;
3487 					}
3488 					else
3489 					{
3490 						c2s++;
3491 					}
3492 				}
3493 				if (s2c > c2s)
3494 				{
3495 					direction = TCP_CLIENT_TO_SERVER;
3496 				}
3497 				else
3498 				{
3499 					direction = TCP_SERVER_TO_CLIENT;
3500 				}
3501 				Debug("%u/%u\n", s2c, c2s);
3502 				ts->Direction = direction;
3503 			}
3504 		}
3505 		UnlockList(s->Connection->Tcp->TcpSockList);
3506 
3507 		// Return a success result
3508 		p = PackError(ERR_NO_ERROR);
3509 		PackAddInt(p, "direction", direction);
3510 
3511 		HttpServerSend(c->FirstSock, p);
3512 		FreePack(p);
3513 
3514 		SetTimeout(sock, INFINITE);
3515 
3516 		LockList(s->Connection->Tcp->TcpSockList);
3517 		{
3518 			Add(s->Connection->Tcp->TcpSockList, ts);
3519 		}
3520 		UnlockList(s->Connection->Tcp->TcpSockList);
3521 
3522 		// Increment the number of connections
3523 		Inc(s->Connection->CurrentNumConnection);
3524 		Debug("TCP Connection Incremented: %u\n", Count(s->Connection->CurrentNumConnection));
3525 
3526 		// Issue the Cancel of session
3527 		Cancel(s->Cancel1);
3528 
3529 		Unlock(s->Connection->lock);
3530 
3531 		c->flag1 = true;
3532 
3533 		ReleaseSession(s);
3534 
3535 		return true;
3536 	}
3537 	else if (StrCmpi(method, "enum_hub") == 0)
3538 	{
3539 		// Enumerate the Virtual HUB
3540 		UINT i, num;
3541 		LIST *o;
3542 		o = NewListFast(NULL);
3543 
3544 		c->Type = CONNECTION_TYPE_ENUM_HUB;
3545 
3546 		FreePack(p);
3547 		p = NewPack();
3548 		LockList(c->Cedar->HubList);
3549 		{
3550 			num = LIST_NUM(c->Cedar->HubList);
3551 			for (i = 0;i < num;i++)
3552 			{
3553 				HUB *h = LIST_DATA(c->Cedar->HubList, i);
3554 				if (h->Option != NULL && h->Option->NoEnum == false)
3555 				{
3556 					Insert(o, CopyStr(h->Name));
3557 				}
3558 			}
3559 		}
3560 		UnlockList(c->Cedar->HubList);
3561 
3562 		num = LIST_NUM(o);
3563 		for (i = 0;i < num;i++)
3564 		{
3565 			char *name = LIST_DATA(o, i);
3566 			PackAddStrEx(p, "HubName", name, i, num);
3567 			Free(name);
3568 		}
3569 		ReleaseList(o);
3570 		PackAddInt(p, "NumHub", num);
3571 
3572 		HttpServerSend(c->FirstSock, p);
3573 		FreePack(p);
3574 		FreePack(HttpServerRecv(c->FirstSock));
3575 		c->Err = 0;
3576 
3577 		SLog(c->Cedar, "LS_ENUM_HUB", c->Name, num);
3578 
3579 		error_detail = "enum_hub";
3580 
3581 		goto CLEANUP;
3582 	}
3583 	else if (StrCmpi(method, "farm_connect") == 0)
3584 	{
3585 		// Server farm connection request
3586 		CEDAR *cedar = c->Cedar;
3587 		c->Type = CONNECTION_TYPE_FARM_RPC;
3588 		c->Err = 0;
3589 		if (c->Cedar->Server == NULL)
3590 		{
3591 			// Unsupported
3592 			c->Err = ERR_NOT_FARM_CONTROLLER;
3593 		}
3594 		else
3595 		{
3596 			SERVER *s = c->Cedar->Server;
3597 			if (s->ServerType != SERVER_TYPE_FARM_CONTROLLER || s->FarmControllerInited == false)
3598 			{
3599 				// Not a farm controller
3600 				SLog(c->Cedar, "LS_FARM_ACCEPT_1", c->Name);
3601 				c->Err = ERR_NOT_FARM_CONTROLLER;
3602 			}
3603 			else
3604 			{
3605 				UCHAR check_secure_password[SHA1_SIZE];
3606 				UCHAR secure_password[SHA1_SIZE];
3607 				// User authentication
3608 				SecurePassword(check_secure_password, s->HashedPassword, c->Random);
3609 				if (PackGetDataSize(p, "SecurePassword") == sizeof(secure_password))
3610 				{
3611 					PackGetData(p, "SecurePassword", secure_password);
3612 				}
3613 				else
3614 				{
3615 					Zero(secure_password, sizeof(secure_password));
3616 				}
3617 
3618 				if (Cmp(secure_password, check_secure_password, SHA1_SIZE) != 0)
3619 				{
3620 					// Password is different
3621 					SLog(c->Cedar, "LS_FARM_ACCEPT_2", c->Name);
3622 					c->Err = ERR_ACCESS_DENIED;
3623 				}
3624 				else
3625 				{
3626 					// Get the certificate
3627 					BUF *b;
3628 					X *server_x;
3629 
3630 					SLog(c->Cedar, "LS_FARM_ACCEPT_3", c->Name);
3631 					b = PackGetBuf(p, "ServerCert");
3632 					if (b == NULL)
3633 					{
3634 						c->Err = ERR_PROTOCOL_ERROR;
3635 					}
3636 					else
3637 					{
3638 						server_x = BufToX(b, false);
3639 						FreeBuf(b);
3640 						if (server_x == NULL)
3641 						{
3642 							c->Err = ERR_PROTOCOL_ERROR;
3643 						}
3644 						else
3645 						{
3646 							UINT ip;
3647 							UINT point;
3648 							char hostname[MAX_SIZE];
3649 
3650 #ifdef	OS_WIN32
3651 							MsSetThreadPriorityRealtime();
3652 #endif	// OS_WIN32
3653 
3654 							SetTimeout(c->FirstSock, SERVER_CONTROL_TCP_TIMEOUT);
3655 
3656 							ip = PackGetIp32(p, "PublicIp");
3657 							point = PackGetInt(p, "Point");
3658 							if (PackGetStr(p, "HostName", hostname, sizeof(hostname)))
3659 							{
3660 								UINT num_port = PackGetIndexCount(p, "PublicPort");
3661 								if (num_port >= 1 && num_port <= MAX_PUBLIC_PORT_NUM)
3662 								{
3663 									UINT *ports = ZeroMalloc(sizeof(UINT) * num_port);
3664 									UINT i;
3665 
3666 									for (i = 0;i < num_port;i++)
3667 									{
3668 										ports[i] = PackGetIntEx(p, "PublicPort", i);
3669 									}
3670 
3671 									SiFarmServ(s, c->FirstSock, server_x, ip, num_port, ports, hostname, point,
3672 										PackGetInt(p, "Weight"), PackGetInt(p, "MaxSessions"));
3673 
3674 									Free(ports);
3675 								}
3676 							}
3677 
3678 							FreeX(server_x);
3679 						}
3680 					}
3681 				}
3682 			}
3683 		}
3684 		FreePack(p);
3685 		goto CLEANUP;
3686 	}
3687 	else if (StrCmpi(method, "admin") == 0 && c->Cedar->Server != NULL)
3688 	{
3689 		UINT err;
3690 		// Administrative RPC connection request
3691 		c->Type = CONNECTION_TYPE_ADMIN_RPC;
3692 		err = AdminAccept(c, p);
3693 		FreePack(p);
3694 		if (err != ERR_NO_ERROR)
3695 		{
3696 			PACK *p = PackError(err);
3697 			HttpServerSend(c->FirstSock, p);
3698 			FreePack(p);
3699 		}
3700 
3701 		error_detail = "admin_rpc";
3702 
3703 		goto CLEANUP;
3704 	}
3705 	else if (StrCmpi(method, "password") == 0)
3706 	{
3707 		UINT err;
3708 		// Password change request
3709 		c->Type = CONNECTION_TYPE_PASSWORD;
3710 		err = ChangePasswordAccept(c, p);
3711 		FreePack(p);
3712 
3713 		p = PackError(err);
3714 		HttpServerSend(c->FirstSock, p);
3715 		FreePack(p);
3716 
3717 		error_detail = "change_password";
3718 
3719 		goto CLEANUP;
3720 	}
3721 	else
3722 	{
3723 		// Unknown method
3724 		FreePack(p);
3725 		c->Err = ERR_PROTOCOL_ERROR;
3726 
3727 		error_detail = "unknown_method";
3728 
3729 		goto CLEANUP;
3730 	}
3731 
3732 CLEANUP:
3733 	// Release the user object
3734 	if (loggedin_user_object != NULL)
3735 	{
3736 		ReleaseUser(loggedin_user_object);
3737 	}
3738 
3739 
3740 	// Error packet transmission
3741 	if (supress_return_pack_error == false)
3742 	{
3743 		p = PackError(c->Err);
3744 		PackAddBool(p, "no_save_password", no_save_password);
3745 		HttpServerSend(c->FirstSock, p);
3746 		FreePack(p);
3747 	}
3748 
3749 	FreePack(HttpServerRecv(c->FirstSock));
3750 
3751 	SleepThread(25);
3752 
3753 	SLog(c->Cedar, "LS_CONNECTION_ERROR", c->Name, GetUniErrorStr(c->Err), c->Err);
3754 
3755 	if (release_me_eap_client != NULL)
3756 	{
3757 		ReleaseEapClient(release_me_eap_client);
3758 	}
3759 
3760 	return ret;
3761 }
3762 
3763 
3764 // Create a Node information
CreateNodeInfo(NODE_INFO * info,CONNECTION * c)3765 void CreateNodeInfo(NODE_INFO *info, CONNECTION *c)
3766 {
3767 	SESSION *s;
3768 	OS_INFO *os;
3769 	char *product_id;
3770 	IP ip;
3771 	// Validate arguments
3772 	if (c == NULL)
3773 	{
3774 		return;
3775 	}
3776 
3777 	s = c->Session;
3778 	os = GetOsInfo();
3779 
3780 
3781 
3782 	Zero(info, sizeof(NODE_INFO));
3783 
3784 	// Client product name
3785 	StrCpy(info->ClientProductName, sizeof(info->ClientProductName), c->ClientStr);
3786 	// Client version
3787 	info->ClientProductVer = Endian32(c->ClientVer);
3788 	// Client build number
3789 	info->ClientProductBuild = Endian32(c->ClientBuild);
3790 
3791 	// Server product name
3792 	StrCpy(info->ServerProductName, sizeof(info->ServerProductName), c->ServerStr);
3793 	// Server version
3794 	info->ServerProductVer = Endian32(c->ServerVer);
3795 	// Server build number
3796 	info->ServerProductBuild = Endian32(c->ServerBuild);
3797 
3798 	// Client OS name
3799 	StrCpy(info->ClientOsName, sizeof(info->ClientOsName), os->OsProductName);
3800 	// Client OS version
3801 	StrCpy(info->ClientOsVer, sizeof(info->ClientOsVer), os->OsVersion);
3802 	// Client OS Product ID
3803 	product_id = OSGetProductId();
3804 	StrCpy(info->ClientOsProductId, sizeof(info->ClientOsProductId), product_id);
3805 	Free(product_id);
3806 
3807 	// Client host name
3808 #ifndef	OS_WIN32
3809 	GetMachineName(info->ClientHostname, sizeof(info->ClientHostname));
3810 #else	// OS_WIN32
3811 	if (true)
3812 	{
3813 		wchar_t namew[256];
3814 		char namea[256];
3815 
3816 		Zero(namew, sizeof(namew));
3817 		MsGetComputerNameFullEx(namew, sizeof(namew), true);
3818 
3819 		Zero(namea, sizeof(namea));
3820 		UniToStr(namea, sizeof(namea), namew);
3821 
3822 		if (IsEmptyStr(namea))
3823 		{
3824 			GetMachineName(namea, sizeof(namea));
3825 		}
3826 
3827 		StrCpy(info->ClientHostname, sizeof(info->ClientHostname), namea);
3828 
3829 	}
3830 #endif	// OS_WIN32
3831 	// Client IP address
3832 	if (IsIP6(&c->FirstSock->LocalIP) == false)
3833 	{
3834 		info->ClientIpAddress = IPToUINT(&c->FirstSock->LocalIP);
3835 	}
3836 	else
3837 	{
3838 		Copy(info->ClientIpAddress6, c->FirstSock->LocalIP.address, sizeof(info->ClientIpAddress6));
3839 	}
3840 	// Client port number
3841 	info->ClientPort = Endian32(c->FirstSock->LocalPort);
3842 
3843 	// Server host name
3844 	StrCpy(info->ServerHostname, sizeof(info->ServerHostname), c->ServerName);
3845 	// Server IP address
3846 	if (GetIP(&ip, info->ServerHostname))
3847 	{
3848 		if (IsIP6(&ip) == false)
3849 		{
3850 			info->ServerIpAddress = IPToUINT(&ip);
3851 		}
3852 		else
3853 		{
3854 			Copy(info->ServerIpAddress6, ip.address, sizeof(info->ServerIpAddress6));
3855 		}
3856 	}
3857 	// Server port number
3858 	info->ServerPort = Endian32(c->ServerPort);
3859 
3860 	if (s->ClientOption->ProxyType == PROXY_SOCKS || s->ClientOption->ProxyType == PROXY_HTTP)
3861 	{
3862 		// Proxy host name
3863 		StrCpy(info->ProxyHostname, sizeof(info->ProxyHostname), s->ClientOption->ProxyName);
3864 
3865 		// Proxy Server IP Address
3866 		if (IsIP6(&c->FirstSock->RemoteIP) == false)
3867 		{
3868 			info->ProxyIpAddress = IPToUINT(&c->FirstSock->RemoteIP);
3869 		}
3870 		else
3871 		{
3872 			Copy(&info->ProxyIpAddress6, c->FirstSock->RemoteIP.address, sizeof(info->ProxyIpAddress6));
3873 		}
3874 
3875 		info->ProxyPort = Endian32(c->FirstSock->RemotePort);
3876 	}
3877 
3878 	// HUB name
3879 	StrCpy(info->HubName, sizeof(info->HubName), s->ClientOption->HubName);
3880 
3881 	// Unique ID
3882 	Copy(info->UniqueId, c->Cedar->UniqueId, sizeof(info->UniqueId));
3883 }
3884 
3885 // Connect a socket additionally
ClientAdditionalConnectToServer(CONNECTION * c)3886 SOCK *ClientAdditionalConnectToServer(CONNECTION *c)
3887 {
3888 	SOCK *s;
3889 	// Validate arguments
3890 	if (c == NULL)
3891 	{
3892 		return NULL;
3893 	}
3894 
3895 	// Socket connection
3896 	s = ClientConnectGetSocket(c, true);
3897 	if (s == NULL)
3898 	{
3899 		// Connection failure
3900 		return NULL;
3901 	}
3902 
3903 	// Add the socket to the list
3904 	LockList(c->ConnectingSocks);
3905 	{
3906 		Add(c->ConnectingSocks, s);
3907 		AddRef(s->ref);
3908 	}
3909 	UnlockList(c->ConnectingSocks);
3910 
3911 	if (c->Session->Halt)
3912 	{
3913 		// Stop
3914 		Disconnect(s);
3915 		LockList(c->ConnectingSocks);
3916 		{
3917 			if (Delete(c->ConnectingSocks, s))
3918 			{
3919 				ReleaseSock(s);
3920 			}
3921 		}
3922 		UnlockList(c->ConnectingSocks);
3923 		ReleaseSock(s);
3924 		return NULL;
3925 	}
3926 
3927 	// Time-out
3928 	SetTimeout(s, CONNECTING_TIMEOUT);
3929 
3930 	// Start the SSL communication
3931 	if (StartSSLEx(s, NULL, NULL, 0, c->ServerName) == false)
3932 	{
3933 		// SSL communication failure
3934 		Disconnect(s);
3935 		LockList(c->ConnectingSocks);
3936 		{
3937 			if (Delete(c->ConnectingSocks, s))
3938 			{
3939 				ReleaseSock(s);
3940 			}
3941 		}
3942 		UnlockList(c->ConnectingSocks);
3943 		ReleaseSock(s);
3944 		return NULL;
3945 	}
3946 
3947 	// Check the certificate
3948 	if (CompareX(s->RemoteX, c->ServerX) == false)
3949 	{
3950 		// The certificate is invalid
3951 		Disconnect(s);
3952 		c->Session->SessionTimeOuted = true;
3953 	}
3954 
3955 	return s;
3956 }
3957 
3958 // Attempt to sign by the secure device
SecureSign(SECURE_SIGN * sign,UINT device_id,char * pin)3959 UINT SecureSign(SECURE_SIGN *sign, UINT device_id, char *pin)
3960 {
3961 	SECURE *sec;
3962 	X *x;
3963 	// Validate arguments
3964 	if (sign == false || pin == NULL || device_id == 0)
3965 	{
3966 		return ERR_INTERNAL_ERROR;
3967 	}
3968 
3969 	// Open the device
3970 	sec = OpenSec(device_id);
3971 	if (sec == NULL)
3972 	{
3973 		return ERR_SECURE_DEVICE_OPEN_FAILED;
3974 	}
3975 
3976 	// Open the session
3977 	if (OpenSecSession(sec, 0) == false)
3978 	{
3979 		CloseSec(sec);
3980 		return ERR_SECURE_DEVICE_OPEN_FAILED;
3981 	}
3982 
3983 	// Login
3984 	if (LoginSec(sec, pin) == false)
3985 	{
3986 		CloseSecSession(sec);
3987 		CloseSec(sec);
3988 		return ERR_SECURE_PIN_LOGIN_FAILED;
3989 	}
3990 
3991 	// Read the certificate
3992 	x = ReadSecCert(sec, sign->SecurePublicCertName);
3993 	if (x == NULL)
3994 	{
3995 		LogoutSec(sec);
3996 		CloseSecSession(sec);
3997 		CloseSec(sec);
3998 		return ERR_SECURE_NO_CERT;
3999 	}
4000 
4001 	// Sign by the private key
4002 	if (SignSec(sec, sign->SecurePrivateKeyName, sign->Signature, sign->Random, SHA1_SIZE) == false)
4003 	{
4004 		// Signing failure
4005 		FreeX(x);
4006 		LogoutSec(sec);
4007 		CloseSecSession(sec);
4008 		CloseSec(sec);
4009 		return ERR_SECURE_NO_PRIVATE_KEY;
4010 	}
4011 
4012 	// Convert the certificate to buffer
4013 	sign->ClientCert = x;
4014 
4015 	// Log out
4016 	LogoutSec(sec);
4017 
4018 	// Close the session
4019 	CloseSecSession(sec);
4020 
4021 	// Close the device
4022 	CloseSec(sec);
4023 
4024 	// Success
4025 	return ERR_NO_ERROR;
4026 }
4027 
4028 // Client connects to the server additionally
ClientAdditionalConnect(CONNECTION * c,THREAD * t)4029 bool ClientAdditionalConnect(CONNECTION *c, THREAD *t)
4030 {
4031 	SOCK *s;
4032 	PACK *p;
4033 	TCPSOCK *ts;
4034 	UINT err;
4035 	UINT direction;
4036 
4037 	// Validate arguments
4038 	if (c == NULL)
4039 	{
4040 		return false;
4041 	}
4042 
4043 	// Socket connection to the server
4044 	s = ClientAdditionalConnectToServer(c);
4045 	if (s == NULL)
4046 	{
4047 		// Failed to connect socket
4048 		return false;
4049 	}
4050 
4051 	if (c->Halt)
4052 	{
4053 		goto CLEANUP;
4054 	}
4055 
4056 	// Send a signature
4057 	Debug("Uploading Signature...\n");
4058 	if (ClientUploadSignature(s) == false)
4059 	{
4060 		goto CLEANUP;
4061 	}
4062 
4063 	if (c->Halt)
4064 	{
4065 		// Stop
4066 		goto CLEANUP;
4067 	}
4068 
4069 	// Receive a Hello packet
4070 	Debug("Downloading Hello...\n");
4071 	if (ClientDownloadHello(c, s) == false)
4072 	{
4073 		goto CLEANUP;
4074 	}
4075 
4076 	if (c->Halt)
4077 	{
4078 		// Stop
4079 		goto CLEANUP;
4080 	}
4081 
4082 	// Send a authentication data for the additional connection
4083 	if (ClientUploadAuth2(c, s) == false)
4084 	{
4085 		// Disconnected
4086 		goto CLEANUP;
4087 	}
4088 
4089 	// Receive a response
4090 	p = HttpClientRecv(s);
4091 	if (p == NULL)
4092 	{
4093 		// Disconnected
4094 		goto CLEANUP;
4095 	}
4096 
4097 	err = GetErrorFromPack(p);
4098 	direction = PackGetInt(p, "direction");
4099 
4100 	FreePack(p);
4101 	p = NULL;
4102 
4103 	if (err != 0)
4104 	{
4105 		// Error has occurred
4106 		Debug("Additional Connect Error: %u\n", err);
4107 		if (err == ERR_SESSION_TIMEOUT || err == ERR_INVALID_PROTOCOL)
4108 		{
4109 			// We shall re-connection because it is a fatal error
4110 			c->Session->SessionTimeOuted = true;
4111 		}
4112 		goto CLEANUP;
4113 	}
4114 
4115 	Debug("Additional Connect Succeed!\n");
4116 
4117 	if (s->IsRUDPSocket && s->BulkRecvKey != NULL && s->BulkSendKey != NULL)
4118 	{
4119 		// Restore R-UDP bulk send/recv keys for additional connections
4120 		if (c->Session->BulkRecvKeySize != 0 && c->Session->BulkSendKeySize != 0)
4121 		{
4122 			Copy(s->BulkRecvKey->Data, c->Session->BulkRecvKey, c->Session->BulkRecvKeySize);
4123 			s->BulkRecvKey->Size = c->Session->BulkRecvKeySize;
4124 
4125 			Copy(s->BulkSendKey->Data, c->Session->BulkSendKey, c->Session->BulkSendKeySize);
4126 			s->BulkSendKey->Size = c->Session->BulkSendKeySize;
4127 		}
4128 	}
4129 
4130 	// Success the additional connection
4131 	// Add to the TcpSockList of the connection
4132 	ts = NewTcpSock(s);
4133 
4134 	if (c->ServerMode == false)
4135 	{
4136 		if (c->Session->ClientOption->ConnectionDisconnectSpan != 0)
4137 		{
4138 			ts->DisconnectTick = Tick64() + c->Session->ClientOption->ConnectionDisconnectSpan * (UINT64)1000;
4139 		}
4140 	}
4141 
4142 	LockList(c->Tcp->TcpSockList);
4143 	{
4144 		ts->Direction = direction;
4145 		Add(c->Tcp->TcpSockList, ts);
4146 	}
4147 	UnlockList(c->Tcp->TcpSockList);
4148 	Debug("TCP Connection Incremented: %u\n", Count(c->CurrentNumConnection));
4149 
4150 	if (c->Session->HalfConnection)
4151 	{
4152 		Debug("New Half Connection: %s\n",
4153 			direction == TCP_SERVER_TO_CLIENT ? "TCP_SERVER_TO_CLIENT" : "TCP_CLIENT_TO_SERVER"
4154 			);
4155 	}
4156 
4157 	// Issue the Cancel to the session
4158 	Cancel(c->Session->Cancel1);
4159 
4160 	// Remove the socket from the socket list of connected
4161 	LockList(c->ConnectingSocks);
4162 	{
4163 		if (Delete(c->ConnectingSocks, s))
4164 		{
4165 			ReleaseSock(s);
4166 		}
4167 	}
4168 	UnlockList(c->ConnectingSocks);
4169 	ReleaseSock(s);
4170 	return true;
4171 
4172 CLEANUP:
4173 	// Disconnection process
4174 	Disconnect(s);
4175 	LockList(c->ConnectingSocks);
4176 	{
4177 		if (Delete(c->ConnectingSocks, s))
4178 		{
4179 			ReleaseSock(s);
4180 
4181 		}
4182 	}
4183 	UnlockList(c->ConnectingSocks);
4184 	ReleaseSock(s);
4185 	return false;
4186 }
4187 
4188 // Secure device signing thread
ClientSecureSignThread(THREAD * thread,void * param)4189 void ClientSecureSignThread(THREAD *thread, void *param)
4190 {
4191 	SECURE_SIGN_THREAD_PROC *p = (SECURE_SIGN_THREAD_PROC *)param;
4192 	// Validate arguments
4193 	if (thread == NULL || param == NULL)
4194 	{
4195 		return;
4196 	}
4197 
4198 	NoticeThreadInit(thread);
4199 
4200 	p->Ok = p->SecureSignProc(p->Connection->Session, p->Connection, p->SecureSign);
4201 	p->UserFinished = true;
4202 }
4203 
4204 // Signing with the secure device
ClientSecureSign(CONNECTION * c,UCHAR * sign,UCHAR * random,X ** x)4205 bool ClientSecureSign(CONNECTION *c, UCHAR *sign, UCHAR *random, X **x)
4206 {
4207 	SECURE_SIGN_THREAD_PROC *p;
4208 	SECURE_SIGN *ss;
4209 	SESSION *s;
4210 	CLIENT_OPTION *o;
4211 	CLIENT_AUTH *a;
4212 	THREAD *thread;
4213 	UINT64 start;
4214 	bool ret;
4215 	// Validate arguments
4216 	if (c == NULL || sign == NULL || random == NULL || x == NULL)
4217 	{
4218 		return false;
4219 	}
4220 
4221 	s = c->Session;
4222 	o = s->ClientOption;
4223 	a = s->ClientAuth;
4224 
4225 	p = ZeroMalloc(sizeof(SECURE_SIGN_THREAD_PROC));
4226 	p->Connection = c;
4227 	ss = p->SecureSign = ZeroMallocEx(sizeof(SECURE_SIGN), true);
4228 	StrCpy(ss->SecurePrivateKeyName, sizeof(ss->SecurePrivateKeyName),
4229 		a->SecurePrivateKeyName);
4230 	StrCpy(ss->SecurePublicCertName, sizeof(ss->SecurePublicCertName),
4231 		a->SecurePublicCertName);
4232 	ss->UseSecureDeviceId = c->Cedar->Client->UseSecureDeviceId;
4233 	Copy(ss->Random, random, SHA1_SIZE);
4234 
4235 #ifdef	OS_WIN32
4236 	ss->BitmapId = CmGetSecureBitmapId(c->ServerName);
4237 #endif	// OS_WIN32
4238 
4239 	p->SecureSignProc = a->SecureSignProc;
4240 
4241 	// Create a thread
4242 	thread = NewThread(ClientSecureSignThread, p);
4243 	WaitThreadInit(thread);
4244 
4245 	// Poll every 0.5 seconds until signing is completed or canceled
4246 	start = Tick64();
4247 	while (true)
4248 	{
4249 		if ((Tick64() - start) > CONNECTING_POOLING_SPAN)
4250 		{
4251 			// Send a NOOP periodically for disconnection prevention
4252 			start = Tick64();
4253 			ClientUploadNoop(c);
4254 		}
4255 		if (p->UserFinished)
4256 		{
4257 			// User selected
4258 			break;
4259 		}
4260 		WaitThread(thread, 500);
4261 	}
4262 	ReleaseThread(thread);
4263 
4264 	ret = p->Ok;
4265 
4266 	if (ret)
4267 	{
4268 		Copy(sign, ss->Signature, sizeof(ss->Signature));
4269 		*x = ss->ClientCert;
4270 	}
4271 
4272 	Free(p->SecureSign);
4273 	Free(p);
4274 
4275 	return ret;
4276 }
4277 
4278 // Server certificate confirmation thread
ClientCheckServerCertThread(THREAD * thread,void * param)4279 void ClientCheckServerCertThread(THREAD *thread, void *param)
4280 {
4281 	CHECK_CERT_THREAD_PROC *p = (CHECK_CERT_THREAD_PROC *)param;
4282 	// Validate arguments
4283 	if (thread == NULL || param == NULL)
4284 	{
4285 		return;
4286 	}
4287 
4288 	// Notify the completion of initialization
4289 	NoticeThreadInit(thread);
4290 
4291 	// Query for the selection to the user
4292 	p->Ok = p->CheckCertProc(p->Connection->Session, p->Connection, p->ServerX, &p->Expired);
4293 	p->UserSelected = true;
4294 }
4295 
4296 // Client verify the certificate of the server
ClientCheckServerCert(CONNECTION * c,bool * expired)4297 bool ClientCheckServerCert(CONNECTION *c, bool *expired)
4298 {
4299 	CLIENT_AUTH *auth;
4300 	X *x;
4301 	CHECK_CERT_THREAD_PROC *p;
4302 	THREAD *thread;
4303 	CEDAR *cedar;
4304 	bool ret;
4305 	UINT64 start;
4306 	// Validate arguments
4307 	if (c == NULL)
4308 	{
4309 		return false;
4310 	}
4311 
4312 	if (expired != NULL)
4313 	{
4314 		*expired = false;
4315 	}
4316 
4317 	auth = c->Session->ClientAuth;
4318 	cedar = c->Cedar;
4319 
4320 	if (auth->CheckCertProc == NULL && c->Session->LinkModeClient == false)
4321 	{
4322 		// No checking function
4323 		return true;
4324 	}
4325 
4326 	if (c->Session->LinkModeClient && c->Session->Link->CheckServerCert == false)
4327 	{
4328 		// It's in cascade connection mode, but do not check the server certificate
4329 		return true;
4330 	}
4331 
4332 	if (c->UseTicket)
4333 	{
4334 		// Check the certificate of the redirected VPN server
4335 		if (CompareX(c->FirstSock->RemoteX, c->ServerX) == false)
4336 		{
4337 			return false;
4338 		}
4339 		else
4340 		{
4341 			return true;
4342 		}
4343 	}
4344 
4345 	x = CloneX(c->FirstSock->RemoteX);
4346 	if (x == NULL)
4347 	{
4348 		// Strange error occurs
4349 		return false;
4350 	}
4351 
4352 	if (CheckXDateNow(x))
4353 	{
4354 		// Check whether it is signed by the root certificate to trust
4355 		if (c->Session->LinkModeClient == false)
4356 		{
4357 			// Normal VPN Client mode
4358 			if (CheckSignatureByCa(cedar, x))
4359 			{
4360 				// This certificate can be trusted because it is signed
4361 				FreeX(x);
4362 				return true;
4363 			}
4364 		}
4365 		else
4366 		{
4367 			// Cascade connection mode
4368 			if (CheckSignatureByCaLinkMode(c->Session, x))
4369 			{
4370 				// This certificate can be trusted because it is signed
4371 				FreeX(x);
4372 				return true;
4373 			}
4374 		}
4375 	}
4376 
4377 	if (c->Session->LinkModeClient)
4378 	{
4379 		if (CheckXDateNow(x))
4380 		{
4381 			Lock(c->Session->Link->lock);
4382 			{
4383 				if (c->Session->Link->ServerCert != NULL)
4384 				{
4385 					if (CompareX(c->Session->Link->ServerCert, x))
4386 					{
4387 						Unlock(c->Session->Link->lock);
4388 						// Exactly match the certificate that is registered in the cascade configuration
4389 						FreeX(x);
4390 						return true;
4391 					}
4392 				}
4393 			}
4394 			Unlock(c->Session->Link->lock);
4395 		}
4396 		else
4397 		{
4398 			if (expired != NULL)
4399 			{
4400 				*expired = true;
4401 			}
4402 		}
4403 
4404 		// Verification failure at this point in the case of cascade connection mode
4405 		FreeX(x);
4406 		return false;
4407 	}
4408 
4409 	p = ZeroMalloc(sizeof(CHECK_CERT_THREAD_PROC));
4410 	p->ServerX = x;
4411 	p->CheckCertProc = auth->CheckCertProc;
4412 	p->Connection = c;
4413 
4414 	// Create a thread
4415 	thread = NewThread(ClientCheckServerCertThread, p);
4416 	WaitThreadInit(thread);
4417 
4418 	// Poll at 0.5-second intervals until the user selects whether the connection
4419 	start = Tick64();
4420 	while (true)
4421 	{
4422 		if ((Tick64() - start) > CONNECTING_POOLING_SPAN)
4423 		{
4424 			// Send a NOOP periodically for disconnection prevention
4425 			start = Tick64();
4426 			ClientUploadNoop(c);
4427 		}
4428 		if (p->UserSelected)
4429 		{
4430 			// User-selected
4431 			break;
4432 		}
4433 		WaitThread(thread, 500);
4434 	}
4435 
4436 	if (expired != NULL)
4437 	{
4438 		*expired = p->Expired;
4439 	}
4440 
4441 	ret = p->Ok;
4442 	FreeX(p->ServerX);
4443 	Free(p);
4444 	ReleaseThread(thread);
4445 
4446 	return ret;
4447 }
4448 
4449 // Client connects to the server
ClientConnect(CONNECTION * c)4450 bool ClientConnect(CONNECTION *c)
4451 {
4452 	bool ret = false;
4453 	bool ok = false;
4454 	UINT err;
4455 	SOCK *s;
4456 	PACK *p = NULL;
4457 	UINT session_key_32;
4458 	SESSION *sess;
4459 	char session_name[MAX_SESSION_NAME_LEN + 1];
4460 	char connection_name[MAX_CONNECTION_NAME_LEN + 1];
4461 	UCHAR session_key[SHA1_SIZE];
4462 	POLICY *policy;
4463 	bool expired = false;
4464 	IP server_ip;
4465 	// Validate arguments
4466 	if (c == NULL)
4467 	{
4468 		return false;
4469 	}
4470 
4471 	sess = c->Session;
4472 
4473 	PrintStatus(sess, L"init");
4474 	PrintStatus(sess, _UU("STATUS_1"));
4475 
4476 REDIRECTED:
4477 
4478 	// [Connecting]
4479 	c->Status = CONNECTION_STATUS_CONNECTING;
4480 	c->Session->ClientStatus = CLIENT_STATUS_CONNECTING;
4481 
4482 	s = ClientConnectToServer(c);
4483 	if (s == NULL)
4484 	{
4485 		PrintStatus(sess, L"free");
4486 		return false;
4487 	}
4488 
4489 	Copy(&server_ip, &s->RemoteIP, sizeof(IP));
4490 
4491 	if (c->Halt)
4492 	{
4493 		// Stop
4494 		c->Err = ERR_USER_CANCEL;
4495 		goto CLEANUP;
4496 	}
4497 
4498 	// [Negotiating]
4499 	c->Session->ClientStatus = CLIENT_STATUS_NEGOTIATION;
4500 
4501 	// Initialize the UDP acceleration function
4502 	if (sess->ClientOption != NULL && sess->ClientOption->NoUdpAcceleration == false)
4503 	{
4504 		if (sess->ClientOption->ProxyType == PROXY_DIRECT)
4505 		{
4506 			if (s->Type == SOCK_TCP)
4507 			{
4508 				if (sess->UdpAccel == NULL)
4509 				{
4510 					bool no_nat_t = false;
4511 
4512 					if (sess->ClientOption->PortUDP != 0)
4513 					{
4514 						// There is no need for NAT-T treatment on my part if the UDP port on the other end is known beforehand
4515 						no_nat_t = true;
4516 					}
4517 
4518 
4519 					sess->UdpAccel = NewUdpAccel(c->Cedar, &s->LocalIP, true, true, no_nat_t);
4520 				}
4521 			}
4522 		}
4523 	}
4524 
4525 	// Send a signature
4526 	Debug("Uploading Signature...\n");
4527 	if (ClientUploadSignature(s) == false)
4528 	{
4529 		c->Err = ERR_DISCONNECTED;
4530 		goto CLEANUP;
4531 	}
4532 
4533 	if (c->Halt)
4534 	{
4535 		// Stop
4536 		c->Err = ERR_USER_CANCEL;
4537 		goto CLEANUP;
4538 	}
4539 
4540 	PrintStatus(sess, _UU("STATUS_5"));
4541 
4542 	// Receive a Hello packet
4543 	Debug("Downloading Hello...\n");
4544 	if (ClientDownloadHello(c, s) == false)
4545 	{
4546 		goto CLEANUP;
4547 	}
4548 
4549 	if (c->Session->ClientOption != NULL && c->Session->ClientOption->FromAdminPack)
4550 	{
4551 		if (IsAdminPackSupportedServerProduct(c->ServerStr) == false)
4552 		{
4553 			c->Err = ERR_NOT_ADMINPACK_SERVER;
4554 			goto CLEANUP;
4555 		}
4556 	}
4557 
4558 	if (c->Halt)
4559 	{
4560 		// Stop
4561 		c->Err = ERR_USER_CANCEL;
4562 		goto CLEANUP;
4563 	}
4564 
4565 	Debug("Server Version : %u\n"
4566 		"Server String  : %s\n"
4567 		"Server Build   : %u\n"
4568 		"Client Version : %u\n"
4569 		"Client String  : %s\n"
4570 		"Client Build   : %u\n",
4571 		c->ServerVer, c->ServerStr, c->ServerBuild,
4572 		c->ClientVer, c->ClientStr, c->ClientBuild);
4573 
4574 	// During user authentication
4575 	c->Session->ClientStatus = CLIENT_STATUS_AUTH;
4576 
4577 	// Verify the server certificate by the client
4578 	if (ClientCheckServerCert(c, &expired) == false)
4579 	{
4580 		if (expired == false)
4581 		{
4582 			c->Err = ERR_CERT_NOT_TRUSTED;
4583 		}
4584 		else
4585 		{
4586 			c->Err = ERR_SERVER_CERT_EXPIRES;
4587 		}
4588 
4589 		if (c->Session->LinkModeClient == false && c->Err == ERR_CERT_NOT_TRUSTED
4590 			&& (c->Session->Account == NULL || ! c->Session->Account->RetryOnServerCert))
4591 		{
4592 			c->Session->ForceStopFlag = true;
4593 		}
4594 
4595 		goto CLEANUP;
4596 	}
4597 
4598 	PrintStatus(sess, _UU("STATUS_6"));
4599 
4600 	// Send the authentication data
4601 	if (ClientUploadAuth(c) == false)
4602 	{
4603 		goto CLEANUP;
4604 	}
4605 
4606 	if (c->Halt)
4607 	{
4608 		// Stop
4609 		c->Err = ERR_USER_CANCEL;
4610 		goto CLEANUP;
4611 	}
4612 
4613 	// Receive a Welcome packet
4614 	p = HttpClientRecv(s);
4615 	if (p == NULL)
4616 	{
4617 		c->Err = ERR_DISCONNECTED;
4618 		goto CLEANUP;
4619 	}
4620 
4621 	// Error checking
4622 	err = GetErrorFromPack(p);
4623 	if (err != 0)
4624 	{
4625 		// An error has occured
4626 		c->Err = err;
4627 		c->ClientConnectError_NoSavePassword = PackGetBool(p, "no_save_password");
4628 		goto CLEANUP;
4629 	}
4630 
4631 	// Branding string check for the connection limit
4632 	{
4633 		char tmp[20];
4634 		char *branded_cfroms = _SS("BRANDED_C_FROM_S");
4635 		PackGetStr(p, "branded_cfroms", tmp, sizeof(tmp));
4636 
4637 		if(StrLen(branded_cfroms) > 0 && StrCmpi(branded_cfroms, tmp) != 0)
4638 		{
4639 			c->Err = ERR_BRANDED_C_FROM_S;
4640 			goto CLEANUP;
4641 		}
4642 	}
4643 
4644 	if (c->Cedar->Server == NULL)
4645 	{
4646 		// Suppress client notification flag
4647 		if (PackIsValueExists(p, "suppress_client_update_notification"))
4648 		{
4649 			bool suppress_client_update_notification = PackGetBool(p, "suppress_client_update_notification");
4650 
4651 #ifdef	OS_WIN32
4652 			MsRegWriteIntEx2(REG_LOCAL_MACHINE, PROTO_SUPPRESS_CLIENT_UPDATE_NOTIFICATION_REGKEY, PROTO_SUPPRESS_CLIENT_UPDATE_NOTIFICATION_REGVALUE,
4653 				(suppress_client_update_notification ? 1 : 0), false, true);
4654 #endif	// OS_WIN32
4655 		}
4656 	}
4657 
4658 	if (true)
4659 	{
4660 		// Message retrieval
4661 		UINT utf_size;
4662 		char *utf;
4663 		wchar_t *msg;
4664 
4665 		utf_size = PackGetDataSize(p, "Msg");
4666 		utf = ZeroMalloc(utf_size + 8);
4667 		PackGetData(p, "Msg", utf);
4668 
4669 		msg = CopyUtfToUni(utf);
4670 
4671 		if (IsEmptyUniStr(msg) == false)
4672 		{
4673 			if (c->Session->Client_Message != NULL)
4674 			{
4675 				Free(c->Session->Client_Message);
4676 			}
4677 
4678 			c->Session->Client_Message = msg;
4679 		}
4680 		else
4681 		{
4682 			Free(msg);
4683 		}
4684 
4685 		Free(utf);
4686 	}
4687 
4688 	if (PackGetInt(p, "Redirect") != 0)
4689 	{
4690 		UINT i;
4691 		UINT ip;
4692 		UINT num_port;
4693 		UINT *ports;
4694 		UINT use_port = 0;
4695 		UINT current_port = c->ServerPort;
4696 		UCHAR ticket[SHA1_SIZE];
4697 		X *server_cert = NULL;
4698 		BUF *b;
4699 
4700 		// Redirect mode
4701 		PrintStatus(sess, _UU("STATUS_8"));
4702 
4703 		ip = PackGetIp32(p, "Ip");
4704 		num_port = MAX(MIN(PackGetIndexCount(p, "Port"), MAX_PUBLIC_PORT_NUM), 1);
4705 		ports = ZeroMalloc(sizeof(UINT) * num_port);
4706 		for (i = 0;i < num_port;i++)
4707 		{
4708 			ports[i] = PackGetIntEx(p, "Port", i);
4709 		}
4710 
4711 		// Select a port number
4712 		for (i = 0;i < num_port;i++)
4713 		{
4714 			if (ports[i] == current_port)
4715 			{
4716 				use_port = current_port;
4717 			}
4718 		}
4719 		if (use_port == 0)
4720 		{
4721 			use_port = ports[0];
4722 		}
4723 
4724 		Free(ports);
4725 
4726 		if (PackGetDataSize(p, "Ticket") == SHA1_SIZE)
4727 		{
4728 			PackGetData(p, "Ticket", ticket);
4729 		}
4730 
4731 		b = PackGetBuf(p, "Cert");
4732 		if (b != NULL)
4733 		{
4734 			server_cert = BufToX(b, false);
4735 			FreeBuf(b);
4736 		}
4737 
4738 		if (c->ServerX != NULL)
4739 		{
4740 			FreeX(c->ServerX);
4741 		}
4742 		c->ServerX = server_cert;
4743 
4744 		IPToStr32(c->ServerName, sizeof(c->ServerName), ip);
4745 		c->ServerPort = use_port;
4746 
4747 		c->UseTicket = true;
4748 		Copy(c->Ticket, ticket, SHA1_SIZE);
4749 
4750 		FreePack(p);
4751 
4752 		p = NewPack();
4753 		HttpClientSend(s, p);
4754 		FreePack(p);
4755 
4756 		p = NULL;
4757 
4758 		c->FirstSock = NULL;
4759 		Disconnect(s);
4760 		ReleaseSock(s);
4761 		s = NULL;
4762 
4763 		goto REDIRECTED;
4764 	}
4765 
4766 	PrintStatus(sess, _UU("STATUS_7"));
4767 
4768 	// Parse the Welcome packet
4769 	if (ParseWelcomeFromPack(p, session_name, sizeof(session_name),
4770 		connection_name, sizeof(connection_name), &policy) == false)
4771 	{
4772 		// Parsing failure
4773 		c->Err = ERR_PROTOCOL_ERROR;
4774 		goto CLEANUP;
4775 	}
4776 
4777 	// Get the session key
4778 	if (GetSessionKeyFromPack(p, session_key, &session_key_32) == false)
4779 	{
4780 		// Acquisition failure
4781 		Free(policy);
4782 		policy = NULL;
4783 		c->Err = ERR_PROTOCOL_ERROR;
4784 		goto CLEANUP;
4785 	}
4786 
4787 	Copy(c->Session->SessionKey, session_key, SHA1_SIZE);
4788 	c->Session->SessionKey32 = session_key_32;
4789 
4790 	// Save the contents of the Welcome packet
4791 	Debug("session_name: %s, connection_name: %s\n",
4792 		session_name, connection_name);
4793 
4794 	Lock(c->Session->lock);
4795 	{
4796 		// Deploy and update connection parameters
4797 		sess->EnableUdpRecovery = PackGetBool(p, "enable_udp_recovery");
4798 		c->Session->MaxConnection = PackGetInt(p, "max_connection");
4799 
4800 		if (sess->EnableUdpRecovery == false)
4801 		{
4802 			c->Session->MaxConnection = MIN(c->Session->MaxConnection, c->Session->ClientOption->MaxConnection);
4803 		}
4804 
4805 		c->Session->MaxConnection = MIN(c->Session->MaxConnection, MAX_TCP_CONNECTION);
4806 		c->Session->MaxConnection = MAX(c->Session->MaxConnection, 1);
4807 		c->Session->UseCompress = PackGetInt(p, "use_compress") == 0 ? false : true;
4808 		c->Session->UseEncrypt = PackGetInt(p, "use_encrypt") == 0 ? false : true;
4809 		c->Session->NoSendSignature = PackGetBool(p, "no_send_signature");
4810 		c->Session->HalfConnection = PackGetInt(p, "half_connection") == 0 ? false : true;
4811 		c->Session->IsAzureSession = PackGetInt(p, "is_azure_session") == 0 ? false : true;
4812 		c->Session->Timeout = PackGetInt(p, "timeout");
4813 		c->Session->QoS = PackGetInt(p, "qos") == 0 ? false : true;
4814 		if (c->Session->QoS)
4815 		{
4816 			c->Session->MaxConnection = MAX(c->Session->MaxConnection, (UINT)(c->Session->HalfConnection ? 4 : 2));
4817 		}
4818 		c->Session->VLanId = PackGetInt(p, "vlan_id");
4819 
4820 		// R-UDP Session ?
4821 		c->Session->IsRUDPSession = s->IsRUDPSocket;
4822 
4823 		ZeroIP4(&c->Session->AzureRealServerGlobalIp);
4824 
4825 		if (c->Session->IsAzureSession)
4826 		{
4827 			// Disable the life parameter of the connection in the case of VPN Azure relayed session
4828 			c->Session->ClientOption->ConnectionDisconnectSpan = 0;
4829 
4830 			// Get the AzureRealServerGlobalIp the case of VPN Azure relayed
4831 			PackGetIp(p, "azure_real_server_global_ip", &c->Session->AzureRealServerGlobalIp);
4832 		}
4833 
4834 		if (c->Session->IsRUDPSession)
4835 		{
4836 			// Disable the life parameter of the connection in the case of R-UDP session
4837 			c->Session->ClientOption->ConnectionDisconnectSpan = 0;
4838 
4839 			// Disable QoS, etc. in the case of R-UDP session
4840 			c->Session->QoS = false;
4841 			c->Session->HalfConnection = false;
4842 
4843 			if (c->Session->EnableUdpRecovery == false)
4844 			{
4845 				// Set the number of connection to 1 if UDP recovery is not supported
4846 				c->Session->MaxConnection = 1;
4847 			}
4848 		}
4849 
4850 		// Physical communication protocol
4851 		StrCpy(c->Session->UnderlayProtocol, sizeof(c->Session->UnderlayProtocol), s->UnderlayProtocol);
4852 
4853 		AddProtocolDetailsStr(c->Session->ProtocolDetails, sizeof(c->Session->ProtocolDetails), s->ProtocolDetails);
4854 
4855 		if (c->Session->IsAzureSession)
4856 		{
4857 			StrCpy(c->Session->UnderlayProtocol, sizeof(c->Session->UnderlayProtocol), SOCK_UNDERLAY_AZURE);
4858 
4859 			AddProtocolDetailsStr(c->Session->ProtocolDetails, sizeof(c->Session->ProtocolDetails), "VPN Azure");
4860 		}
4861 
4862 		if (c->Protocol == CONNECTION_UDP)
4863 		{
4864 			// In the case of UDP protocol, receive the key from the server
4865 			if (PackGetDataSize(p, "udp_send_key") == sizeof(c->Session->UdpSendKey))
4866 			{
4867 				PackGetData(p, "udp_send_key", c->Session->UdpSendKey);
4868 			}
4869 
4870 			if (PackGetDataSize(p, "udp_recv_key") == sizeof(c->Session->UdpRecvKey))
4871 			{
4872 				PackGetData(p, "udp_recv_key", c->Session->UdpRecvKey);
4873 			}
4874 		}
4875 
4876 		sess->EnableBulkOnRUDP = false;
4877 		sess->EnableHMacOnBulkOfRUDP = false;
4878 		if (s != NULL && s->IsRUDPSocket && s->BulkRecvKey != NULL && s->BulkSendKey != NULL)
4879 		{
4880 			// Bulk transfer on R-UDP
4881 			sess->EnableHMacOnBulkOfRUDP = PackGetBool(p, "enable_hmac_on_bulk_of_rudp");
4882 			sess->BulkOnRUDPVersion = PackGetInt(p, "rudp_bulk_version");
4883 
4884 			if (PackGetBool(p, "enable_bulk_on_rudp"))
4885 			{
4886 				// Receive the key
4887 				UCHAR key_send[RUDP_BULK_KEY_SIZE_MAX];
4888 				UCHAR key_recv[RUDP_BULK_KEY_SIZE_MAX];
4889 
4890 				UINT key_size = SHA1_SIZE;
4891 
4892 				if (sess->BulkOnRUDPVersion == 2)
4893 				{
4894 					key_size = RUDP_BULK_KEY_SIZE_V2;
4895 				}
4896 
4897 				if (PackGetData2(p, "bulk_on_rudp_send_key", key_send, key_size) &&
4898 					PackGetData2(p, "bulk_on_rudp_recv_key", key_recv, key_size))
4899 				{
4900 					sess->EnableBulkOnRUDP = true;
4901 
4902 					Copy(s->BulkSendKey->Data, key_send, key_size);
4903 					Copy(s->BulkRecvKey->Data, key_recv, key_size);
4904 
4905 					s->BulkSendKey->Size = key_size;
4906 					s->BulkRecvKey->Size = key_size;
4907 
4908 					// Backup R-UDP bulk send/recv keys for additional connections
4909 					Copy(sess->BulkSendKey, s->BulkSendKey->Data, s->BulkSendKey->Size);
4910 					sess->BulkSendKeySize = s->BulkSendKey->Size;
4911 
4912 					Copy(sess->BulkRecvKey, s->BulkRecvKey->Data, s->BulkRecvKey->Size);
4913 					sess->BulkRecvKeySize = s->BulkRecvKey->Size;
4914 
4915 					AddProtocolDetailsKeyValueInt(sess->ProtocolDetails, sizeof(sess->ProtocolDetails), "RUDP_Bulk_Ver", sess->BulkOnRUDPVersion);
4916 				}
4917 			}
4918 
4919 			sess->EnableHMacOnBulkOfRUDP = PackGetBool(p, "enable_hmac_on_bulk_of_rudp");
4920 		}
4921 
4922 		Debug("EnableBulkOnRUDP = %u\n", sess->EnableBulkOnRUDP);
4923 		Debug("EnableHMacOnBulkOfRUDP = %u\n", sess->EnableHMacOnBulkOfRUDP);
4924 		Debug("EnableUdpRecovery = %u\n", sess->EnableUdpRecovery);
4925 		Debug("BulkOnRUDPVersion = %u\n", sess->BulkOnRUDPVersion);
4926 
4927 		sess->UseUdpAcceleration = false;
4928 		sess->IsUsingUdpAcceleration = false;
4929 		sess->UseHMacOnUdpAcceleration = false;
4930 
4931 		if (sess->UdpAccel != NULL)
4932 		{
4933 			sess->UdpAccel->UseHMac = false;
4934 
4935 			sess->UdpAccelFastDisconnectDetect = false;
4936 
4937 			if (PackGetBool(p, "use_udp_acceleration"))
4938 			{
4939 				UINT udp_acceleration_version = PackGetInt(p, "udp_acceleration_version");
4940 				IP udp_acceleration_server_ip;
4941 
4942 				if (udp_acceleration_version == 0)
4943 				{
4944 					udp_acceleration_version = 1;
4945 				}
4946 
4947 				sess->UdpAccelFastDisconnectDetect = PackGetBool(p, "udp_accel_fast_disconnect_detect");
4948 
4949 				if (PackGetIp(p, "udp_acceleration_server_ip", &udp_acceleration_server_ip))
4950 				{
4951 					UINT udp_acceleration_server_port = PackGetInt(p, "udp_acceleration_server_port");
4952 
4953 					if (IsZeroIp(&udp_acceleration_server_ip))
4954 					{
4955 						Copy(&udp_acceleration_server_ip, &s->RemoteIP, sizeof(IP));
4956 					}
4957 
4958 					if (udp_acceleration_server_port != 0)
4959 					{
4960 						UCHAR udp_acceleration_server_key[UDP_ACCELERATION_COMMON_KEY_SIZE_V1];
4961 						UCHAR udp_acceleration_server_key_v2[UDP_ACCELERATION_COMMON_KEY_SIZE_V2];
4962 						UINT server_cookie = PackGetInt(p, "udp_acceleration_server_cookie");
4963 						UINT client_cookie = PackGetInt(p, "udp_acceleration_client_cookie");
4964 						bool encryption = PackGetBool(p, "udp_acceleration_use_encryption");
4965 
4966 						Zero(udp_acceleration_server_key, sizeof(udp_acceleration_server_key));
4967 						Zero(udp_acceleration_server_key_v2, sizeof(udp_acceleration_server_key_v2));
4968 
4969 						PackGetData2(p, "udp_acceleration_server_key", udp_acceleration_server_key, UDP_ACCELERATION_COMMON_KEY_SIZE_V1);
4970 						PackGetData2(p, "udp_acceleration_server_key_v2", udp_acceleration_server_key_v2, UDP_ACCELERATION_COMMON_KEY_SIZE_V2);
4971 
4972 						if (server_cookie != 0 && client_cookie != 0)
4973 						{
4974 							IP remote_ip;
4975 
4976 							Copy(&remote_ip, &s->RemoteIP, sizeof(IP));
4977 
4978 							if (IsZeroIp(&c->Session->AzureRealServerGlobalIp) == false)
4979 							{
4980 								Copy(&remote_ip, &c->Session->AzureRealServerGlobalIp, sizeof(IP));
4981 							}
4982 
4983 							sess->UdpAccel->Version = 1;
4984 							if (udp_acceleration_version == 2)
4985 							{
4986 								sess->UdpAccel->Version = 2;
4987 							}
4988 
4989 							if (UdpAccelInitClient(sess->UdpAccel,
4990 								sess->UdpAccel->Version == 2 ? udp_acceleration_server_key_v2 : udp_acceleration_server_key,
4991 								&remote_ip, &udp_acceleration_server_ip, udp_acceleration_server_port,
4992 								server_cookie, client_cookie) == false)
4993 							{
4994 								Debug("UdpAccelInitClient failed.\n");
4995 							}
4996 							else
4997 							{
4998 								sess->UseUdpAcceleration = true;
4999 
5000 								sess->UdpAccel->FastDetect = sess->UdpAccelFastDisconnectDetect;
5001 
5002 								sess->UdpAccel->PlainTextMode = !encryption;
5003 
5004 								sess->UseHMacOnUdpAcceleration = PackGetBool(p, "use_hmac_on_udp_acceleration");
5005 
5006 								if (sess->UseHMacOnUdpAcceleration)
5007 								{
5008 									sess->UdpAccel->UseHMac = true;
5009 								}
5010 
5011 								AddProtocolDetailsKeyValueInt(sess->ProtocolDetails, sizeof(sess->ProtocolDetails), "UDPAccel_Ver", sess->UdpAccel->Version);
5012 
5013 								AddProtocolDetailsStr(sess->ProtocolDetails, sizeof(sess->ProtocolDetails), sess->UdpAccel->Version > 1 ? "ChaCha20-Poly1305" : "RC4");
5014 
5015 								AddProtocolDetailsKeyValueInt(sess->ProtocolDetails, sizeof(sess->ProtocolDetails), "UDPAccel_MSS", UdpAccelCalcMss(sess->UdpAccel));
5016 							}
5017 						}
5018 					}
5019 				}
5020 			}
5021 		}
5022 	}
5023 	Unlock(c->Session->lock);
5024 
5025 	Debug("UseUdpAcceleration = %u\n", sess->UseUdpAcceleration);
5026 
5027 	if (sess->UseUdpAcceleration == false)
5028 	{
5029 		if (sess->UdpAccel != NULL)
5030 		{
5031 			FreeUdpAccel(sess->UdpAccel);
5032 			sess->UdpAccel = NULL;
5033 		}
5034 	}
5035 
5036 	Lock(c->lock);
5037 	{
5038 		if (c->Name != NULL)
5039 		{
5040 			Free(c->Name);
5041 		}
5042 		c->Name = CopyStr(connection_name);
5043 
5044 		// Save the name of a cryptographic algorithm
5045 		if (c->CipherName != NULL)
5046 		{
5047 			Free(c->CipherName);
5048 		}
5049 
5050 		c->CipherName = CopyStr(c->FirstSock->CipherName);
5051 	}
5052 	Unlock(c->lock);
5053 
5054 	Lock(c->Session->lock);
5055 	{
5056 		if (c->Session->Name != NULL)
5057 		{
5058 			Free(c->Session->Name);
5059 		}
5060 		c->Session->Name = CopyStr(session_name);
5061 
5062 		c->Session->Policy = policy;
5063 	}
5064 	Unlock(c->Session->lock);
5065 
5066 	// Discard the Welcome packet
5067 	FreePack(p);
5068 	p = NULL;
5069 
5070 
5071 	// Connection establishment
5072 	c->Session->ClientStatus = CLIENT_STATUS_ESTABLISHED;
5073 
5074 	// Save the server certificate
5075 	if (c->ServerX == NULL)
5076 	{
5077 		c->ServerX = CloneX(c->FirstSock->RemoteX);
5078 	}
5079 
5080 	PrintStatus(sess, _UU("STATUS_9"));
5081 #ifdef OS_UNIX
5082 	UnixVLanSetState(c->Session->ClientOption->DeviceName, true);
5083 #endif
5084 	// Shift the connection to the tunneling mode
5085 	StartTunnelingMode(c);
5086 	s = NULL;
5087 
5088 	if (c->Session->HalfConnection)
5089 	{
5090 		// Processing in the case of half-connection
5091 		TCPSOCK *ts = (TCPSOCK *)LIST_DATA(c->Tcp->TcpSockList, 0);
5092 		ts->Direction = TCP_CLIENT_TO_SERVER;
5093 	}
5094 
5095 	PrintStatus(sess, L"free");
5096 
5097 	CLog(c->Cedar->Client, "LC_CONNECT_2", c->Session->ClientOption->AccountName,
5098 		session_name);
5099 
5100 	if (c->Session->LinkModeClient && c->Session->Link != NULL)
5101 	{
5102 		HLog(c->Session->Link->Hub, "LH_CONNECT_2", c->Session->ClientOption->AccountName, session_name);
5103 	}
5104 
5105 	// Main routine of the session
5106 	SessionMain(c->Session);
5107 
5108 	ok = true;
5109 
5110 	if (c->Err == ERR_USER_CANCEL)
5111 	{
5112 		ret = true;
5113 	}
5114 
5115 CLEANUP:
5116 	c->FirstSock = NULL;
5117 
5118 	if (sess->UdpAccel != NULL)
5119 	{
5120 		FreeUdpAccel(sess->UdpAccel);
5121 		sess->UdpAccel = NULL;
5122 	}
5123 
5124 	if (p != NULL)
5125 	{
5126 		FreePack(p);
5127 	}
5128 
5129 	Disconnect(s);
5130 	ReleaseSock(s);
5131 
5132 	Debug("Error: %u\n", c->Err);
5133 
5134 	if (ok == false)
5135 	{
5136 		PrintStatus(sess, L"free");
5137 	}
5138 
5139 	return ret;
5140 }
5141 
5142 // Parse the Welcome packet
ParseWelcomeFromPack(PACK * p,char * session_name,UINT session_name_size,char * connection_name,UINT connection_name_size,POLICY ** policy)5143 bool ParseWelcomeFromPack(PACK *p, char *session_name, UINT session_name_size,
5144 						  char *connection_name, UINT connection_name_size,
5145 						  POLICY **policy)
5146 {
5147 	// Validate arguments
5148 	if (p == NULL || session_name == NULL || connection_name == NULL || policy == NULL)
5149 	{
5150 		return false;
5151 	}
5152 
5153 	// Session name
5154 	if (PackGetStr(p, "session_name", session_name, session_name_size) == false)
5155 	{
5156 		return false;
5157 	}
5158 
5159 	// Connection name
5160 	if (PackGetStr(p, "connection_name", connection_name, connection_name_size) == false)
5161 	{
5162 		return false;
5163 	}
5164 
5165 	// Policy
5166 	*policy = PackGetPolicy(p);
5167 	if (*policy == NULL)
5168 	{
5169 		return false;
5170 	}
5171 
5172 	return true;
5173 }
5174 
5175 // Generate the Welcome packet
PackWelcome(SESSION * s)5176 PACK *PackWelcome(SESSION *s)
5177 {
5178 	PACK *p;
5179 	// Validate arguments
5180 	if (s == NULL)
5181 	{
5182 		return NULL;
5183 	}
5184 
5185 	p = NewPack();
5186 
5187 	// Session name
5188 	PackAddStr(p, "session_name", s->Name);
5189 
5190 	// Connection name
5191 	PackAddStr(p, "connection_name", s->Connection->Name);
5192 
5193 	// Parameters
5194 	PackAddInt(p, "max_connection", s->MaxConnection);
5195 	PackAddInt(p, "use_encrypt", s->UseEncrypt == false ? 0 : 1);
5196 	PackAddInt(p, "use_compress", s->UseCompress == false ? 0 : 1);
5197 	PackAddInt(p, "half_connection", s->HalfConnection == false ? 0 : 1);
5198 	PackAddInt(p, "timeout", s->Timeout);
5199 	PackAddInt(p, "qos", s->QoS ? 1 : 0);
5200 	PackAddInt(p, "is_azure_session", s->IsAzureSession);
5201 
5202 	// Session key
5203 	PackAddData(p, "session_key", s->SessionKey, SHA1_SIZE);
5204 	PackAddInt(p, "session_key_32", s->SessionKey32);
5205 
5206 	// Policy
5207 	PackAddPolicy(p, s->Policy);
5208 
5209 	// VLAN ID
5210 	PackAddInt(p, "vlan_id", s->VLanId);
5211 
5212 	if (s->Connection->Protocol == CONNECTION_UDP)
5213 	{
5214 		// In the case of UDP protocol, generate 2 pairs of key
5215 		Rand(s->UdpSendKey, sizeof(s->UdpSendKey));
5216 		Rand(s->UdpRecvKey, sizeof(s->UdpRecvKey));
5217 
5218 		// Send to client by exchanging 2 keys
5219 		PackAddData(p, "udp_send_key", s->UdpRecvKey, sizeof(s->UdpRecvKey));
5220 		PackAddData(p, "udp_recv_key", s->UdpSendKey, sizeof(s->UdpSendKey));
5221 	}
5222 
5223 	// no_send_signature
5224 	if (s->NoSendSignature)
5225 	{
5226 		PackAddBool(p, "no_send_signature", true);
5227 	}
5228 
5229 	if (s->InProcMode)
5230 	{
5231 		// MAC address for IPC
5232 		PackAddData(p, "IpcMacAddress", s->IpcMacAddress, 6);
5233 
5234 		// Virtual HUB name
5235 		PackAddStr(p, "IpcHubName", s->Hub->Name);
5236 
5237 		// Shared Buffer
5238 		s->IpcSessionSharedBuffer = NewSharedBuffer(NULL, sizeof(IPC_SESSION_SHARED_BUFFER_DATA));
5239 		AddRef(s->IpcSessionSharedBuffer->Ref);
5240 
5241 		s->IpcSessionShared = s->IpcSessionSharedBuffer->Data;
5242 
5243 		PackAddInt64(p, "IpcSessionSharedBuffer", (UINT64)s->IpcSessionSharedBuffer);
5244 	}
5245 
5246 	if (s->UdpAccel != NULL)
5247 	{
5248 		// UDP acceleration function
5249 		PackAddBool(p, "use_udp_acceleration", true);
5250 		PackAddInt(p, "udp_acceleration_version", s->UdpAccel->Version);
5251 		PackAddIp(p, "udp_acceleration_server_ip", &s->UdpAccel->MyIp);
5252 		PackAddInt(p, "udp_acceleration_server_port", s->UdpAccel->MyPort);
5253 		PackAddData(p, "udp_acceleration_server_key", s->UdpAccel->MyKey, sizeof(s->UdpAccel->MyKey));
5254 		PackAddData(p, "udp_acceleration_server_key_v2", s->UdpAccel->MyKey_V2, sizeof(s->UdpAccel->MyKey_V2));
5255 		PackAddInt(p, "udp_acceleration_server_cookie", s->UdpAccel->MyCookie);
5256 		PackAddInt(p, "udp_acceleration_client_cookie", s->UdpAccel->YourCookie);
5257 		PackAddBool(p, "udp_acceleration_use_encryption", !s->UdpAccel->PlainTextMode);
5258 		PackAddBool(p, "use_hmac_on_udp_acceleration", s->UdpAccel->UseHMac);
5259 		PackAddBool(p, "udp_accel_fast_disconnect_detect", s->UdpAccelFastDisconnectDetect);
5260 	}
5261 
5262 	if (s->EnableBulkOnRUDP)
5263 	{
5264 		// Allow bulk transfer on R-UDP
5265 		PackAddBool(p, "enable_bulk_on_rudp", true);
5266 		PackAddBool(p, "enable_hmac_on_bulk_of_rudp", s->EnableHMacOnBulkOfRUDP);
5267 		PackAddInt(p, "rudp_bulk_version", s->BulkOnRUDPVersion);
5268 
5269 		if (s->BulkOnRUDPVersion == 2)
5270 		{
5271 			PackAddData(p, "bulk_on_rudp_send_key", s->Connection->FirstSock->BulkRecvKey->Data, RUDP_BULK_KEY_SIZE_V2);
5272 			s->Connection->FirstSock->BulkRecvKey->Size = RUDP_BULK_KEY_SIZE_V2;
5273 
5274 			PackAddData(p, "bulk_on_rudp_recv_key", s->Connection->FirstSock->BulkSendKey->Data, RUDP_BULK_KEY_SIZE_V2);
5275 			s->Connection->FirstSock->BulkSendKey->Size = RUDP_BULK_KEY_SIZE_V2;
5276 		}
5277 		else
5278 		{
5279 			PackAddData(p, "bulk_on_rudp_send_key", s->Connection->FirstSock->BulkRecvKey->Data, SHA1_SIZE);
5280 			s->Connection->FirstSock->BulkRecvKey->Size = SHA1_SIZE;
5281 
5282 			PackAddData(p, "bulk_on_rudp_recv_key", s->Connection->FirstSock->BulkSendKey->Data, SHA1_SIZE);
5283 			s->Connection->FirstSock->BulkSendKey->Size = SHA1_SIZE;
5284 		}
5285 
5286 		// Backup R-UDP bulk send/recv keys for additional connections
5287 		Copy(s->BulkSendKey, s->Connection->FirstSock->BulkSendKey->Data,
5288 			s->Connection->FirstSock->BulkSendKey->Size);
5289 
5290 		s->BulkSendKeySize = s->Connection->FirstSock->BulkSendKey->Size;
5291 
5292 		Copy(s->BulkRecvKey, s->Connection->FirstSock->BulkRecvKey->Data,
5293 			s->Connection->FirstSock->BulkRecvKey->Size);
5294 
5295 		s->BulkRecvKeySize = s->Connection->FirstSock->BulkRecvKey->Size;
5296 	}
5297 
5298 	if (s->IsAzureSession)
5299 	{
5300 		if (s->Connection != NULL && s->Connection->FirstSock != NULL)
5301 		{
5302 			SOCK *sock = s->Connection->FirstSock;
5303 
5304 			PackAddIp(p, "azure_real_server_global_ip", &sock->Reverse_MyServerGlobalIp);
5305 		}
5306 	}
5307 
5308 	PackAddBool(p, "enable_udp_recovery", s->EnableUdpRecovery);
5309 
5310 	return p;
5311 }
5312 
5313 #define	PACK_ADD_POLICY_BOOL(name, value)	\
5314 	PackAddBool(p, "policy:" name, y->value == false ? 0 : 1)
5315 #define	PACK_ADD_POLICY_UINT(name, value)	\
5316 	PackAddInt(p, "policy:" name, y->value)
5317 #define	PACK_GET_POLICY_BOOL(name, value)	\
5318 	y->value = (PackGetBool(p, "policy:" name))
5319 #define	PACK_GET_POLICY_UINT(name, value)	\
5320 	y->value = PackGetInt(p, "policy:" name)
5321 
5322 // Get a PACK from the session key
GetSessionKeyFromPack(PACK * p,UCHAR * session_key,UINT * session_key_32)5323 bool GetSessionKeyFromPack(PACK *p, UCHAR *session_key, UINT *session_key_32)
5324 {
5325 	// Validate arguments
5326 	if (p == NULL || session_key == NULL || session_key_32 == NULL)
5327 	{
5328 		return false;
5329 	}
5330 
5331 	if (PackGetDataSize(p, "session_key") != SHA1_SIZE)
5332 	{
5333 		return false;
5334 	}
5335 	if (PackGetData(p, "session_key", session_key) == false)
5336 	{
5337 		return false;
5338 	}
5339 	*session_key_32 = PackGetInt(p, "session_key_32");
5340 
5341 	return true;
5342 }
5343 
5344 // Get the policy from the PACK
PackGetPolicy(PACK * p)5345 POLICY *PackGetPolicy(PACK *p)
5346 {
5347 	POLICY *y;
5348 	// Validate arguments
5349 	if (p == NULL)
5350 	{
5351 		return NULL;
5352 	}
5353 
5354 	y = ZeroMalloc(sizeof(POLICY));
5355 
5356 	// Bool value
5357 	// Ver 2
5358 	PACK_GET_POLICY_BOOL("Access", Access);
5359 	PACK_GET_POLICY_BOOL("DHCPFilter", DHCPFilter);
5360 	PACK_GET_POLICY_BOOL("DHCPNoServer", DHCPNoServer);
5361 	PACK_GET_POLICY_BOOL("DHCPForce", DHCPForce);
5362 	PACK_GET_POLICY_BOOL("NoBridge", NoBridge);
5363 	PACK_GET_POLICY_BOOL("NoRouting", NoRouting);
5364 	PACK_GET_POLICY_BOOL("PrivacyFilter", PrivacyFilter);
5365 	PACK_GET_POLICY_BOOL("NoServer", NoServer);
5366 	PACK_GET_POLICY_BOOL("CheckMac", CheckMac);
5367 	PACK_GET_POLICY_BOOL("CheckIP", CheckIP);
5368 	PACK_GET_POLICY_BOOL("ArpDhcpOnly", ArpDhcpOnly);
5369 	PACK_GET_POLICY_BOOL("MonitorPort", MonitorPort);
5370 	PACK_GET_POLICY_BOOL("NoBroadcastLimiter", NoBroadcastLimiter);
5371 	PACK_GET_POLICY_BOOL("FixPassword", FixPassword);
5372 	PACK_GET_POLICY_BOOL("NoQoS", NoQoS);
5373 	// Ver 3
5374 	PACK_GET_POLICY_BOOL("RSandRAFilter", RSandRAFilter);
5375 	PACK_GET_POLICY_BOOL("RAFilter", RAFilter);
5376 	PACK_GET_POLICY_BOOL("DHCPv6Filter", DHCPv6Filter);
5377 	PACK_GET_POLICY_BOOL("DHCPv6NoServer", DHCPv6NoServer);
5378 	PACK_GET_POLICY_BOOL("NoRoutingV6", NoRoutingV6);
5379 	PACK_GET_POLICY_BOOL("CheckIPv6", CheckIPv6);
5380 	PACK_GET_POLICY_BOOL("NoServerV6", NoServerV6);
5381 	PACK_GET_POLICY_BOOL("NoSavePassword", NoSavePassword);
5382 	PACK_GET_POLICY_BOOL("FilterIPv4", FilterIPv4);
5383 	PACK_GET_POLICY_BOOL("FilterIPv6", FilterIPv6);
5384 	PACK_GET_POLICY_BOOL("FilterNonIP", FilterNonIP);
5385 	PACK_GET_POLICY_BOOL("NoIPv6DefaultRouterInRA", NoIPv6DefaultRouterInRA);
5386 	PACK_GET_POLICY_BOOL("NoIPv6DefaultRouterInRAWhenIPv6", NoIPv6DefaultRouterInRAWhenIPv6);
5387 
5388 	// UINT value
5389 	// Ver 2
5390 	PACK_GET_POLICY_UINT("MaxConnection", MaxConnection);
5391 	PACK_GET_POLICY_UINT("TimeOut", TimeOut);
5392 	PACK_GET_POLICY_UINT("MaxMac", MaxMac);
5393 	PACK_GET_POLICY_UINT("MaxIP", MaxIP);
5394 	PACK_GET_POLICY_UINT("MaxUpload", MaxUpload);
5395 	PACK_GET_POLICY_UINT("MaxDownload", MaxDownload);
5396 	PACK_GET_POLICY_UINT("MultiLogins", MultiLogins);
5397 	// Ver 3
5398 	PACK_GET_POLICY_UINT("MaxIPv6", MaxIPv6);
5399 	PACK_GET_POLICY_UINT("AutoDisconnect", AutoDisconnect);
5400 	PACK_GET_POLICY_UINT("VLanId", VLanId);
5401 
5402 	// Ver 3 flag
5403 	PACK_GET_POLICY_BOOL("Ver3", Ver3);
5404 
5405 	return y;
5406 }
5407 
5408 // Insert the policy into the PACK
PackAddPolicy(PACK * p,POLICY * y)5409 void PackAddPolicy(PACK *p, POLICY *y)
5410 {
5411 	// Validate arguments
5412 	if (p == NULL || y == NULL)
5413 	{
5414 		return;
5415 	}
5416 
5417 	// Bool value
5418 	// Ver 2
5419 	PACK_ADD_POLICY_BOOL("Access", Access);
5420 	PACK_ADD_POLICY_BOOL("DHCPFilter", DHCPFilter);
5421 	PACK_ADD_POLICY_BOOL("DHCPNoServer", DHCPNoServer);
5422 	PACK_ADD_POLICY_BOOL("DHCPForce", DHCPForce);
5423 	PACK_ADD_POLICY_BOOL("NoBridge", NoBridge);
5424 	PACK_ADD_POLICY_BOOL("NoRouting", NoRouting);
5425 	PACK_ADD_POLICY_BOOL("PrivacyFilter", PrivacyFilter);
5426 	PACK_ADD_POLICY_BOOL("NoServer", NoServer);
5427 	PACK_ADD_POLICY_BOOL("CheckMac", CheckMac);
5428 	PACK_ADD_POLICY_BOOL("CheckIP", CheckIP);
5429 	PACK_ADD_POLICY_BOOL("ArpDhcpOnly", ArpDhcpOnly);
5430 	PACK_ADD_POLICY_BOOL("MonitorPort", MonitorPort);
5431 	PACK_ADD_POLICY_BOOL("NoBroadcastLimiter", NoBroadcastLimiter);
5432 	PACK_ADD_POLICY_BOOL("FixPassword", FixPassword);
5433 	PACK_ADD_POLICY_BOOL("NoQoS", NoQoS);
5434 	// Ver 3
5435 	PACK_ADD_POLICY_BOOL("RSandRAFilter", RSandRAFilter);
5436 	PACK_ADD_POLICY_BOOL("RAFilter", RAFilter);
5437 	PACK_ADD_POLICY_BOOL("DHCPv6Filter", DHCPv6Filter);
5438 	PACK_ADD_POLICY_BOOL("DHCPv6NoServer", DHCPv6NoServer);
5439 	PACK_ADD_POLICY_BOOL("NoRoutingV6", NoRoutingV6);
5440 	PACK_ADD_POLICY_BOOL("CheckIPv6", CheckIPv6);
5441 	PACK_ADD_POLICY_BOOL("NoServerV6", NoServerV6);
5442 	PACK_ADD_POLICY_BOOL("NoSavePassword", NoSavePassword);
5443 	PACK_ADD_POLICY_BOOL("FilterIPv4", FilterIPv4);
5444 	PACK_ADD_POLICY_BOOL("FilterIPv6", FilterIPv6);
5445 	PACK_ADD_POLICY_BOOL("FilterNonIP", FilterNonIP);
5446 	PACK_ADD_POLICY_BOOL("NoIPv6DefaultRouterInRA", NoIPv6DefaultRouterInRA);
5447 	PACK_ADD_POLICY_BOOL("NoIPv6DefaultRouterInRAWhenIPv6", NoIPv6DefaultRouterInRAWhenIPv6);
5448 
5449 	// UINT value
5450 	// Ver 2
5451 	PACK_ADD_POLICY_UINT("MaxConnection", MaxConnection);
5452 	PACK_ADD_POLICY_UINT("TimeOut", TimeOut);
5453 	PACK_ADD_POLICY_UINT("MaxMac", MaxMac);
5454 	PACK_ADD_POLICY_UINT("MaxIP", MaxIP);
5455 	PACK_ADD_POLICY_UINT("MaxUpload", MaxUpload);
5456 	PACK_ADD_POLICY_UINT("MaxDownload", MaxDownload);
5457 	PACK_ADD_POLICY_UINT("MultiLogins", MultiLogins);
5458 	// Ver 3
5459 	PACK_ADD_POLICY_UINT("MaxIPv6", MaxIPv6);
5460 	PACK_ADD_POLICY_UINT("AutoDisconnect", AutoDisconnect);
5461 	PACK_ADD_POLICY_UINT("VLanId", VLanId);
5462 
5463 	// Ver 3 flag
5464 	PackAddBool(p, "policy:Ver3", true);
5465 }
5466 
5467 // Upload the authentication data for the additional connection
ClientUploadAuth2(CONNECTION * c,SOCK * s)5468 bool ClientUploadAuth2(CONNECTION *c, SOCK *s)
5469 {
5470 	PACK *p = NULL;
5471 	// Validate arguments
5472 	if (c == NULL)
5473 	{
5474 		return false;
5475 	}
5476 
5477 	p = PackAdditionalConnect(c->Session->SessionKey);
5478 
5479 	PackAddClientVersion(p, c);
5480 
5481 	if (HttpClientSend(s, p) == false)
5482 	{
5483 		FreePack(p);
5484 		return false;
5485 	}
5486 	FreePack(p);
5487 
5488 	return true;
5489 }
5490 
5491 // Send a NOOP
ClientUploadNoop(CONNECTION * c)5492 void ClientUploadNoop(CONNECTION *c)
5493 {
5494 	PACK *p;
5495 	// Validate arguments
5496 	if (c == NULL)
5497 	{
5498 		return;
5499 	}
5500 
5501 	p = PackError(0);
5502 	PackAddInt(p, "noop", 1);
5503 	(void)HttpClientSend(c->FirstSock, p);
5504 	FreePack(p);
5505 
5506 	p = HttpClientRecv(c->FirstSock);
5507 	if (p != NULL)
5508 	{
5509 		FreePack(p);
5510 	}
5511 }
5512 
5513 // Add client version information to the PACK
PackAddClientVersion(PACK * p,CONNECTION * c)5514 void PackAddClientVersion(PACK *p, CONNECTION *c)
5515 {
5516 	// Validate arguments
5517 	if (p == NULL || c == NULL)
5518 	{
5519 		return;
5520 	}
5521 
5522 	PackAddStr(p, "client_str", c->ClientStr);
5523 	PackAddInt(p, "client_ver", c->ClientVer);
5524 	PackAddInt(p, "client_build", c->ClientBuild);
5525 }
5526 
5527 // Upload the certificate data for the new connection
ClientUploadAuth(CONNECTION * c)5528 bool ClientUploadAuth(CONNECTION *c)
5529 {
5530 	PACK *p = NULL;
5531 	CLIENT_AUTH *a;
5532 	CLIENT_OPTION *o;
5533 	X *x;
5534 	bool ret;
5535 	NODE_INFO info;
5536 	UCHAR secure_password[SHA1_SIZE];
5537 	UCHAR sign[4096 / 8];
5538 	UCHAR unique[SHA1_SIZE];
5539 	RPC_WINVER v;
5540 	// Validate arguments
5541 	if (c == NULL)
5542 	{
5543 		return false;
5544 	}
5545 
5546 	Zero(sign, sizeof(sign));
5547 
5548 	a = c->Session->ClientAuth;
5549 	o = c->Session->ClientOption;
5550 
5551 	if (c->UseTicket == false)
5552 	{
5553 		switch (a->AuthType)
5554 		{
5555 		case CLIENT_AUTHTYPE_ANONYMOUS:
5556 			// Anonymous authentication
5557 			p = PackLoginWithAnonymous(o->HubName, a->Username);
5558 			break;
5559 
5560 		case CLIENT_AUTHTYPE_PASSWORD:
5561 			// Password authentication
5562 			SecurePassword(secure_password, a->HashedPassword, c->Random);
5563 			p = PackLoginWithPassword(o->HubName, a->Username, secure_password);
5564 			break;
5565 
5566 		case CLIENT_AUTHTYPE_PLAIN_PASSWORD:
5567 			// Plaintext password authentication
5568 			p = PackLoginWithPlainPassword(o->HubName, a->Username, a->PlainPassword);
5569 			break;
5570 
5571 		case CLIENT_AUTHTYPE_CERT:
5572 			// Certificate authentication
5573 			if (a->ClientX != NULL && a->ClientX->is_compatible_bit &&
5574 				a->ClientX->bits != 0 && (a->ClientX->bits / 8) <= sizeof(sign))
5575 			{
5576 				if (RsaSignEx(sign, c->Random, SHA1_SIZE, a->ClientK, a->ClientX->bits))
5577 				{
5578 					p = PackLoginWithCert(o->HubName, a->Username, a->ClientX, sign, a->ClientX->bits / 8);
5579 					c->ClientX = CloneX(a->ClientX);
5580 				}
5581 			}
5582 			break;
5583 
5584 		case CLIENT_AUTHTYPE_OPENSSLENGINE:
5585 			// Certificate authentication
5586 			if (a->ClientX != NULL && a->ClientX->is_compatible_bit &&
5587 				a->ClientX->bits != 0 && (a->ClientX->bits / 8) <= sizeof(sign))
5588 			{
5589 				if (RsaSignEx(sign, c->Random, SHA1_SIZE, a->ClientK, a->ClientX->bits))
5590 				{
5591 					p = PackLoginWithCert(o->HubName, a->Username, a->ClientX, sign, a->ClientX->bits / 8);
5592 					c->ClientX = CloneX(a->ClientX);
5593 				}
5594 			}
5595 			break;
5596 
5597 
5598 		case CLIENT_AUTHTYPE_SECURE:
5599 			// Authentication by secure device
5600 			if (ClientSecureSign(c, sign, c->Random, &x))
5601 			{
5602 				p = PackLoginWithCert(o->HubName, a->Username, x, sign, x->bits / 8);
5603 				c->ClientX = CloneX(x);
5604 				FreeX(x);
5605 			}
5606 			else
5607 			{
5608 				c->Err = ERR_SECURE_DEVICE_OPEN_FAILED;
5609 				c->Session->ForceStopFlag = true;
5610 			}
5611 			break;
5612 		}
5613 	}
5614 	else
5615 	{
5616 		// Ticket
5617 		p = NewPack();
5618 		PackAddStr(p, "method", "login");
5619 		PackAddStr(p, "hubname", o->HubName);
5620 		PackAddStr(p, "username", a->Username);
5621 		PackAddInt(p, "authtype", AUTHTYPE_TICKET);
5622 		PackAddData(p, "ticket", c->Ticket, SHA1_SIZE);
5623 	}
5624 
5625 	if (p == NULL)
5626 	{
5627 		// Error
5628 		if (c->Err != ERR_SECURE_DEVICE_OPEN_FAILED)
5629 		{
5630 			c->Err = ERR_PROTOCOL_ERROR;
5631 		}
5632 		return false;
5633 	}
5634 
5635 	PackAddClientVersion(p, c);
5636 
5637 	// Protocol
5638 	PackAddInt(p, "protocol", c->Protocol);
5639 
5640 	// Version, etc.
5641 	PackAddStr(p, "hello", c->ClientStr);
5642 	PackAddInt(p, "version", c->ClientVer);
5643 	PackAddInt(p, "build", c->ClientBuild);
5644 	PackAddInt(p, "client_id", c->Cedar->ClientId);
5645 
5646 	// The maximum number of connections
5647 	PackAddInt(p, "max_connection", o->MaxConnection);
5648 	// Flag to use of cryptography
5649 	PackAddInt(p, "use_encrypt", o->UseEncrypt == false ? 0 : 1);
5650 	// Data compression flag
5651 	PackAddInt(p, "use_compress", o->UseCompress == false ? 0 : 1);
5652 	// Half connection flag
5653 	PackAddInt(p, "half_connection", o->HalfConnection == false ? 0 : 1);
5654 
5655 	// Bridge / routing mode flag
5656 	PackAddBool(p, "require_bridge_routing_mode", o->RequireBridgeRoutingMode);
5657 
5658 	// Monitor mode flag
5659 	PackAddBool(p, "require_monitor_mode", o->RequireMonitorMode);
5660 
5661 	// VoIP / QoS flag
5662 	PackAddBool(p, "qos", o->DisableQoS ? false : true);
5663 
5664 	// Bulk transfer support
5665 	PackAddBool(p, "support_bulk_on_rudp", true);
5666 	PackAddBool(p, "support_hmac_on_bulk_of_rudp", true);
5667 
5668 	// UDP recovery support
5669 	PackAddBool(p, "support_udp_recovery", true);
5670 
5671 	// Unique ID
5672 	GenerateMachineUniqueHash(unique);
5673 	PackAddData(p, "unique_id", unique, SHA1_SIZE);
5674 
5675 	// UDP acceleration function using flag
5676 	if (o->NoUdpAcceleration == false && c->Session->UdpAccel != NULL)
5677 	{
5678 		PackAddBool(p, "use_udp_acceleration", true);
5679 
5680 		PackAddInt(p, "udp_acceleration_version", c->Session->UdpAccel->Version);
5681 
5682 		IP my_ip;
5683 		if (IsLocalHostIP(&c->Session->UdpAccel->MyIp) == false)
5684 		{
5685 			Copy(&my_ip, &c->Session->UdpAccel->MyIp, sizeof(my_ip));
5686 		}
5687 		else
5688 		{
5689 			Zero(&my_ip, sizeof(my_ip));
5690 		}
5691 
5692 		PackAddIp(p, "udp_acceleration_client_ip", &my_ip);
5693 		PackAddInt(p, "udp_acceleration_client_port", c->Session->UdpAccel->MyPort);
5694 		PackAddData(p, "udp_acceleration_client_key", c->Session->UdpAccel->MyKey, UDP_ACCELERATION_COMMON_KEY_SIZE_V1);
5695 		PackAddData(p, "udp_acceleration_client_key_v2", c->Session->UdpAccel->MyKey_V2, UDP_ACCELERATION_COMMON_KEY_SIZE_V2);
5696 		PackAddBool(p, "support_hmac_on_udp_acceleration", true);
5697 		PackAddBool(p, "support_udp_accel_fast_disconnect_detect", true);
5698 		PackAddInt(p, "udp_acceleration_max_version", 2);
5699 	}
5700 
5701 	PackAddInt(p, "rudp_bulk_max_version", 2);
5702 
5703 	// Brand string for the connection limit
5704 	{
5705 		char *branded_ctos = _SS("BRANDED_C_TO_S");
5706 		if(StrLen(branded_ctos) > 0)
5707 		{
5708 			PackAddStr(p, "branded_ctos", branded_ctos);
5709 		}
5710 	}
5711 
5712 	// Node information
5713 	CreateNodeInfo(&info, c);
5714 	OutRpcNodeInfo(p, &info);
5715 
5716 	// OS information
5717 	GetWinVer(&v);
5718 	OutRpcWinVer(p, &v);
5719 
5720 	ret = HttpClientSend(c->FirstSock, p);
5721 	if (ret == false)
5722 	{
5723 		c->Err = ERR_DISCONNECTED;
5724 	}
5725 
5726 	FreePack(p);
5727 
5728 	return ret;
5729 }
5730 
5731 // Upload the Hello packet
ServerUploadHello(CONNECTION * c)5732 bool ServerUploadHello(CONNECTION *c)
5733 {
5734 	PACK *p;
5735 	// Validate arguments
5736 	if (c == NULL)
5737 	{
5738 		return false;
5739 	}
5740 
5741 	// Random number generation
5742 	Rand(c->Random, SHA1_SIZE);
5743 
5744 	p = PackHello(c->Random, c->ServerVer, c->ServerBuild, c->ServerStr);
5745 	if (HttpServerSend(c->FirstSock, p) == false)
5746 	{
5747 		FreePack(p);
5748 		c->Err = ERR_DISCONNECTED;
5749 		return false;
5750 	}
5751 
5752 	FreePack(p);
5753 
5754 	return true;
5755 }
5756 
5757 // Download the Hello packet
ClientDownloadHello(CONNECTION * c,SOCK * s)5758 bool ClientDownloadHello(CONNECTION *c, SOCK *s)
5759 {
5760 	PACK *p;
5761 	UINT err;
5762 	UCHAR random[SHA1_SIZE];
5763 	// Validate arguments
5764 	if (c == NULL)
5765 	{
5766 		return false;
5767 	}
5768 
5769 	// Data reception
5770 	p = HttpClientRecv(s);
5771 	if (p == NULL)
5772 	{
5773 		c->Err = ERR_SERVER_IS_NOT_VPN;
5774 		return false;
5775 	}
5776 
5777 	if (err = GetErrorFromPack(p))
5778 	{
5779 		// An error has occured
5780 		c->Err = err;
5781 		FreePack(p);
5782 		return false;
5783 	}
5784 
5785 	// Packet interpretation
5786 	if (GetHello(p, random, &c->ServerVer, &c->ServerBuild, c->ServerStr, sizeof(c->ServerStr)) == false)
5787 	{
5788 		c->Err = ERR_SERVER_IS_NOT_VPN;
5789 		FreePack(p);
5790 		return false;
5791 	}
5792 
5793 	if (c->FirstSock == s)
5794 	{
5795 		Copy(c->Random, random, SHA1_SIZE);
5796 	}
5797 
5798 	FreePack(p);
5799 
5800 	return true;
5801 }
5802 
5803 // Download the signature
ServerDownloadSignature(CONNECTION * c,char ** error_detail_str)5804 bool ServerDownloadSignature(CONNECTION *c, char **error_detail_str)
5805 {
5806 	HTTP_HEADER *h;
5807 	UCHAR *data;
5808 	UINT data_size;
5809 	SOCK *s;
5810 	UINT num = 0, max = 19;
5811 	SERVER *server;
5812 	char *vpn_http_target = HTTP_VPN_TARGET2;
5813 	// Validate arguments
5814 	if (c == NULL)
5815 	{
5816 		return false;
5817 	}
5818 
5819 	server = c->Cedar->Server;
5820 
5821 	s = c->FirstSock;
5822 
5823 	while (true)
5824 	{
5825 		bool not_found_error = false;
5826 
5827 		num++;
5828 		if (num > max)
5829 		{
5830 			// Disconnect
5831 			Disconnect(s);
5832 			c->Err = ERR_CLIENT_IS_NOT_VPN;
5833 
5834 			*error_detail_str = "HTTP_TOO_MANY_REQUEST";
5835 			return false;
5836 		}
5837 		// Receive a header
5838 		h = RecvHttpHeader(s);
5839 		if (h == NULL)
5840 		{
5841 			c->Err = ERR_CLIENT_IS_NOT_VPN;
5842 			if (c->IsJsonRpc)
5843 			{
5844 				c->Err = ERR_DISCONNECTED;
5845 			}
5846 			return false;
5847 		}
5848 
5849 		// Interpret
5850 		if (StrCmpi(h->Method, "POST") == 0)
5851 		{
5852 			// Receive the data since it's POST
5853 			data_size = GetContentLength(h);
5854 
5855 			if (server->DisableJsonRpcWebApi == false)
5856 			{
5857 				if (StrCmpi(h->Target, "/api") == 0 || StrCmpi(h->Target, "/api/") == 0)
5858 				{
5859 					c->IsJsonRpc = true;
5860 					c->Type = CONNECTION_TYPE_ADMIN_RPC;
5861 
5862 					JsonRpcProcPost(c, s, h, data_size);
5863 
5864 					FreeHttpHeader(h);
5865 
5866 					if (c->JsonRpcAuthed)
5867 					{
5868 						num = 0;
5869 					}
5870 
5871 					continue;
5872 				}
5873 				else if (StartWith(h->Target, "/admin"))
5874 				{
5875 					c->IsJsonRpc = true;
5876 					c->Type = CONNECTION_TYPE_ADMIN_RPC;
5877 
5878 					AdminWebProcPost(c, s, h, data_size, h->Target);
5879 
5880 					FreeHttpHeader(h);
5881 
5882 					if (c->JsonRpcAuthed)
5883 					{
5884 						num = 0;
5885 					}
5886 
5887 					continue;
5888 				}
5889 			}
5890 
5891 			if ((data_size > MAX_WATERMARK_SIZE || data_size < SizeOfWaterMark()) && (data_size != StrLen(HTTP_VPN_TARGET_POSTDATA)))
5892 			{
5893 				// Data is too large
5894 				HttpSendForbidden(s, h->Target, NULL);
5895 				FreeHttpHeader(h);
5896 				c->Err = ERR_CLIENT_IS_NOT_VPN;
5897 				*error_detail_str = "POST_Recv_TooLong";
5898 				return false;
5899 			}
5900 			data = Malloc(data_size);
5901 			if (RecvAll(s, data, data_size, s->SecureMode) == false)
5902 			{
5903 				// Data reception failure
5904 				Free(data);
5905 				FreeHttpHeader(h);
5906 				c->Err = ERR_DISCONNECTED;
5907 				*error_detail_str = "POST_Recv_Failed";
5908 				return false;
5909 			}
5910 			// Check the Target
5911 			if ((StrCmpi(h->Target, vpn_http_target) != 0) || not_found_error)
5912 			{
5913 				// Target is invalid
5914 				HttpSendNotFound(s, h->Target);
5915 				Free(data);
5916 				FreeHttpHeader(h);
5917 				*error_detail_str = "POST_Target_Wrong";
5918 			}
5919 			else
5920 			{
5921 				// Compare posted data with the WaterMark
5922 				if ((data_size == StrLen(HTTP_VPN_TARGET_POSTDATA) && (Cmp(data, HTTP_VPN_TARGET_POSTDATA, data_size) == 0))
5923 					|| ((data_size >= SizeOfWaterMark()) && Cmp(data, WaterMark, SizeOfWaterMark()) == 0))
5924 				{
5925 					// Check the WaterMark
5926 					Free(data);
5927 					FreeHttpHeader(h);
5928 					return true;
5929 				}
5930 				else
5931 				{
5932 					// WaterMark is incorrect
5933 					HttpSendForbidden(s, h->Target, NULL);
5934 					FreeHttpHeader(h);
5935 					*error_detail_str = "POST_WaterMark_Error";
5936 				}
5937 			}
5938 		}
5939 		else if (StrCmpi(h->Method, "OPTIONS") == 0)
5940 		{
5941 			if (server->DisableJsonRpcWebApi == false)
5942 			{
5943 				if (StrCmpi(h->Target, "/api") == 0 || StrCmpi(h->Target, "/api/") == 0 || StartWith(h->Target, "/admin"))
5944 				{
5945 					c->IsJsonRpc = true;
5946 					c->Type = CONNECTION_TYPE_ADMIN_RPC;
5947 
5948 					JsonRpcProcOptions(c, s, h, h->Target);
5949 
5950 					FreeHttpHeader(h);
5951 
5952 					num = 0;
5953 
5954 					continue;
5955 				}
5956 			}
5957 		}
5958 		else if (StrCmpi(h->Method, "SSTP_DUPLEX_POST") == 0 && (ProtoEnabled(server->Proto, "SSTP") || s->IsReverseAcceptedSocket) && GetServerCapsBool(server, "b_support_sstp"))
5959 		{
5960 			// SSTP client is connected
5961 			c->WasSstp = true;
5962 
5963 			if (StrCmpi(h->Target, SSTP_URI) == 0)
5964 			{
5965 				bool sstp_ret;
5966 				// Accept the SSTP connection
5967 				c->Type = CONNECTION_TYPE_OTHER;
5968 
5969 				sstp_ret = ProtoHandleConnection(server->Proto, s, "SSTP");
5970 
5971 				c->Err = ERR_DISCONNECTED;
5972 				FreeHttpHeader(h);
5973 
5974 				if (sstp_ret)
5975 				{
5976 					*error_detail_str = "";
5977 				}
5978 				else
5979 				{
5980 					*error_detail_str = "SSTP_ABORT";
5981 				}
5982 
5983 				return false;
5984 			}
5985 			else
5986 			{
5987 				// URI is invalid
5988 				HttpSendNotFound(s, h->Target);
5989 				*error_detail_str = "SSTP_URL_WRONG";
5990 			}
5991 
5992 			FreeHttpHeader(h);
5993 		}
5994 		else
5995 		{
5996 			// This should not be a VPN client, but interpret a bit more
5997 			if (StrCmpi(h->Method, "GET") != 0 && StrCmpi(h->Method, "HEAD") != 0
5998 				 && StrCmpi(h->Method, "POST") != 0)
5999 			{
6000 				// Unsupported method calls
6001 				HttpSendNotImplemented(s, h->Method, h->Target, h->Version);
6002 				*error_detail_str = "HTTP_BAD_METHOD";
6003 			}
6004 			else
6005 			{
6006 				if (StrCmpi(h->Target, "/") == 0)
6007 				{
6008 					// Root directory
6009 					BUF *b = NULL;
6010 					*error_detail_str = "HTTP_ROOT";
6011 
6012 					if (server->DisableJsonRpcWebApi == false)
6013 					{
6014 						b = ReadDump("|wwwroot/index.html");
6015 					}
6016 
6017 					if (b != NULL)
6018 					{
6019 						FreeHttpHeader(h);
6020 						h = NewHttpHeader("HTTP/1.1", "202", "OK");
6021 						AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE4));
6022 						AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
6023 						AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
6024 
6025 						PostHttp(c->FirstSock, h, b->Buf, b->Size);
6026 
6027 						FreeBuf(b);
6028 					}
6029 					else
6030 					{
6031 						HttpSendForbidden(c->FirstSock, h->Target, "");
6032 					}
6033 				}
6034 				else
6035 				{
6036 					bool b = false;
6037 
6038 					// Show the WebUI if the configuration allow to use the WebUI
6039 					if (c->Cedar->Server != NULL && c->Cedar->Server->UseWebUI)
6040 					{
6041 						WU_WEBPAGE *page;
6042 
6043 						// Show the WebUI
6044 						page = WuGetPage(h->Target, c->Cedar->WebUI);
6045 
6046 						if (page != NULL)
6047 						{
6048 							PostHttp(s, page->header, page->data, page->size);
6049 							b = true;
6050 							WuFreeWebPage(page);
6051 						}
6052 
6053 					}
6054 
6055 					if (IsLocalHostIP(&c->FirstSock->RemoteIP))
6056 					{
6057 						if (StrCmpi(h->Target, HTTP_SAITAMA) == 0)
6058 						{
6059 							// Saitama (joke)
6060 							FreeHttpHeader(h);
6061 							h = NewHttpHeader("HTTP/1.1", "202", "OK");
6062 							AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3));
6063 							AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
6064 							AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
6065 							PostHttp(s, h, Saitama, SizeOfSaitama());
6066 							b = true;
6067 						}
6068 						else if (StartWith(h->Target, HTTP_PICTURES))
6069 						{
6070 							BUF *buf;
6071 
6072 							// Lots of photos
6073 							buf = ReadDump("|Pictures.mht");
6074 
6075 							if (buf != NULL)
6076 							{
6077 								FreeHttpHeader(h);
6078 								h = NewHttpHeader("HTTP/1.1", "202", "OK");
6079 								AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE5));
6080 								AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
6081 								AddHttpValue(h, NewHttpValue("Keep-Alive", HTTP_KEEP_ALIVE));
6082 								PostHttp(s, h, buf->Buf, buf->Size);
6083 								b = true;
6084 
6085 								FreeBuf(buf);
6086 							}
6087 						}
6088 					}
6089 
6090 					if (b == false)
6091 					{
6092 						if (server->DisableJsonRpcWebApi == false)
6093 						{
6094 							if (StartWith(h->Target, "/api?") || StartWith(h->Target, "/api/") || StrCmpi(h->Target, "/api") == 0)
6095 							{
6096 								c->IsJsonRpc = true;
6097 								c->Type = CONNECTION_TYPE_ADMIN_RPC;
6098 
6099 								JsonRpcProcGet(c, s, h, h->Target);
6100 
6101 								if (c->JsonRpcAuthed)
6102 								{
6103 									num = 0;
6104 								}
6105 
6106 								FreeHttpHeader(h);
6107 
6108 								continue;
6109 							}
6110 							else if (StartWith(h->Target, "/admin"))
6111 							{
6112 								c->IsJsonRpc = true;
6113 								c->Type = CONNECTION_TYPE_ADMIN_RPC;
6114 
6115 								AdminWebProcGet(c, s, h, h->Target);
6116 
6117 								if (c->JsonRpcAuthed)
6118 								{
6119 									num = 0;
6120 								}
6121 
6122 								FreeHttpHeader(h);
6123 
6124 								continue;
6125 							}
6126 						}
6127 					}
6128 
6129 					if (b == false)
6130 					{
6131 						// Not Found
6132 						HttpSendNotFound(s, h->Target);
6133 
6134 						*error_detail_str = "HTTP_NOT_FOUND";
6135 					}
6136 				}
6137 			}
6138 			FreeHttpHeader(h);
6139 		}
6140 	}
6141 }
6142 
6143 // Upload a signature
ClientUploadSignature(SOCK * s)6144 bool ClientUploadSignature(SOCK *s)
6145 {
6146 	HTTP_HEADER *h;
6147 	UINT water_size, rand_size;
6148 	UCHAR *water;
6149 	char ip_str[128];
6150 	// Validate arguments
6151 	if (s == NULL)
6152 	{
6153 		return false;
6154 	}
6155 
6156 	IPToStr(ip_str, sizeof(ip_str), &s->RemoteIP);
6157 
6158 	h = NewHttpHeader("POST", HTTP_VPN_TARGET2, "HTTP/1.1");
6159 	AddHttpValue(h, NewHttpValue("Host", ip_str));
6160 	AddHttpValue(h, NewHttpValue("Content-Type", HTTP_CONTENT_TYPE3));
6161 	AddHttpValue(h, NewHttpValue("Connection", "Keep-Alive"));
6162 
6163 
6164 
6165 	// Generate a watermark
6166 	rand_size = Rand32() % (HTTP_PACK_RAND_SIZE_MAX * 2);
6167 	water_size = SizeOfWaterMark() + rand_size;
6168 	water = Malloc(water_size);
6169 	Copy(water, WaterMark, SizeOfWaterMark());
6170 	Rand(&water[SizeOfWaterMark()], rand_size);
6171 
6172 	// Upload the watermark data
6173 	if (PostHttp(s, h, water, water_size) == false)
6174 	{
6175 		Free(water);
6176 		FreeHttpHeader(h);
6177 		return false;
6178 	}
6179 
6180 	Free(water);
6181 	FreeHttpHeader(h);
6182 
6183 	return true;
6184 }
6185 
6186 // Establish a connection to the server
ClientConnectToServer(CONNECTION * c)6187 SOCK *ClientConnectToServer(CONNECTION *c)
6188 {
6189 	SOCK *s = NULL;
6190 	X *x = NULL;
6191 	K *k = NULL;
6192 	// Validate arguments
6193 	if (c == NULL)
6194 	{
6195 		return NULL;
6196 	}
6197 
6198 	if (c->Halt)
6199 	{
6200 		c->Err = ERR_USER_CANCEL;
6201 		return NULL;
6202 	}
6203 
6204 	// Get the socket by connecting
6205 	s = ClientConnectGetSocket(c, false);
6206 	if (s == NULL)
6207 	{
6208 		// Connection failure
6209 		return NULL;
6210 	}
6211 
6212 	c->FirstSock = s;
6213 
6214 	if (c->Halt)
6215 	{
6216 		c->Err = ERR_USER_CANCEL;
6217 		ReleaseSock(s);
6218 		c->FirstSock = NULL;
6219 		return NULL;
6220 	}
6221 
6222 	// Time-out
6223 	SetTimeout(s, CONNECTING_TIMEOUT);
6224 
6225 	// Start the SSL communication
6226 	if (StartSSLEx(s, x, k, 0, c->ServerName) == false)
6227 	{
6228 		// SSL communication start failure
6229 		Disconnect(s);
6230 		ReleaseSock(s);
6231 		c->FirstSock = NULL;
6232 		c->Err = ERR_SERVER_IS_NOT_VPN;
6233 		return NULL;
6234 	}
6235 
6236 	if (s->RemoteX == NULL)
6237 	{
6238 		// SSL communication start failure
6239 		Disconnect(s);
6240 		ReleaseSock(s);
6241 		c->FirstSock = NULL;
6242 		c->Err = ERR_SERVER_IS_NOT_VPN;
6243 		return NULL;
6244 	}
6245 
6246 	return s;
6247 }
6248 
6249 // Return a socket by connecting to the server
ClientConnectGetSocket(CONNECTION * c,bool additional_connect)6250 SOCK *ClientConnectGetSocket(CONNECTION *c, bool additional_connect)
6251 {
6252 	volatile bool *cancel_flag = NULL;
6253 	char hostname[MAX_HOST_NAME_LEN];
6254 	bool save_resolved_ip = false;
6255 	CLIENT_OPTION *o;
6256 	SESSION *sess;
6257 	SOCK *sock = NULL;
6258 	IP resolved_ip;
6259 	// Validate arguments
6260 	if (c == NULL || c->Session == NULL || c->Session->ClientOption == NULL)
6261 	{
6262 		return NULL;
6263 	}
6264 
6265 	cancel_flag = &c->Halt;
6266 	sess = c->Session;
6267 	o = c->Session->ClientOption;
6268 
6269 	Zero(&resolved_ip, sizeof(resolved_ip));
6270 
6271 	if (additional_connect == false && c->RestoreServerNameAndPort)
6272 	{
6273 		// Update server name and port number.
6274 		// At the time of writing this comment RestoreServerNameAndPort is never true.
6275 		c->RestoreServerNameAndPort = false;
6276 
6277 		if (StrCmpi(c->ServerName, o->Hostname) != 0)
6278 		{
6279 			StrCpy(c->ServerName, sizeof(c->ServerName), o->Hostname);
6280 		}
6281 
6282 		c->ServerPort = o->Port;
6283 	}
6284 
6285 	if (IsZeroIP(&sess->ServerIP_CacheForNextConnect) == false)
6286 	{
6287 		IPToStr(hostname, sizeof(hostname), &sess->ServerIP_CacheForNextConnect);
6288 		Debug("ClientConnectGetSocket(): Using cached IP address %s\n", hostname);
6289 	}
6290 	else
6291 	{
6292 		IP tmp;
6293 
6294 		StrCpy(hostname, sizeof(hostname), o->ProxyType == PROXY_DIRECT ? c->ServerName : o->ProxyName);
6295 
6296 		if (StrToIP(&tmp, hostname) == false)
6297 		{
6298 			// The hostname is not an IP address
6299 			save_resolved_ip = true;
6300 		}
6301 	}
6302 
6303 	if (o->ProxyType == PROXY_DIRECT)
6304 	{
6305 		UINT nat_t_err = 0;
6306 		wchar_t tmp[MAX_SIZE];
6307 		UniFormat(tmp, sizeof(tmp), _UU("STATUS_4"), hostname);
6308 		PrintStatus(sess, tmp);
6309 
6310 		if (o->PortUDP == 0)
6311 		{
6312 			// If additional_connect == false, enable trying to NAT-T connection
6313 			// If additional_connect == true, follow the IsRUDPSession setting in this session
6314 			sock = TcpIpConnectEx(hostname, c->ServerPort,
6315 				(bool *)cancel_flag, c->hWndForUI, &nat_t_err, (additional_connect ? (!sess->IsRUDPSession) : false),
6316 				true, &resolved_ip);
6317 		}
6318 		else
6319 		{
6320 			// Mode to connect with R-UDP directly without using NAT-T server when using UDP
6321 			IP ip;
6322 			if (StrToIP(&ip, hostname))
6323 			{
6324 				sock = NewRUDPClientDirect(VPN_RUDP_SVC_NAME, &ip, o->PortUDP, &nat_t_err,
6325 					TIMEOUT_TCP_PORT_CHECK, (bool *)cancel_flag, NULL, NULL, 0, false);
6326 
6327 				if (sock != NULL)
6328 				{
6329 					StrCpy(sock->UnderlayProtocol, sizeof(sock->UnderlayProtocol), SOCK_UNDERLAY_NAT_T);
6330 				}
6331 			}
6332 		}
6333 
6334 		if (sock == NULL)
6335 		{
6336 			// Connection failure
6337 			if (nat_t_err != RUDP_ERROR_NAT_T_TWO_OR_MORE)
6338 			{
6339 				c->Err = ERR_CONNECT_FAILED;
6340 			}
6341 			else
6342 			{
6343 				c->Err = ERR_NAT_T_TWO_OR_MORE;
6344 			}
6345 
6346 			return NULL;
6347 		}
6348 	}
6349 	else
6350 	{
6351 		wchar_t tmp[MAX_SIZE];
6352 		PROXY_PARAM_OUT out;
6353 		PROXY_PARAM_IN in;
6354 		UINT ret;
6355 
6356 		Zero(&in, sizeof(in));
6357 
6358 		in.Timeout = 0;
6359 
6360 		StrCpy(in.TargetHostname, sizeof(in.TargetHostname), c->ServerName);
6361 		in.TargetPort = c->ServerPort;
6362 
6363 		StrCpy(in.Hostname, sizeof(in.Hostname), IsEmptyStr(hostname) ? o->ProxyName : hostname);
6364 		in.Port = o->ProxyPort;
6365 
6366 		StrCpy(in.Username, sizeof(in.Username), o->ProxyUsername);
6367 		StrCpy(in.Password, sizeof(in.Password), o->ProxyPassword);
6368 
6369 		StrCpy(in.HttpCustomHeader, sizeof(in.HttpCustomHeader), o->CustomHttpHeader);
6370 		StrCpy(in.HttpUserAgent, sizeof(in.HttpUserAgent), c->Cedar->HttpUserAgent);
6371 
6372 #ifdef OS_WIN32
6373 		in.Hwnd = c->hWndForUI;
6374 #endif
6375 
6376 		UniFormat(tmp, sizeof(tmp), _UU("STATUS_2"), in.TargetHostname, in.Hostname);
6377 		PrintStatus(sess, tmp);
6378 
6379 		switch (o->ProxyType)
6380 		{
6381 		case PROXY_HTTP:
6382 			ret = ProxyHttpConnect(&out, &in, cancel_flag);
6383 			break;
6384 		case PROXY_SOCKS:
6385 			ret = ProxySocks4Connect(&out, &in, cancel_flag);
6386 			break;
6387 		case PROXY_SOCKS5:
6388 			ret = ProxySocks5Connect(&out, &in, cancel_flag);
6389 			break;
6390 		default:
6391 			c->Err = ERR_INTERNAL_ERROR;
6392 			Debug("ClientConnectGetSocket(): Unknown proxy type: %u!\n", o->ProxyType);
6393 			return NULL;
6394 		}
6395 
6396 		c->Err = ProxyCodeToCedar(ret);
6397 
6398 		if (c->Err != ERR_NO_ERROR)
6399 		{
6400 			Debug("ClientConnectGetSocket(): Connection via proxy server failed with error %u\n", ret);
6401 			return NULL;
6402 		}
6403 
6404 		sock = out.Sock;
6405 
6406 		CopyIP(&resolved_ip, &out.ResolvedIp);
6407 	}
6408 
6409 	if (additional_connect == false || IsZeroIP(&sock->RemoteIP))
6410 	{
6411 		if (((sock->IsRUDPSocket || sock->IPv6) && IsZeroIP(&sock->RemoteIP) == false && o->ProxyType == PROXY_DIRECT) || GetIP(&c->Session->ServerIP, hostname) == false)
6412 		{
6413 			Copy(&c->Session->ServerIP, &sock->RemoteIP, sizeof(c->Session->ServerIP));
6414 		}
6415 	}
6416 
6417 	if (save_resolved_ip && IsZeroIP(&resolved_ip) == false)
6418 	{
6419 		Copy(&c->Session->ServerIP_CacheForNextConnect, &resolved_ip, sizeof(c->Session->ServerIP_CacheForNextConnect));
6420 		Debug("ClientConnectGetSocket(): Saved %s IP address %r for future connections.\n", hostname, &resolved_ip);
6421 	}
6422 
6423 	return sock;
6424 }
6425 
ProxyCodeToCedar(UINT code)6426 UINT ProxyCodeToCedar(UINT code)
6427 {
6428 	switch (code)
6429 	{
6430 	case PROXY_ERROR_SUCCESS:
6431 		return ERR_NO_ERROR;
6432 	case PROXY_ERROR_GENERIC:
6433 	case PROXY_ERROR_VERSION:
6434 		return ERR_PROXY_ERROR;
6435 	case PROXY_ERROR_CANCELED:
6436 		return ERR_USER_CANCEL;
6437 	case PROXY_ERROR_CONNECTION:
6438 		return ERR_PROXY_CONNECT_FAILED;
6439 	case PROXY_ERROR_TARGET:
6440 		return ERR_CONNECT_FAILED;
6441 	case PROXY_ERROR_DISCONNECTED:
6442 		return ERR_DISCONNECTED;
6443 	case PROXY_ERROR_AUTHENTICATION:
6444 		return ERR_PROXY_AUTH_FAILED;
6445 	default:
6446 		return ERR_INTERNAL_ERROR;
6447 	}
6448 }
6449 
6450 // TCP connection function
TcpConnectEx3(char * hostname,UINT port,UINT timeout,bool * cancel_flag,void * hWnd,bool no_nat_t,UINT * nat_t_error_code,bool try_start_ssl,IP * ret_ip)6451 SOCK *TcpConnectEx3(char *hostname, UINT port, UINT timeout, bool *cancel_flag, void *hWnd, bool no_nat_t, UINT *nat_t_error_code, bool try_start_ssl, IP *ret_ip)
6452 {
6453 #ifdef	OS_WIN32
6454 	if (hWnd == NULL)
6455 	{
6456 #endif	// OS_WIN32
6457 		return ConnectEx4(hostname, port, timeout, cancel_flag, (no_nat_t ? NULL : VPN_RUDP_SVC_NAME), nat_t_error_code, try_start_ssl, true, ret_ip);
6458 #ifdef	OS_WIN32
6459 	}
6460 	else
6461 	{
6462 		return WinConnectEx3((HWND)hWnd, hostname, port, timeout, 0, NULL, NULL, nat_t_error_code, (no_nat_t ? NULL : VPN_RUDP_SVC_NAME), try_start_ssl);
6463 	}
6464 #endif	// OS_WIN32
6465 }
6466 
6467 // Connect with TCP/IP
TcpIpConnectEx(char * hostname,UINT port,bool * cancel_flag,void * hWnd,UINT * nat_t_error_code,bool no_nat_t,bool try_start_ssl,IP * ret_ip)6468 SOCK *TcpIpConnectEx(char *hostname, UINT port, bool *cancel_flag, void *hWnd, UINT *nat_t_error_code, bool no_nat_t, bool try_start_ssl, IP *ret_ip)
6469 {
6470 	SOCK *s = NULL;
6471 	UINT dummy_int = 0;
6472 	// Validate arguments
6473 	if (nat_t_error_code == NULL)
6474 	{
6475 		nat_t_error_code = &dummy_int;
6476 	}
6477 	*nat_t_error_code = 0;
6478 	if (hostname == NULL || port == 0)
6479 	{
6480 		return NULL;
6481 	}
6482 
6483 	s = TcpConnectEx3(hostname, port, 0, cancel_flag, hWnd, no_nat_t, nat_t_error_code, try_start_ssl, ret_ip);
6484 	if (s == NULL)
6485 	{
6486 		return NULL;
6487 	}
6488 
6489 	return s;
6490 }
6491 
6492 // Protocol routine initialization
InitProtocol()6493 void InitProtocol()
6494 {
6495 }
6496 
6497 // Release the protocol routine
FreeProtocol()6498 void FreeProtocol()
6499 {
6500 }
6501 
6502 // Create a Hello packet
PackHello(void * random,UINT ver,UINT build,char * server_str)6503 PACK *PackHello(void *random, UINT ver, UINT build, char *server_str)
6504 {
6505 	PACK *p;
6506 	// Validate arguments
6507 	if (random == NULL || server_str == NULL)
6508 	{
6509 		return NULL;
6510 	}
6511 
6512 	p = NewPack();
6513 	PackAddStr(p, "hello", server_str);
6514 	PackAddInt(p, "version", ver);
6515 	PackAddInt(p, "build", build);
6516 	PackAddData(p, "random", random, SHA1_SIZE);
6517 
6518 	return p;
6519 }
6520 
6521 // Interpret the Hello packet
GetHello(PACK * p,void * random,UINT * ver,UINT * build,char * server_str,UINT server_str_size)6522 bool GetHello(PACK *p, void *random, UINT *ver, UINT *build, char *server_str, UINT server_str_size)
6523 {
6524 	// Validate arguments
6525 	if (p == NULL || random == NULL || ver == NULL || server_str == NULL)
6526 	{
6527 		return false;
6528 	}
6529 
6530 	if (PackGetStr(p, "hello", server_str, server_str_size) == false)
6531 	{
6532 		return false;
6533 	}
6534 	*ver = PackGetInt(p, "version");
6535 	*build = PackGetInt(p, "build");
6536 	if (PackGetDataSize(p, "random") != SHA1_SIZE)
6537 	{
6538 		return false;
6539 	}
6540 	if (PackGetData(p, "random", random) == false)
6541 	{
6542 		return false;
6543 	}
6544 
6545 	return true;
6546 }
6547 
6548 // Get the authentication method from PACK
GetAuthTypeFromPack(PACK * p)6549 UINT GetAuthTypeFromPack(PACK *p)
6550 {
6551 	// Validate arguments
6552 	if (p == NULL)
6553 	{
6554 		return 0;
6555 	}
6556 
6557 	return PackGetInt(p, "authtype");
6558 }
6559 
6560 // Get the HUB name and the user name from the PACK
GetHubnameAndUsernameFromPack(PACK * p,char * username,UINT username_size,char * hubname,UINT hubname_size)6561 bool GetHubnameAndUsernameFromPack(PACK *p, char *username, UINT username_size,
6562 								   char *hubname, UINT hubname_size)
6563 {
6564 	// Validate arguments
6565 	if (p == NULL || username == NULL || hubname == NULL)
6566 	{
6567 		return false;
6568 	}
6569 
6570 	if (PackGetStr(p, "username", username, username_size) == false)
6571 	{
6572 		return false;
6573 	}
6574 	if (PackGetStr(p, "hubname", hubname, hubname_size) == false)
6575 	{
6576 		return false;
6577 	}
6578 	return true;
6579 }
6580 
6581 // Get the protocol from PACK
GetProtocolFromPack(PACK * p)6582 UINT GetProtocolFromPack(PACK *p)
6583 {
6584 	// Validate arguments
6585 	if (p == NULL)
6586 	{
6587 		return 0;
6588 	}
6589 
6590 #if	0
6591 	return PackGetInt(p, "protocol");
6592 #else
6593 	// Limit to the TCP protocol in the current version
6594 	return CONNECTION_TCP;
6595 #endif
6596 }
6597 
6598 // Get the method from the PACK
GetMethodFromPack(PACK * p,char * method,UINT size)6599 bool GetMethodFromPack(PACK *p, char *method, UINT size)
6600 {
6601 	// Validate arguments
6602 	if (p == NULL || method == NULL || size == 0)
6603 	{
6604 		return false;
6605 	}
6606 
6607 	return PackGetStr(p, "method", method, size);
6608 }
6609 
6610 // Generate a packet of certificate authentication login
PackLoginWithCert(char * hubname,char * username,X * x,void * sign,UINT sign_size)6611 PACK *PackLoginWithCert(char *hubname, char *username, X *x, void *sign, UINT sign_size)
6612 {
6613 	PACK *p;
6614 	BUF *b;
6615 	// Validate arguments
6616 	if (hubname == NULL || username == NULL)
6617 	{
6618 		return NULL;
6619 	}
6620 
6621 	p = NewPack();
6622 	PackAddStr(p, "method", "login");
6623 	PackAddStr(p, "hubname", hubname);
6624 	PackAddStr(p, "username", username);
6625 	PackAddInt(p, "authtype", CLIENT_AUTHTYPE_CERT);
6626 
6627 	// Certificate
6628 	b = XToBuf(x, false);
6629 	PackAddData(p, "cert", b->Buf, b->Size);
6630 	FreeBuf(b);
6631 
6632 	// Signature data
6633 	PackAddData(p, "sign", sign, sign_size);
6634 
6635 	return p;
6636 }
6637 
6638 // Generate a packet of plain text password authentication login
PackLoginWithPlainPassword(char * hubname,char * username,void * plain_password)6639 PACK *PackLoginWithPlainPassword(char *hubname, char *username, void *plain_password)
6640 {
6641 	PACK *p;
6642 	// Validate arguments
6643 	if (hubname == NULL || username == NULL)
6644 	{
6645 		return NULL;
6646 	}
6647 
6648 	p = NewPack();
6649 	PackAddStr(p, "method", "login");
6650 	PackAddStr(p, "hubname", hubname);
6651 	PackAddStr(p, "username", username);
6652 	PackAddInt(p, "authtype", CLIENT_AUTHTYPE_PLAIN_PASSWORD);
6653 	PackAddStr(p, "plain_password", plain_password);
6654 
6655 	return p;
6656 }
6657 
6658 // Generate a packet of WireGuard key login
PackLoginWithWireGuardKey(char * key)6659 PACK *PackLoginWithWireGuardKey(char *key)
6660 {
6661 	PACK *p;
6662 	// Validate arguments
6663 	if (key == NULL)
6664 	{
6665 		return NULL;
6666 	}
6667 
6668 	p = NewPack();
6669 	PackAddStr(p, "method", "login");
6670 	PackAddInt(p, "authtype", AUTHTYPE_WIREGUARD_KEY);
6671 	PackAddStr(p, "key", key);
6672 
6673 	return p;
6674 }
6675 
6676 // Generate a packet of OpenVPN certificate login
PackLoginWithOpenVPNCertificate(char * hubname,char * username,X * x)6677 PACK *PackLoginWithOpenVPNCertificate(char *hubname, char *username, X *x)
6678 {
6679 	PACK *p;
6680 	char cn_username[128];
6681 	BUF *cert_buf = NULL;
6682 	// Validate arguments
6683 	if (hubname == NULL || username == NULL || x == NULL)
6684 	{
6685 		return NULL;
6686 	}
6687 
6688 	p = NewPack();
6689 	PackAddStr(p, "method", "login");
6690 	PackAddStr(p, "hubname", hubname);
6691 
6692 	if (IsEmptyStr(username))
6693 	{
6694 		if (x->subject_name == NULL)
6695 		{
6696 			FreePack(p);
6697 			return NULL;
6698 		}
6699 		UniToStr(cn_username, sizeof(cn_username), x->subject_name->CommonName);
6700 		PackAddStr(p, "username", cn_username);
6701 	}
6702 	else
6703 	{
6704 		PackAddStr(p, "username", username);
6705 	}
6706 
6707 	PackAddInt(p, "authtype", AUTHTYPE_OPENVPN_CERT);
6708 
6709 	cert_buf = XToBuf(x, false);
6710 	PackAddBuf(p, "cert", cert_buf);
6711 	FreeBuf(cert_buf);
6712 
6713 	return p;
6714 }
6715 
6716 // Create a packet of password authentication login
PackLoginWithPassword(char * hubname,char * username,void * secure_password)6717 PACK *PackLoginWithPassword(char *hubname, char *username, void *secure_password)
6718 {
6719 	PACK *p;
6720 	// Validate arguments
6721 	if (hubname == NULL || username == NULL)
6722 	{
6723 		return NULL;
6724 	}
6725 
6726 	p = NewPack();
6727 	PackAddStr(p, "method", "login");
6728 	PackAddStr(p, "hubname", hubname);
6729 	PackAddStr(p, "username", username);
6730 	PackAddInt(p, "authtype", CLIENT_AUTHTYPE_PASSWORD);
6731 	PackAddData(p, "secure_password", secure_password, SHA1_SIZE);
6732 
6733 	return p;
6734 }
6735 
6736 // Create a packet for anonymous login
PackLoginWithAnonymous(char * hubname,char * username)6737 PACK *PackLoginWithAnonymous(char *hubname, char *username)
6738 {
6739 	PACK *p;
6740 	// Validate arguments
6741 	if (hubname == NULL || username == NULL)
6742 	{
6743 		return NULL;
6744 	}
6745 
6746 	p = NewPack();
6747 	PackAddStr(p, "method", "login");
6748 	PackAddStr(p, "hubname", hubname);
6749 	PackAddStr(p, "username", username);
6750 	PackAddInt(p, "authtype", CLIENT_AUTHTYPE_ANONYMOUS);
6751 
6752 	return p;
6753 }
6754 
6755 // Create a packet for the additional connection
PackAdditionalConnect(UCHAR * session_key)6756 PACK *PackAdditionalConnect(UCHAR *session_key)
6757 {
6758 	PACK *p;
6759 	// Validate arguments
6760 	if (session_key == NULL)
6761 	{
6762 		return NULL;
6763 	}
6764 
6765 	p = NewPack();
6766 	PackAddStr(p, "method", "additional_connect");
6767 	PackAddData(p, "session_key", session_key, SHA1_SIZE);
6768 
6769 	return p;
6770 }
6771