1 /* -*- c-basic-offset: 8 -*-
2 rdesktop: A Remote Desktop Protocol client.
3 Generic utility functions
4 Copyright 2013-2019 Henrik Andersson <hean01@cendio.se> for Cendio AB
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <sys/stat.h>
23 #include <errno.h>
24 #include <iconv.h>
25 #include <stdarg.h>
26 #include <assert.h>
27
28 #include "rdesktop.h"
29
30 #include "utils.h"
31
32 extern char g_codepage[16];
33
34 static RD_BOOL g_iconv_works = True;
35
36 uint32
utils_djb2_hash(const char * str)37 utils_djb2_hash(const char *str)
38 {
39 uint8 c;
40 uint8 *pstr;
41 uint32 hash = 5381;
42
43 pstr = (uint8 *) str;
44 while ((c = *pstr++))
45 {
46 hash = ((hash << 5) + hash) + c;
47 }
48 return hash;
49 }
50
51 char *
utils_string_escape(const char * str)52 utils_string_escape(const char *str)
53 {
54 const char *p;
55 char *pe, *e, esc[4];
56 size_t es;
57 int cnt;
58
59 /* count indices */
60 cnt = 0;
61 p = str;
62 while (*(p++) != '\0')
63 if ((unsigned char) *p < 32 || *p == '%')
64 cnt++;
65
66 /* if no characters needs escaping return copy of str */
67 if (cnt == 0)
68 return strdup(str);
69
70 /* allocate new mem for result */
71 es = strlen(str) + (cnt * 3) + 1;
72 pe = e = xmalloc(es);
73 memset(e, 0, es);
74 p = str;
75 while (*p != '\0')
76 {
77 if ((unsigned char) *p < 32 || *p == '%')
78 {
79 snprintf(esc, 4, "%%%02X", *p);
80 memcpy(pe, esc, 3);
81 pe += 3;
82 }
83 else
84 {
85 *pe = *p;
86 pe++;
87 }
88
89 p++;
90 }
91
92 return e;
93 }
94
95 char *
utils_string_unescape(const char * str)96 utils_string_unescape(const char *str)
97 {
98 char *ns, *ps, *pd;
99 unsigned char c;
100
101 ns = xmalloc(strlen(str) + 1);
102 memcpy(ns, str, strlen(str) + 1);
103 ps = pd = ns;
104
105 while (*ps != '\0')
106 {
107 /* check if found escaped character */
108 if (ps[0] == '%')
109 {
110 if (sscanf(ps, "%%%2hhX", &c) == 1)
111 {
112 pd[0] = (char) c;
113 ps += 3;
114 pd++;
115 continue;
116 }
117 }
118
119 /* just copy over the char */
120 *pd = *ps;
121 ps++;
122 pd++;
123 }
124 pd[0] = '\0';
125
126 return ns;
127 }
128
129 int
utils_mkdir_safe(const char * path,int mask)130 utils_mkdir_safe(const char *path, int mask)
131 {
132 int res = 0;
133 struct stat st;
134
135 res = stat(path, &st);
136 if (res == -1)
137 return mkdir(path, mask);
138
139 if (!S_ISDIR(st.st_mode))
140 {
141 errno = EEXIST;
142 return -1;
143 }
144
145 return 0;
146 }
147
148 int
utils_mkdir_p(const char * path,int mask)149 utils_mkdir_p(const char *path, int mask)
150 {
151 int res;
152 char *ptok;
153 char pt[PATH_MAX];
154 char bp[PATH_MAX];
155
156 if (!path || strlen(path) == 0)
157 {
158 errno = EINVAL;
159 return -1;
160 }
161 if (strlen(path) > PATH_MAX)
162 {
163 errno = E2BIG;
164 return -1;
165 }
166
167 res = 0;
168 pt[0] = bp[0] = '\0';
169 strcpy(bp, path);
170
171 ptok = strtok(bp, "/");
172 if (ptok == NULL)
173 return utils_mkdir_safe(path, mask);
174
175 do
176 {
177 if (ptok != bp)
178 strcat(pt, "/");
179
180 strcat(pt, ptok);
181 res = utils_mkdir_safe(pt, mask);
182 if (res != 0)
183 return res;
184
185 }
186 while ((ptok = strtok(NULL, "/")) != NULL);
187
188 return 0;
189 }
190
191 /* Convert from system locale string to UTF-8 */
192 int
utils_locale_to_utf8(const char * src,size_t is,char * dest,size_t os)193 utils_locale_to_utf8(const char *src, size_t is, char *dest, size_t os)
194 {
195 static iconv_t *iconv_h = (iconv_t) - 1;
196 if (strncmp(g_codepage, "UTF-8", strlen("UTF-8")) == 0)
197 goto pass_trough_as_is;
198
199 if (g_iconv_works == False)
200 goto pass_trough_as_is;
201
202 /* if not already initialize */
203 if (iconv_h == (iconv_t) - 1)
204 {
205 if ((iconv_h = iconv_open("UTF-8", g_codepage)) == (iconv_t) - 1)
206 {
207 logger(Core, Warning,
208 "utils_string_to_utf8(), iconv_open[%s -> %s] fail %p", g_codepage,
209 "UTF-8", iconv_h);
210
211 g_iconv_works = False;
212 goto pass_trough_as_is;
213 }
214 }
215
216 /* convert string */
217 if (iconv(iconv_h, (char **) &src, &is, &dest, &os) == (size_t) - 1)
218 {
219 iconv_close(iconv_h);
220 iconv_h = (iconv_t) - 1;
221 logger(Core, Warning, "utils_string_to_utf8, iconv(1) fail, errno %d", errno);
222
223 g_iconv_works = False;
224 goto pass_trough_as_is;
225 }
226
227 /* Out couldn't hold the entire conversion */
228 if (is != 0)
229 return -1;
230
231 pass_trough_as_is:
232 /* can dest hold strcpy of src */
233 if (os < (strlen(src) + 1))
234 return -1;
235
236 memcpy(dest, src, strlen(src) + 1);
237 return 0;
238 }
239
240
241 void
utils_calculate_dpi_scale_factors(uint32 width,uint32 height,uint32 dpi,uint32 * physwidth,uint32 * physheight,uint32 * desktopscale,uint32 * devicescale)242 utils_calculate_dpi_scale_factors(uint32 width, uint32 height, uint32 dpi,
243 uint32 * physwidth, uint32 * physheight,
244 uint32 * desktopscale, uint32 * devicescale)
245 {
246 *physwidth = *physheight = *desktopscale = *devicescale = 0;
247
248 if (dpi > 0)
249 {
250 *physwidth = width * 254 / (dpi * 10);
251 *physheight = height * 254 / (dpi * 10);
252
253 /* the spec calls this out as being valid for range
254 100-500 but I doubt the upper range is accurate */
255 *desktopscale = dpi < 96 ? 100 : (dpi * 100 + 48) / 96;
256
257 /* the only allowed values for device scale factor are
258 100, 140, and 180. */
259 *devicescale = dpi < 134 ? 100 : (dpi < 173 ? 140 : 180);
260
261 }
262 }
263
264
265 void
utils_apply_session_size_limitations(uint32 * width,uint32 * height)266 utils_apply_session_size_limitations(uint32 * width, uint32 * height)
267 {
268 /* width MUST be even number */
269 *width -= (*width) % 2;
270
271 if (*width > 8192)
272 *width = 8192;
273 else if (*width < 200)
274 *width = 200;
275
276 if (*height > 8192)
277 *height = 8192;
278 else if (*height < 200)
279 *height = 200;
280 }
281
282 #define MAX_CHOICES 10
283 const char *
util_dialog_choice(const char * message,...)284 util_dialog_choice(const char *message, ...)
285 {
286 int i;
287 va_list ap;
288 char *p;
289 const char *choice;
290 char response[512];
291 const char *choices[MAX_CHOICES] = {0};
292
293 /* gather choices into array */
294 va_start(ap, message);
295 for (i = 0; i < MAX_CHOICES; i++)
296 {
297 choices[i] = va_arg(ap, const char *);
298 if (choices[i] == NULL)
299 break;
300 }
301 va_end(ap);
302
303 choice = NULL;
304 while (choice == NULL)
305 {
306 /* display message */
307 fprintf(stderr,"\n%s", message);
308
309 /* read input */
310 if (fgets(response, sizeof(response), stdin) != NULL)
311 {
312 /* strip final newline */
313 p = strchr(response, '\n');
314 if (p != NULL)
315 *p = 0;
316
317 for (i = 0; i < MAX_CHOICES; i++)
318 {
319 if (choices[i] == NULL)
320 break;
321
322 if (strcmp(response, choices[i]) == 0)
323 {
324 choice = choices[i];
325 break;
326 }
327 }
328 }
329 else
330 {
331 logger(Core, Error, "Failed to read response from stdin");
332 break;
333 }
334 }
335
336 return choice;
337 }
338
339 /*
340 * component logging
341 *
342 */
343
344 static char *level[] = {
345 "debug",
346 "verbose", /* Verbose message for end user, no prefixed lines */
347 "warning",
348 "error",
349 "notice" /* Normal messages for end user, no prefixed lines */
350 };
351
352 static char *subject[] = {
353 "UI",
354 "Keyboard",
355 "Clipboard",
356 "Sound",
357 "Protocol",
358 "Graphics",
359 "Core",
360 "SmartCard",
361 "Disk"
362 };
363
364 static log_level_t _logger_level = Warning;
365
366 #define DEFAULT_LOGGER_SUBJECTS (1 << Core)
367
368 #define ALL_LOGGER_SUBJECTS \
369 (1 << GUI) \
370 | (1 << Keyboard) \
371 | (1 << Clipboard) \
372 | (1 << Sound) \
373 | (1 << Protocol) \
374 | (1 << Graphics) \
375 | (1 << Core) \
376 | (1 << SmartCard) \
377 | (1 << Disk)
378
379
380 static int _logger_subjects = DEFAULT_LOGGER_SUBJECTS;
381
382 void
logger(log_subject_t s,log_level_t lvl,char * format,...)383 logger(log_subject_t s, log_level_t lvl, char *format, ...)
384 {
385 va_list ap;
386 char buf[1024];
387
388 // Do not log if message is below global log level
389 if (_logger_level > lvl)
390 return;
391
392 // Skip debug logging for non specified subjects
393 if (lvl < Verbose && !(_logger_subjects & (1 << s)))
394 return;
395
396 va_start(ap, format);
397 vsnprintf(buf, sizeof(buf), format, ap);
398
399 // Notice and Verbose messages goes without prefix
400 if (lvl == Notice || lvl == Verbose)
401 fprintf(stdout, "%s\n", buf);
402 else
403 fprintf(stderr, "%s(%s): %s\n", subject[s], level[lvl], buf);
404
405 fflush(stdout);
406
407 va_end(ap);
408 }
409
410 void
logger_set_verbose(int verbose)411 logger_set_verbose(int verbose)
412 {
413 if (_logger_level < Verbose)
414 return;
415
416 if (verbose)
417 _logger_level = Verbose;
418 else
419 _logger_level = Warning;
420 }
421
422 void
logger_set_subjects(char * subjects)423 logger_set_subjects(char *subjects)
424 {
425 int clear;
426 int bit;
427 char *pcs;
428 char *token;
429
430 if (!subjects || !strlen(subjects))
431 return;
432
433 pcs = strdup(subjects);
434
435 token = strtok(pcs, ",");
436 if (token == NULL)
437 {
438 free(pcs);
439 return;
440 }
441
442 _logger_subjects = 0;
443
444 do
445 {
446
447 if (token == NULL)
448 break;
449
450 bit = 0;
451 clear = (token[0] == '-') ? 1 : 0;
452
453 if (clear == 1)
454 token++;
455
456 if (strcmp(token, "All") == 0)
457 _logger_subjects |= ALL_LOGGER_SUBJECTS;
458 else if (strcmp(token, "UI") == 0)
459 bit = (1 << GUI);
460 else if (strcmp(token, "Keyboard") == 0)
461 bit = (1 << Keyboard);
462 else if (strcmp(token, "Clipboard") == 0)
463 bit = (1 << Clipboard);
464 else if (strcmp(token, "Sound") == 0)
465 bit = (1 << Sound);
466 else if (strcmp(token, "Protocol") == 0)
467 bit = (1 << Protocol);
468 else if (strcmp(token, "Graphics") == 0)
469 bit = (1 << Graphics);
470 else if (strcmp(token, "Core") == 0)
471 bit = (1 << Core);
472 else if (strcmp(token, "SmartCard") == 0)
473 bit = (1 << SmartCard);
474 else if (strcmp(token, "Disk") == 0)
475 bit = (1 << Disk);
476 else
477 continue;
478
479 // set or clear logger subject bit
480 if (clear)
481 _logger_subjects &= ~bit;
482 else
483 _logger_subjects |= bit;
484
485 }
486 while ((token = strtok(NULL, ",")) != NULL);
487
488 _logger_level = Debug;
489
490 free(pcs);
491 }
492
493 static size_t
_utils_data_to_hex(uint8 * data,size_t len,char * out,size_t size)494 _utils_data_to_hex(uint8 *data, size_t len, char *out, size_t size)
495 {
496 size_t i;
497 char hex[4];
498
499 assert((len * 2) < size);
500
501 memset(out, 0, size);
502 for (i = 0; i < len; i++)
503 {
504 snprintf(hex, sizeof(hex), "%.2x", data[i]);
505 strcat(out, hex);
506 }
507
508 return (len*2);
509 }
510
511 static size_t
_utils_oid_to_string(const char * oid,char * out,size_t size)512 _utils_oid_to_string(const char *oid, char *out, size_t size)
513 {
514 memset(out, 0, size);
515 if (strcmp(oid, "0.9.2342.19200300.100.1.25") == 0) {
516 snprintf(out, size, "%s", "DC");
517 }
518 else if (strcmp(oid, "2.5.4.3") == 0) {
519 snprintf(out, size, "%s", "CN");
520 }
521 else if (strcmp(oid, "1.2.840.113549.1.1.13") == 0)
522 {
523 snprintf(out, size, "%s", "sha512WithRSAEncryption");
524 }
525 else
526 {
527 snprintf(out, size, "%s", oid);
528 }
529
530 return strlen(out);
531 }
532
533 static int
_utils_dn_to_string(gnutls_x509_dn_t dn,RD_BOOL exclude_oid,char * out,size_t size)534 _utils_dn_to_string(gnutls_x509_dn_t dn, RD_BOOL exclude_oid,
535 char *out, size_t size)
536 {
537 int i, j;
538 char buf[128] = {0};
539 char name[64] = {0};
540 char result[1024] = {0};
541 size_t left;
542 gnutls_x509_ava_st ava;
543
544 left = sizeof(result);
545
546 for (j = 0; j < 100; j++)
547 {
548 for (i = 0; i < 100; i++)
549 {
550 if (gnutls_x509_dn_get_rdn_ava(dn, j, i, &ava) != 0)
551 {
552 break;
553 }
554
555 if (exclude_oid)
556 {
557 snprintf(buf, sizeof(buf), "%.*s", ava.value.size, ava.value.data);
558 strncat(result, buf, left);
559 left -= strlen(buf);
560 }
561 else
562 {
563 _utils_oid_to_string((char *)ava.oid.data, name, sizeof(name));
564 snprintf(buf, sizeof(buf), "%s%s=%.*s",
565 (j > 0)?", ":"", name, ava.value.size, ava.value.data);
566 strncat(result, buf, left);
567 left -= strlen(buf);
568 }
569 }
570
571 if (i == 0)
572 {
573 break;
574 }
575 }
576
577 snprintf(out, size, "%s", result);
578
579 return 0;
580 }
581
582 static void
_utils_cert_get_info(gnutls_x509_crt_t cert,char * out,size_t size)583 _utils_cert_get_info(gnutls_x509_crt_t cert, char *out, size_t size)
584 {
585 char buf[128];
586 size_t buf_size;
587 char digest[128];
588 gnutls_x509_dn_t dn;
589 time_t expire_ts, activated_ts;
590
591 char subject[256];
592 char issuer[256];
593 char valid_from[256];
594 char valid_to[256];
595 char sha1[256];
596 char sha256[256];
597
598 /* get subject */
599 gnutls_x509_crt_get_subject(cert, &dn);
600 if (_utils_dn_to_string(dn, False, buf, sizeof(buf)) == 0)
601 {
602 snprintf(subject, sizeof(subject), " Subject: %s", buf);
603 }
604
605 /* get issuer */
606 gnutls_x509_crt_get_issuer(cert, &dn);
607 if (_utils_dn_to_string(dn, False, buf, sizeof(buf)) == 0)
608 {
609 snprintf(issuer, sizeof(issuer), " Issuer: %s", buf);
610 }
611
612 /* get activation / expiration time */
613 activated_ts = gnutls_x509_crt_get_activation_time(cert);
614 snprintf(valid_from, sizeof(valid_from), " Valid From: %s", ctime(&activated_ts));
615
616 expire_ts = gnutls_x509_crt_get_expiration_time(cert);
617 snprintf(valid_to, sizeof(valid_to), " To: %s", ctime(&expire_ts));
618
619 /* get sha1 / sha256 fingerprint */
620 buf_size = sizeof(buf);
621 gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, buf, &buf_size);
622 _utils_data_to_hex((uint8 *)buf, buf_size, digest, sizeof(digest));
623 snprintf(sha1, sizeof(sha1), " sha1: %s", digest);
624
625 buf_size = sizeof(buf);
626 gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, buf, &buf_size);
627 _utils_data_to_hex((uint8 *)buf, buf_size, digest, sizeof(digest));
628 snprintf(sha256, sizeof(sha256), " sha256: %s", digest);
629
630 /* render cert info into out */
631 snprintf(out, size,
632 "%s\n"
633 "%s\n"
634 "%s"
635 "%s"
636 "\n"
637 " Certificate fingerprints:\n\n"
638 "%s\n"
639 "%s\n", subject, issuer, valid_from, valid_to, sha1, sha256);
640 }
641
642 static int
_utils_cert_san_to_string(gnutls_x509_crt_t cert,char * out,size_t size)643 _utils_cert_san_to_string(gnutls_x509_crt_t cert, char *out, size_t size)
644 {
645 int i, res;
646 char entries[1024] = {0};
647 char san[128] = {0};
648 ssize_t left;
649 size_t san_size;
650 unsigned int san_type, critical;
651
652 left = sizeof(entries);
653
654 for(i = 0; i < 50; i++)
655 {
656 san_size = sizeof(san);
657 res = gnutls_x509_crt_get_subject_alt_name2(cert, i, san, &san_size, &san_type, &critical);
658
659 /* break if there are no more SAN entries */
660 if (res <= 0)
661 break;
662
663 /* log if we cant handle more san entires in buffer */
664 if (left <= 0)
665 {
666 logger(Core, Warning, "%s(), buffer is full, at least one SAN entry is missing from list", __func__);
667 break;
668 }
669
670 /* add SAN entry to list */
671 switch(san_type)
672 {
673 case GNUTLS_SAN_IPADDRESS:
674 case GNUTLS_SAN_DNSNAME:
675
676 if (left < (ssize_t)sizeof(entries))
677 {
678 strncat(entries, ", ", left);
679 left -= 2;
680 }
681
682 strncat(entries, san, left);
683 left -= strlen(san);
684
685 break;
686 }
687 }
688
689 if (strlen(entries) == 0)
690 {
691 return 1;
692 }
693 snprintf(out, size, "%s", entries);
694
695 return 0;
696 }
697
698 static void
_utils_cert_get_status_report(gnutls_x509_crt_t cert,unsigned int status,RD_BOOL hostname_mismatch,const char * hostname,char * out,size_t size)699 _utils_cert_get_status_report(gnutls_x509_crt_t cert, unsigned int status,
700 RD_BOOL hostname_mismatch, const char *hostname,
701 char *out, size_t size)
702 {
703 int i;
704 char buf[1024];
705 char str[1024 + 64];
706
707 i = 1;
708
709 if (hostname_mismatch == True)
710 {
711 snprintf(buf, sizeof(buf),
712 " %d. The hostname used for this connection does not match any of the names\n"
713 " given in the certificate.\n\n"
714 " Hostname: %s\n"
715 , i++, hostname);
716 strncat(out, buf, size - 1);
717 size -= strlen(buf);
718
719 /* parse subject dn */
720 gnutls_x509_dn_t dn;
721 gnutls_x509_crt_get_subject(cert, &dn);
722
723 memset(buf, 0, sizeof(buf));
724 if (_utils_dn_to_string(dn, True, buf, sizeof(buf)) == 0)
725 {
726 snprintf(str, sizeof(str), " Common Name: %s\n", buf);
727 strncat(out, str, size);
728 size -= strlen(str);
729 }
730
731 /* get SAN entries */
732 if (_utils_cert_san_to_string(cert, buf, sizeof(buf)) == 0)
733 {
734 snprintf(str, sizeof(str), " Alternate names: %s\n", buf);
735 strncat(out, str, size);
736 size -= strlen(str);
737 }
738
739 strcat(out, "\n");
740 size -= 1;
741 }
742
743 if (status & GNUTLS_CERT_REVOKED) {
744 snprintf(buf, sizeof(buf),
745 " %d. Certificate is revoked by its authority\n\n", i++);
746 strncat(out, buf, size);
747 size -= strlen(buf);
748 }
749
750 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
751 snprintf(buf, sizeof(buf),
752 " %d. Certificate issuer is not trusted by this system.\n\n", i++);
753 strncat(out, buf, size);
754 size -= strlen(buf);
755
756 /* parse subject dn */
757 gnutls_x509_dn_t dn;
758 gnutls_x509_crt_get_issuer(cert, &dn);
759
760 memset(buf, 0, sizeof(buf));
761 if (_utils_dn_to_string(dn, False, buf, sizeof(buf)) == 0)
762 {
763 snprintf(str, sizeof(str), " Issuer: %s\n\n", buf);
764 strncat(out, str, size);
765 size -= strlen(str);
766 }
767 }
768
769 if (status & GNUTLS_CERT_SIGNER_NOT_CA) {
770 snprintf(buf, sizeof(buf),
771 " %d. Certificate signer is not a CA.\n\n", i++);
772 strncat(out, buf, size);
773 size -= strlen(buf);
774 }
775
776 if (status & GNUTLS_CERT_INSECURE_ALGORITHM) {
777 snprintf(buf, sizeof(buf),
778 " %d. Certificate was signed using an insecure algorithm.\n\n", i++);
779 strncat(out, buf, size);
780 size -= strlen(buf);
781 /* TODO: print algorithm*/
782 }
783
784 if (status & GNUTLS_CERT_NOT_ACTIVATED) {
785 snprintf(buf, sizeof(buf),
786 " %d. Certificate is not yet activated.\n\n", i++);
787 strncat(out, buf, size);
788 size -= strlen(buf);
789
790 time_t ts = gnutls_x509_crt_get_activation_time(cert);
791 snprintf(buf, sizeof(buf), " Valid From: %s\n\n", ctime(&ts));
792 strncat(out, buf, size);
793 size -= strlen(buf);
794 }
795
796 if (status & GNUTLS_CERT_EXPIRED) {
797 snprintf(buf, sizeof(buf),
798 " %d. Certificate has expired.\n\n", i++);
799 strncat(out, buf, size);
800 size -= strlen(buf);
801
802 time_t ts = gnutls_x509_crt_get_expiration_time(cert);
803 snprintf(buf, sizeof(buf), " Valid to: %s\n\n", ctime(&ts));
804 strncat(out, buf, size);
805 size -= strlen(buf);
806 }
807
808 if (status & GNUTLS_CERT_SIGNATURE_FAILURE) {
809 snprintf(buf, sizeof(buf),
810 " %d. Failed to verify the signature of the certificate.\n\n", i++);
811 strncat(out, buf, size);
812 size -= strlen(buf);
813 }
814
815 if (status & GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED) {
816 snprintf(buf, sizeof(buf),
817 " %d. Revocation data are old and have been superseded.\n\n", i++);
818 strncat(out, buf, size);
819 size -= strlen(buf);
820 }
821
822 if (status & GNUTLS_CERT_UNEXPECTED_OWNER) {
823 snprintf(buf, sizeof(buf),
824 " %d. The owner is not the expected one.\n\n", i++);
825 strncat(out, buf, size);
826 size -= strlen(buf);
827 }
828
829 if (status & GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE) {
830 snprintf(buf, sizeof(buf),
831 " %d. The revocation data have a future issue date.\n\n", i++);
832 strncat(out, buf, size);
833 size -= strlen(buf);
834 }
835
836 if (status & GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE) {
837 snprintf(buf, sizeof(buf),
838 " %d. The certificate's signer constraints were violated.\n\n", i++);
839 strncat(out, buf, size);
840 size -= strlen(buf);
841 }
842
843 if (status & GNUTLS_CERT_MISMATCH) {
844 snprintf(buf, sizeof(buf),
845 " %d. The certificate presented isn't the expected one (TOFU)\n\n", i++);
846 strncat(out, buf, size);
847 size -= strlen(buf);
848 }
849
850 #if GNUTLS_VERSION_NUMBER >= 0x030400
851 if (status & GNUTLS_CERT_PURPOSE_MISMATCH) {
852 snprintf(buf, sizeof(buf),
853 " %d. The certificate or an intermediate does not match the\n"
854 " intended purpose (extended key usage).\n\n", i++);
855 strncat(out, buf, size);
856 size -= strlen(buf);
857 }
858 #endif
859
860 #if GNUTLS_VERSION_NUMBER >= 0x030501
861 if (status & GNUTLS_CERT_MISSING_OCSP_STATUS) {
862 snprintf(buf, sizeof(buf),
863 " %d. The certificate requires the server to send the certifiate\n"
864 " status, but no status was received.\n\n", i++);
865 strncat(out, buf, size);
866 size -= strlen(buf);
867 }
868
869 if (status & GNUTLS_CERT_INVALID_OCSP_STATUS) {
870 snprintf(buf, sizeof(buf),
871 " %d. The received OCSP status response is invalid.\n\n", i++);
872 strncat(out, buf, size);
873 size -= strlen(buf);
874 }
875 #endif
876
877 #if GNUTLS_VERSION_NUMBER >= 0x030600
878 if (status & GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS) {
879 snprintf(buf, sizeof(buf),
880 " %d. The certificate has extensions marked as critical which are\n"
881 " not supported.\n\n", i++);
882 strncat(out, buf, size);
883 size -= strlen(buf);
884 }
885 #endif
886 }
887
888 static int
_utils_cert_store_get_filename(char * out,size_t size)889 _utils_cert_store_get_filename(char *out, size_t size)
890 {
891 int rv;
892 char *home;
893 char dir[PATH_MAX - 12];
894 struct stat sb;
895
896 home = getenv("HOME");
897
898 if (home == NULL)
899 return 1;
900
901 if (snprintf(dir, sizeof(dir) - 1, "%s/%s", home, ".local/share/rdesktop/certs/") > (int)sizeof(dir))
902 {
903 logger(Core, Error, "%s(), certificate store directory is truncated", __func__);
904 return 1;
905 }
906
907 if ((rv = stat(dir, &sb)) == -1)
908 {
909 if (errno == ENOENT)
910 {
911 if (rd_certcache_mkdir() == False) {
912 logger(Core, Error, "%s(), failed to create directory '%s'", __func__, dir);
913 return 1;
914 }
915 }
916 }
917 else
918 {
919 if ((sb.st_mode & S_IFMT) != S_IFDIR)
920 {
921 logger(Core, Error, "%s(), %s exists but it's not a directory",
922 __func__, dir);
923 return 1;
924 }
925 }
926
927 if (snprintf(out, size, "%s/known_certs", dir) > (int)size)
928 {
929 logger(Core, Error, "%s(), certificate store filename is truncated", __func__);
930 return 1;
931 }
932
933 return 0;
934 }
935
936 #define TRUST_CERT_PROMPT_TEXT "Do you trust this certificate (yes/no)? "
937 #define REVIEW_CERT_TEXT \
938 "Review the following certificate info before you trust it to be added as an exception.\n" \
939 "If you do not trust the certificate the connection atempt will be aborted:"
940
941 int
utils_cert_handle_exception(gnutls_session_t session,unsigned int status,RD_BOOL hostname_mismatch,const char * hostname)942 utils_cert_handle_exception(gnutls_session_t session, unsigned int status,
943 RD_BOOL hostname_mismatch, const char *hostname)
944 {
945 int rv;
946 int type;
947 time_t exp_time;
948 gnutls_x509_crt_t cert;
949 const gnutls_datum_t *cert_list;
950 unsigned int cert_list_size = 0;
951
952 char certcache_fn[PATH_MAX];
953 char cert_info[2048] = {0};
954 char cert_invalid_reasons[2048] = {0};
955 char message[8192] = {0};
956 const char *response;
957
958 /* get filename for certificate exception store */
959 if (_utils_cert_store_get_filename(certcache_fn, sizeof(certcache_fn)) != 0)
960 {
961 logger(Core, Error, "%s(), Failed to get certificate store file, "
962 "disabling exception handling.", __func__);
963 return 1;
964 }
965
966 type = gnutls_certificate_type_get(session);
967 if (type != GNUTLS_CRT_X509)
968 {
969 logger(Core, Error, "%s(), Certificate for session is not an x509 certificate, "
970 "disabling exception handling.", __func__);
971 return 1;
972 }
973
974
975 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
976 if (cert_list_size == 0)
977 {
978 logger(Core, Error, "%s(), Failed to get certificate, "
979 "disabling exception handling.", __func__);
980 return 1;
981 }
982
983 rv = gnutls_verify_stored_pubkey(certcache_fn, NULL, hostname, "rdesktop", type, &cert_list[0], 0);
984 if (rv == GNUTLS_E_SUCCESS)
985 {
986 /* Certificate found in store and matches server */
987 logger(Core, Warning, "Certificate received from server is NOT trusted by this system, "
988 "an exception has been added by the user to trust this specific certificate.");
989 return 0;
990 }
991 else if (rv != GNUTLS_E_CERTIFICATE_KEY_MISMATCH && rv != GNUTLS_E_NO_CERTIFICATE_FOUND)
992 {
993 /* Unhandled errors */
994 logger(Core, Error, "%s(), verification for host '%s' certificate failed. Error = 0x%x (%s)",
995 __func__, hostname, rv, gnutls_strerror(rv));
996 return 1;
997 }
998
999 /*
1000 * Give user possibility to add / update certificate to store
1001 */
1002
1003 gnutls_x509_crt_init(&cert);
1004 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1005 _utils_cert_get_info(cert, cert_info, sizeof(cert_info));
1006
1007 if (rv == GNUTLS_E_CERTIFICATE_KEY_MISMATCH)
1008 {
1009 /* Certificate from server mismatches the one in store */
1010
1011 snprintf(message, sizeof(message),
1012 "ATTENTION! Found a certificate stored for host '%s', but it does not match the certificate\n"
1013 "received from server.\n"
1014 REVIEW_CERT_TEXT
1015 "\n\n"
1016 "%s"
1017 "\n\n"
1018 TRUST_CERT_PROMPT_TEXT
1019 , hostname, cert_info);
1020
1021
1022 }
1023 else if (rv == GNUTLS_E_NO_CERTIFICATE_FOUND)
1024 {
1025 /* Certificate is not found in store, propose to add an exception */
1026 _utils_cert_get_status_report(cert, status, hostname_mismatch, hostname,
1027 cert_invalid_reasons, sizeof(cert_invalid_reasons));
1028
1029 snprintf(message, sizeof(message),
1030 "ATTENTION! The server uses and invalid security certificate which can not be trusted for\n"
1031 "the following identified reasons(s);\n\n"
1032 "%s"
1033 "\n"
1034 REVIEW_CERT_TEXT
1035 "\n\n"
1036 "%s"
1037 "\n\n"
1038 TRUST_CERT_PROMPT_TEXT,
1039 cert_invalid_reasons, cert_info);
1040 }
1041
1042 /* show dialog */
1043 response = util_dialog_choice(message, "no", "yes", NULL);
1044 if (strcmp(response, "no") == 0 || response == NULL)
1045 {
1046 return 1;
1047 }
1048
1049 /* user responded with yes, lets add certificate to store */
1050 logger(Core, Debug, "%s(), adding a new certificate for the host '%s'", __func__, hostname);
1051 exp_time = gnutls_x509_crt_get_expiration_time(cert);
1052 rv = gnutls_store_pubkey(certcache_fn, NULL, hostname, "rdesktop", type, &cert_list[0], exp_time, 0);
1053 if (rv != GNUTLS_E_SUCCESS)
1054 {
1055 logger(Core, Error, "%s(), failed to store certificate. error = 0x%x (%s)", __func__, rv, gnutls_strerror(rv));
1056 return 1;
1057 }
1058
1059 return 0;
1060 }
1061