FreeRDP
Loading...
Searching...
No Matches
passphrase.c
1
19
20#include <winpr/atexit.h>
21#include <winpr/environment.h>
22
23#include <freerdp/config.h>
24#include <freerdp/freerdp.h>
25
26#include <errno.h>
27#include <freerdp/utils/passphrase.h>
28
29#ifdef _WIN32
30
31#include <stdio.h>
32#include <string.h>
33#include <io.h>
34#include <conio.h>
35#include <wincred.h>
36
37static char read_chr(FILE* f)
38{
39 char chr;
40 const BOOL isTty = _isatty(_fileno(f));
41 if (isTty)
42 return fgetc(f);
43 if (fscanf_s(f, "%c", &chr, (UINT32)sizeof(char)) && !feof(f))
44 return chr;
45 return 0;
46}
47
48int freerdp_interruptible_getc(rdpContext* context, FILE* f)
49{
50 return read_chr(f);
51}
52
53const char* freerdp_passphrase_read(rdpContext* context, const char* prompt, char* buf,
54 size_t bufsiz, int from_stdin)
55{
56 if (bufsiz == 0)
57 {
58 errno = EINVAL;
59 return nullptr;
60 }
61
62 /* When /from-stdin is requested, read the password from stdin. The Unix
63 * counterpart (freerdp_passphrase_read_tty) does the same, suppressing
64 * terminal echo via tcsetattr; suppress console echo here via SetConsoleMode
65 * when stdin is an interactive console. On a pipe the echo bit is moot. */
66 if (from_stdin)
67 {
68 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
69 const BOOL isTty = _isatty(_fileno(stdin)) != 0;
70 DWORD origMode = 0;
71 BOOL echoSuppressed = FALSE;
72
73 if (isTty && hStdin && hStdin != INVALID_HANDLE_VALUE && GetConsoleMode(hStdin, &origMode))
74 {
75 if (SetConsoleMode(hStdin, origMode & ~(DWORD)ENABLE_ECHO_INPUT))
76 echoSuppressed = TRUE;
77 }
78
79 if (prompt)
80 {
81 (void)fputs(prompt, stdout);
82 (void)fflush(stdout);
83 }
84
85 WINPR_ASSERT(bufsiz <= INT32_MAX);
86 const char* rc = fgets(buf, (int)bufsiz, stdin);
87
88 if (echoSuppressed)
89 {
90 (void)SetConsoleMode(hStdin, origMode);
91 (void)fputc('\n', stdout);
92 (void)fflush(stdout);
93 }
94
95 if (!rc)
96 return nullptr;
97
98 buf[strcspn(buf, "\r\n")] = '\0';
99 return buf;
100 }
101
102 WCHAR UserNameW[CREDUI_MAX_USERNAME_LENGTH + 1] = { 'p', 'r', 'e', 'f', 'i',
103 'l', 'l', 'e', 'd', '\0' };
104 WCHAR PasswordW[CREDUI_MAX_PASSWORD_LENGTH + 1] = WINPR_C_ARRAY_INIT;
105 BOOL fSave = FALSE;
106 DWORD dwFlags = 0;
107 WCHAR* promptW = ConvertUtf8ToWCharAlloc(prompt, nullptr);
108 const DWORD status =
109 CredUICmdLinePromptForCredentialsW(promptW, nullptr, 0, UserNameW, ARRAYSIZE(UserNameW),
110 PasswordW, ARRAYSIZE(PasswordW), &fSave, dwFlags);
111 free(promptW);
112 if (ConvertWCharNToUtf8(PasswordW, ARRAYSIZE(PasswordW), buf, bufsiz) < 0)
113 return nullptr;
114 return buf;
115}
116
117const char* freerdp_passphrase_from_env(WINPR_ATTR_UNUSED rdpContext* context,
118 WINPR_ATTR_UNUSED const char* prompt,
119 WINPR_ATTR_UNUSED char* buf,
120 WINPR_ATTR_UNUSED size_t bufsiz)
121{
122 return nullptr;
123}
124
125const char* freerdp_passphrase_read_tty(WINPR_ATTR_UNUSED rdpContext* context,
126 WINPR_ATTR_UNUSED const char* prompt,
127 WINPR_ATTR_UNUSED char* buf,
128 WINPR_ATTR_UNUSED size_t bufsiz,
129 WINPR_ATTR_UNUSED int from_stdin)
130{
131 return nullptr;
132}
133
134#elif !defined(ANDROID)
135
136#include <fcntl.h>
137#include <stdio.h>
138#include <string.h>
139#include <sys/stat.h>
140#include <sys/wait.h>
141#include <termios.h>
142#include <unistd.h>
143#include <freerdp/utils/signal.h>
144#include <freerdp/log.h>
145#if defined(WINPR_HAVE_POLL_H) && !defined(__APPLE__)
146#include <poll.h>
147#else
148#include <time.h>
149#include <sys/select.h>
150#endif
151
152#define TAG FREERDP_TAG("utils.passphrase")
153
154static int wait_for_fd(int fd, int timeout)
155{
156 int status = 0;
157#if defined(WINPR_HAVE_POLL_H) && !defined(__APPLE__)
158 struct pollfd pollset = WINPR_C_ARRAY_INIT;
159 pollset.fd = fd;
160 pollset.events = POLLIN;
161 pollset.revents = 0;
162
163 do
164 {
165 status = poll(&pollset, 1, timeout);
166 } while ((status < 0) && (errno == EINTR));
167
168#else
169 fd_set rset = WINPR_C_ARRAY_INIT;
170 struct timeval tv = WINPR_C_ARRAY_INIT;
171 FD_ZERO(&rset);
172 FD_SET(fd, &rset);
173
174 if (timeout)
175 {
176 tv.tv_sec = timeout / 1000;
177 tv.tv_usec = (timeout % 1000) * 1000;
178 }
179
180 do
181 {
182 status = select(fd + 1, &rset, nullptr, nullptr, timeout ? &tv : nullptr);
183 } while ((status < 0) && (errno == EINTR));
184
185#endif
186 return status;
187}
188
189static void replace_char(char* buffer, WINPR_ATTR_UNUSED size_t buffer_len, const char* toreplace)
190{
191 while (*toreplace != '\0')
192 {
193 char* ptr = nullptr;
194 while ((ptr = strrchr(buffer, *toreplace)) != nullptr)
195 *ptr = '\0';
196 toreplace++;
197 }
198}
199
200const char* freerdp_passphrase_read_tty(rdpContext* context, const char* prompt, char* buf,
201 size_t bufsiz, int from_stdin)
202{
203 BOOL terminal_needs_reset = FALSE;
204 char term_name[L_ctermid] = WINPR_C_ARRAY_INIT;
205
206 FILE* fout = nullptr;
207
208 if (bufsiz == 0)
209 {
210 errno = EINVAL;
211 return nullptr;
212 }
213
214 ctermid(term_name);
215 int terminal_fildes = 0;
216 if (from_stdin || (strcmp(term_name, "") == 0))
217 {
218 fout = stdout;
219 terminal_fildes = STDIN_FILENO;
220 }
221 else
222 {
223 const int term_file = open(term_name, O_RDWR);
224 if (term_file < 0)
225 {
226 fout = stdout;
227 terminal_fildes = STDIN_FILENO;
228 }
229 else
230 {
231 fout = fdopen(term_file, "w");
232 if (!fout)
233 {
234 close(term_file);
235 return nullptr;
236 }
237 terminal_fildes = term_file;
238 }
239 }
240
241 struct termios orig_flags = WINPR_C_ARRAY_INIT;
242 if (tcgetattr(terminal_fildes, &orig_flags) != -1)
243 {
244 struct termios new_flags = WINPR_C_ARRAY_INIT;
245 new_flags = orig_flags;
246 new_flags.c_lflag &= (uint32_t)~ECHO;
247 new_flags.c_lflag |= ECHONL;
248 terminal_needs_reset = TRUE;
249 if (tcsetattr(terminal_fildes, TCSAFLUSH, &new_flags) == -1)
250 terminal_needs_reset = FALSE;
251 }
252
253 FILE* fp = fdopen(terminal_fildes, "r");
254 if (!fp)
255 goto error;
256
257 if (isatty(fileno(fp)))
258 {
259 (void)fprintf(fout, "%s", prompt);
260 (void)fflush(fout);
261 }
262
263 {
264 char* ptr = nullptr;
265 size_t ptr_len = 0;
266 const SSIZE_T res = freerdp_interruptible_get_line(context, &ptr, &ptr_len, fp);
267 if (res < 0)
268 goto error;
269
270 replace_char(ptr, ptr_len, "\r\n");
271
272 strncpy(buf, ptr, MIN(bufsiz, ptr_len));
273 free(ptr);
274 }
275
276 if (terminal_needs_reset)
277 {
278 if (tcsetattr(terminal_fildes, TCSAFLUSH, &orig_flags) == -1)
279 goto error;
280 }
281
282 if (terminal_fildes != STDIN_FILENO)
283 (void)fclose(fp);
284
285 return buf;
286
287error:
288{
289 // NOLINTNEXTLINE(clang-analyzer-unix.Stream)
290 int saved_errno = errno;
291 if (terminal_needs_reset)
292 (void)tcsetattr(terminal_fildes, TCSAFLUSH, &orig_flags);
293
294 if (terminal_fildes != STDIN_FILENO)
295 {
296 if (fp)
297 (void)fclose(fp);
298 }
299 // NOLINTNEXTLINE(clang-analyzer-unix.Stream)
300 errno = saved_errno;
301}
302
303 return nullptr;
304}
305
306/* Escape a string for use inside a single quoted shell word.
307 *
308 * Between single quotes the shell treats only the single quote itself special, so replace each
309 * one with '\'' (close the quoting, add an escaped quote, reopen the quoting)
310 */
311WINPR_ATTR_MALLOC(winpr_zfree, 1)
312static char* escape_single_quoted(const char* str)
313{
314 static const char quote[] = "'\\''";
315 const size_t quotelen = sizeof(quote) - 1;
316
317 if (!str)
318 str = "";
319
320 size_t len = 1;
321 for (const char* cur = str; *cur != '\0'; cur++)
322 len += (*cur == '\'') ? quotelen : 1;
323
324 char* escaped = calloc(len, sizeof(char));
325 if (!escaped)
326 return nullptr;
327
328 char* dst = escaped;
329 for (const char* cur = str; *cur != '\0'; cur++)
330 {
331 if (*cur == '\'')
332 {
333 memcpy(dst, quote, quotelen);
334 dst += quotelen;
335 }
336 else
337 *dst++ = *cur;
338 }
339 return escaped;
340}
341
342static const char* freerdp_passphrase_read_askpass(const char* prompt, char* buf, size_t bufsiz,
343 char const* askpass_env)
344{
345 char* command = nullptr;
346 size_t commandlen = 0;
347
348 /* The prompt may contain data from untrusted sources (e.g. a server name), so it must not
349 * be able to terminate the quoted argument passed to the askpass program.
350 * The command is allocated as truncation would cut off the closing quote. */
351 char* escaped = escape_single_quoted(prompt);
352 if (!escaped)
353 return nullptr;
354
355 (void)winpr_asprintf(&command, &commandlen, "%s 'FreeRDP authentication\n%s'", askpass_env,
356 escaped);
357 winpr_zfree(escaped);
358 if (!command)
359 return nullptr;
360
361 // NOLINTNEXTLINE(clang-analyzer-optin.taint.GenericTaint,bugprone-command-processor)
362 FILE* askproc = popen(command, "r");
363 winpr_zfree(command);
364 if (!askproc)
365 return nullptr;
366 WINPR_ASSERT(bufsiz <= INT32_MAX);
367 if (fgets(buf, (int)bufsiz, askproc) != nullptr)
368 buf[strcspn(buf, "\r\n")] = '\0';
369 else
370 buf = nullptr;
371 const int status = pclose(askproc);
372 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
373 buf = nullptr;
374
375 return buf;
376}
377
378const char* freerdp_passphrase_from_env(WINPR_ATTR_UNUSED rdpContext* context, const char* prompt,
379 char* buf, size_t bufsiz)
380{
381 // NOLINTNEXTLINE(concurrency-mt-unsafe)
382 const char* askpass_env = getenv("FREERDP_ASKPASS");
383 if (!askpass_env)
384 return nullptr;
385 return freerdp_passphrase_read_askpass(prompt, buf, bufsiz, askpass_env);
386}
387
388const char* freerdp_passphrase_read(rdpContext* context, const char* prompt, char* buf,
389 size_t bufsiz, int from_stdin)
390{
391 const char* askpass_env = freerdp_passphrase_from_env(context, prompt, buf, bufsiz);
392 if (askpass_env)
393 return askpass_env;
394
395 return freerdp_passphrase_read_tty(context, prompt, buf, bufsiz, from_stdin);
396}
397
398static BOOL set_terminal_nonblock(int ifd, BOOL nonblock);
399
400static void restore_terminal(void)
401{
402 (void)set_terminal_nonblock(-1, FALSE);
403}
404
405BOOL set_terminal_nonblock(int ifd, BOOL nonblock)
406{
407 static int fd = -1;
408 static bool registered = false;
409 static int orig = 0;
410 static struct termios termios = WINPR_C_ARRAY_INIT;
411
412 if (ifd >= 0)
413 fd = ifd;
414
415 if (fd < 0)
416 return FALSE;
417
418 if (!isatty(fd))
419 return TRUE;
420
421 if (nonblock)
422 {
423 if (!registered)
424 {
425 (void)winpr_atexit(restore_terminal);
426 registered = true;
427 }
428
429 const int rc1 = fcntl(fd, F_SETFL, orig | O_NONBLOCK);
430 if (rc1 != 0)
431 {
432 char buffer[128] = WINPR_C_ARRAY_INIT;
433 WLog_ERR(TAG, "fcntl(F_SETFL) failed with %s",
434 winpr_strerror(errno, buffer, sizeof(buffer)));
435 return FALSE;
436 }
437 const int rc2 = tcgetattr(fd, &termios);
438 if (rc2 != 0)
439 {
440 char buffer[128] = WINPR_C_ARRAY_INIT;
441 WLog_ERR(TAG, "tcgetattr() failed with %s",
442 winpr_strerror(errno, buffer, sizeof(buffer)));
443 return FALSE;
444 }
445
446 struct termios now = termios;
447 cfmakeraw(&now);
448 const int rc3 = tcsetattr(fd, TCSANOW, &now);
449 if (rc3 != 0)
450 {
451 char buffer[128] = WINPR_C_ARRAY_INIT;
452 WLog_ERR(TAG, "tcsetattr(TCSANOW) failed with %s",
453 winpr_strerror(errno, buffer, sizeof(buffer)));
454 return FALSE;
455 }
456 }
457 else
458 {
459 const int rc1 = tcsetattr(fd, TCSANOW, &termios);
460 if (rc1 != 0)
461 {
462 char buffer[128] = WINPR_C_ARRAY_INIT;
463 WLog_ERR(TAG, "tcsetattr(TCSANOW) failed with %s",
464 winpr_strerror(errno, buffer, sizeof(buffer)));
465 return FALSE;
466 }
467 const int rc2 = fcntl(fd, F_SETFL, orig);
468 if (rc2 != 0)
469 {
470 char buffer[128] = WINPR_C_ARRAY_INIT;
471 WLog_ERR(TAG, "fcntl(F_SETFL) failed with %s",
472 winpr_strerror(errno, buffer, sizeof(buffer)));
473 return FALSE;
474 }
475 fd = -1;
476 }
477 return TRUE;
478}
479
480int freerdp_interruptible_getc(rdpContext* context, FILE* stream)
481{
482 int rc = EOF;
483 const int fd = fileno(stream);
484
485 (void)set_terminal_nonblock(fd, TRUE);
486
487 do
488 {
489 const int res = wait_for_fd(fd, 10);
490 if (res != 0)
491 {
492 char c = 0;
493 const ssize_t rd = read(fd, &c, 1);
494 if (rd == 1)
495 {
496 if (c == 3) /* ctrl + c */
497 return EOF;
498 if (c == 4) /* ctrl + d */
499 return EOF;
500 if (c == 26) /* ctrl + z */
501 return EOF;
502 rc = (int)c;
503 }
504 break;
505 }
506 } while (!freerdp_shall_disconnect_context(context));
507
508 (void)set_terminal_nonblock(fd, FALSE);
509
510 return rc;
511}
512
513#else
514
515const char* freerdp_passphrase_read(rdpContext* context, const char* prompt, char* buf,
516 size_t bufsiz, int from_stdin)
517{
518 return nullptr;
519}
520
521int freerdp_interruptible_getc(rdpContext* context, FILE* f)
522{
523 return EOF;
524}
525
526const char* freerdp_passphrase_from_env(WINPR_ATTR_UNUSED rdpContext* context,
527 WINPR_ATTR_UNUSED const char* prompt,
528 WINPR_ATTR_UNUSED char* buf,
529 WINPR_ATTR_UNUSED size_t bufsiz)
530{
531 return nullptr;
532}
533
534const char* freerdp_passphrase_read_tty(WINPR_ATTR_UNUSED rdpContext* context,
535 WINPR_ATTR_UNUSED const char* prompt,
536 WINPR_ATTR_UNUSED char* buf,
537 WINPR_ATTR_UNUSED size_t bufsiz,
538 WINPR_ATTR_UNUSED int from_stdin)
539{
540 return nullptr;
541}
542#endif
543
544SSIZE_T freerdp_interruptible_get_line(rdpContext* context, char** plineptr, size_t* psize,
545 FILE* stream)
546{
547 int c = 0;
548 char* n = nullptr;
549 size_t step = 32;
550 size_t used = 0;
551 char* ptr = nullptr;
552 size_t len = 0;
553
554 if (!plineptr || !psize)
555 {
556 errno = EINVAL;
557 return -1;
558 }
559
560 bool echo = true;
561#if !defined(_WIN32) && !defined(ANDROID)
562 {
563 const int fd = fileno(stream);
564
565 struct termios termios = WINPR_C_ARRAY_INIT;
566 /* This might fail if /from-stdin is used. */
567 if (tcgetattr(fd, &termios) == 0)
568 echo = (termios.c_lflag & ECHO) != 0;
569 else
570 echo = false;
571 }
572#endif
573
574 if (*plineptr && (*psize > 0))
575 {
576 ptr = *plineptr;
577 used = *psize;
578 if (echo)
579 {
580 printf("%s", ptr);
581 (void)fflush(stdout);
582 }
583 }
584
585 do
586 {
587 if (used + 2 >= len)
588 {
589 len = used + step;
590 n = realloc(ptr, len);
591
592 if (!n)
593 {
594 free(ptr);
595 *plineptr = nullptr;
596 return -1;
597 }
598
599 ptr = n;
600 }
601
602 c = freerdp_interruptible_getc(context, stream);
603 if (c == 127)
604 {
605 if (used > 0)
606 {
607 ptr[used--] = '\0';
608 if (echo)
609 {
610 printf("\b");
611 printf(" ");
612 printf("\b");
613 (void)fflush(stdout);
614 }
615 }
616 continue;
617 }
618 if (echo)
619 {
620 printf("%c", c);
621 (void)fflush(stdout);
622 }
623 if (c != EOF)
624 ptr[used++] = (char)c;
625 } while ((c != '\n') && (c != '\r') && (c != EOF));
626
627 printf("\n");
628 ptr[used] = '\0';
629 if (c == EOF)
630 {
631 free(ptr);
632 *plineptr = nullptr;
633 return EOF;
634 }
635 *plineptr = ptr;
636 *psize = used;
637 return WINPR_ASSERTING_INT_CAST(SSIZE_T, used);
638}