challenger-httpd_challenge.c (40078B)
1 /* 2 This file is part of Challenger 3 Copyright (C) 2023, 2024 Taler Systems SA 4 5 Challenger is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 Challenger is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 Challenger; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 /** 17 * @file challenger-httpd_challenge.c 18 * @brief functions to handle incoming /challenge requests 19 * @author Christian Grothoff 20 */ 21 #include "platform.h" 22 #include "challenger-httpd.h" 23 #include <regex.h> 24 #include <gnunet/gnunet_util_lib.h> 25 #include <gnunet/gnunet_pq_lib.h> 26 #include "challenger-httpd_challenge.h" 27 #include <taler/taler_json_lib.h> 28 #include <taler/taler_mhd_lib.h> 29 #include <taler/taler_templating_lib.h> 30 #include <taler/taler_signatures.h> 31 #include "challenger-database/do_challenge_address.h" 32 #include "challenger-database/get_validation_address.h" 33 #include "challenger-httpd_common.h" 34 35 /** 36 * Maximum number of retries for the database interaction. 37 */ 38 #define MAX_RETRIES 3 39 40 /** 41 * Set to 1 to dump addresses into the log. 42 */ 43 #define DEBUG 0 44 45 /** 46 * Context for a /challenge operation. 47 */ 48 struct ChallengeContext 49 { 50 51 /** 52 * Nonce of the operation. 53 */ 54 struct CHALLENGER_ValidationNonceP nonce; 55 56 /** 57 * Kept in a DLL. 58 */ 59 struct ChallengeContext *next; 60 61 /** 62 * Kept in a DLL. 63 */ 64 struct ChallengeContext *prev; 65 66 /** 67 * Our handler context. 68 */ 69 struct CH_HandlerContext *hc; 70 71 /** 72 * Handle to the helper process. 73 */ 74 struct GNUNET_Process *child; 75 76 /** 77 * Handle to wait for @e child 78 */ 79 struct GNUNET_ChildWaitHandle *cwh; 80 81 /** 82 * Handle for processing uploaded data. 83 */ 84 struct MHD_PostProcessor *pp; 85 86 /** 87 * Where we store the collected address data. 88 */ 89 json_t *address; 90 91 /** 92 * Last key during POST processing. 93 */ 94 char *last_key; 95 96 /** 97 * Name of the first uploaded field that could not be represented 98 * in JSON (because the key or the value was not valid UTF-8), or 99 * NULL if all fields were fine. 100 */ 101 char *bad_key; 102 103 /** 104 * Uploaded data during POST processing. 105 */ 106 char *data; 107 108 /** 109 * Where to redirect the client on errors? 110 */ 111 char *client_redirect_uri; 112 113 /** 114 * OAuth2 state. 115 */ 116 char *state; 117 118 /** 119 * Buffer used by #TALER_MHD_parse_post_json(). Or NULL. 120 */ 121 void *jbuffer; 122 123 /** 124 * When did we transmit last? 125 */ 126 struct GNUNET_TIME_Absolute last_tx_time; 127 128 /** 129 * Exit code from helper. 130 */ 131 unsigned long int exit_code; 132 133 /** 134 * Number of bytes in @a data, excluding 0-terminator. 135 */ 136 size_t data_len; 137 138 /** 139 * Our tan. 140 */ 141 uint32_t tan; 142 143 /** 144 * How many attempts does the user have left on the current TAN? 145 */ 146 uint32_t pin_attempts_left; 147 148 /** 149 * How many times may a TAN still be transmitted for this validation? 150 */ 151 uint32_t pin_transmissions_left; 152 153 /** 154 * How did the helper die? 155 */ 156 enum GNUNET_OS_ProcessStatusType pst; 157 158 /** 159 * Connection status. #GNUNET_OK to continue 160 * normally, #GNUNET_NO if an error was already 161 * returned, #GNUNET_SYSERR if we failed to 162 * return an error and should just return #MHD_NO. 163 */ 164 enum GNUNET_GenericReturnValue status; 165 166 /** 167 * #GNUNET_YES if we are suspended in #bc_head, 168 * #GNUNET_NO if operating normally, 169 * #GNUNET_SYSERR if resumed by shutdown (end with #MHD_NO) 170 */ 171 enum GNUNET_GenericReturnValue suspended; 172 173 /** 174 * True if the provided address was refused, usually because 175 * the user tried too many different addresses already. 176 */ 177 bool address_refused; 178 179 /** 180 * Should we retransmit the TAN? 181 */ 182 bool retransmit; 183 184 /** 185 * True if the validation failed permanently, i.e. the user is out 186 * of address changes, TAN transmissions and TAN attempts. 187 */ 188 bool failed; 189 190 /** 191 * Is the challenge already solved? 192 */ 193 bool solved; 194 195 /** 196 * Did we do the DB interaction? 197 */ 198 bool db_finished; 199 200 /** 201 * True if we handed a new TAN to the transmission helper and it still 202 * needs to be confirmed in the database once the helper succeeded. 203 */ 204 bool pin_pending; 205 206 /** 207 * Is the upload in JSON? 208 */ 209 bool is_json; 210 211 /** 212 * Set to true if the upload is too big. 213 */ 214 bool too_big; 215 }; 216 217 218 /** 219 * Head of suspended challenger contexts. 220 */ 221 struct ChallengeContext *bc_head; 222 223 /** 224 * Tail of suspended challenger contexts. 225 */ 226 struct ChallengeContext *bc_tail; 227 228 229 void 230 CH_wakeup_challenge_on_shutdown () 231 { 232 struct ChallengeContext *bc; 233 234 while (NULL != (bc = bc_head)) 235 { 236 GNUNET_CONTAINER_DLL_remove (bc_head, 237 bc_tail, 238 bc); 239 MHD_resume_connection (bc->hc->connection); 240 bc->suspended = GNUNET_SYSERR; 241 } 242 } 243 244 245 /** 246 * Function called to clean up a backup context. 247 * 248 * @param cls a `struct ChallengeContext` 249 */ 250 static void 251 cleanup_ctx (void *cls) 252 { 253 struct ChallengeContext *bc = cls; 254 255 if (NULL != bc->pp) 256 { 257 GNUNET_break_op (MHD_YES == 258 MHD_destroy_post_processor (bc->pp)); 259 } 260 if (NULL != bc->cwh) 261 { 262 GNUNET_wait_child_cancel (bc->cwh); 263 bc->cwh = NULL; 264 } 265 if (NULL != bc->child) 266 { 267 GNUNET_break (GNUNET_OK == 268 GNUNET_process_kill (bc->child, 269 SIGKILL)); 270 GNUNET_break (GNUNET_OK == 271 GNUNET_process_wait (bc->child, 272 true, 273 NULL, 274 NULL)); 275 GNUNET_process_destroy (bc->child); 276 bc->child = NULL; 277 } 278 TALER_MHD_parse_post_cleanup_callback (bc->jbuffer); 279 json_decref (bc->address); 280 GNUNET_free (bc->data); 281 GNUNET_free (bc->state); 282 GNUNET_free (bc->last_key); 283 GNUNET_free (bc->bad_key); 284 GNUNET_free (bc->client_redirect_uri); 285 GNUNET_free (bc); 286 } 287 288 289 /** 290 * Generate error reply. 291 * 292 * @param bc our context 293 * @param http_status HTTP status to return 294 * @param ec error code to return 295 * @param hint human-readable hint to give 296 */ 297 static enum MHD_Result 298 reply_error (struct ChallengeContext *bc, 299 unsigned int http_status, 300 enum TALER_ErrorCode ec, 301 const char *hint) 302 { 303 struct CH_HandlerContext *hc = bc->hc; 304 305 return TALER_MHD_reply_with_error ( 306 hc->connection, 307 http_status, 308 ec, 309 hint); 310 } 311 312 313 /** 314 * Did a TAN transmission helper report that the TAN was transmitted? 315 * 316 * Exit code 0 means the TAN was confirmed to have reached the address. The 317 * 200-210 band means a service accepted it for delivery without confirming 318 * that it arrived: 201 accepted by the provider, 202 suppressed as a duplicate 319 * of a message already in flight. 320 * 321 * The band deliberately does not start at 1: libgnunetutil reports a helper it 322 * failed to exec() as exit code 1, and that must not be mistaken for a 323 * delivery. 324 * 325 * @param exit_code exit status of the helper, which must have exited normally 326 * @return true if the TAN was transmitted 327 */ 328 static bool 329 helper_reported_success (unsigned long int exit_code) 330 { 331 return (0 == exit_code) || 332 ( (exit_code >= 200) && 333 (exit_code <= 210) ); 334 } 335 336 337 /** 338 * Map the exit status of a TAN transmission helper onto an HTTP status and 339 * error code. 340 * 341 * The helpers use a banded exit-code scheme documented in 342 * challenger-send-sms(1): 0 and 200-210 mean the TAN was transmitted (see 343 * #helper_reported_success()), 10-19 blames the address the user gave us, 344 * 20-29 is a recipient that is temporarily unreachable, 30-39 is the 345 * transmission provider and 40-49 is our own configuration. 346 * 347 * Codes we do not recognise are reported as an upstream failure rather than 348 * blamed on the user, so that a helper predating this scheme -- which used 349 * small ad-hoc exit codes -- never yields a 400. 350 * 351 * @param exit_code exit status of the helper, which must have exited normally 352 * @param[out] http_status set to the HTTP status to return 353 * @return error code to return, #TALER_EC_NONE if the TAN was transmitted 354 */ 355 static enum TALER_ErrorCode 356 classify_helper_status (unsigned long int exit_code, 357 unsigned int *http_status) 358 { 359 if (helper_reported_success (exit_code)) 360 { 361 *http_status = MHD_HTTP_OK; 362 return TALER_EC_NONE; 363 } 364 if ( (exit_code >= 10) && 365 (exit_code < 20) ) 366 { 367 *http_status = MHD_HTTP_BAD_REQUEST; 368 return TALER_EC_CHALLENGER_ADDRESS_UNUSABLE; 369 } 370 if ( (exit_code >= 20) && 371 (exit_code < 30) ) 372 { 373 *http_status = MHD_HTTP_SERVICE_UNAVAILABLE; 374 return TALER_EC_CHALLENGER_ADDRESS_UNREACHABLE; 375 } 376 if ( (exit_code >= 40) && 377 (exit_code < 50) ) 378 { 379 *http_status = MHD_HTTP_INTERNAL_SERVER_ERROR; 380 return TALER_EC_CHALLENGER_HELPER_MISCONFIGURED; 381 } 382 *http_status = MHD_HTTP_BAD_GATEWAY; 383 return TALER_EC_CHALLENGER_HELPER_EXEC_FAILED; 384 } 385 386 387 /** 388 * Function called when our TAN transmission helper has terminated. 389 * 390 * @param cls our `struct ChallengeContext *` 391 * @param type type of the process 392 * @param exit_code status code of the process 393 */ 394 static void 395 child_done_cb (void *cls, 396 enum GNUNET_OS_ProcessStatusType type, 397 long unsigned int exit_code) 398 { 399 struct ChallengeContext *bc = cls; 400 struct GNUNET_AsyncScopeSave old_scope; 401 402 GNUNET_async_scope_enter (&bc->hc->async_scope_id, 403 &old_scope); 404 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 405 "Child done with exit code %d/%llu\n", 406 (int) type, 407 (unsigned long long) exit_code); 408 GNUNET_process_destroy (bc->child); 409 bc->child = NULL; 410 bc->cwh = NULL; 411 bc->pst = type; 412 bc->exit_code = exit_code; 413 bc->suspended = GNUNET_NO; 414 MHD_resume_connection (bc->hc->connection); 415 GNUNET_CONTAINER_DLL_remove (bc_head, 416 bc_tail, 417 bc); 418 CH_trigger_daemon (); 419 GNUNET_async_scope_restore (&old_scope); 420 } 421 422 423 /** 424 * Resolve a binary name via PATH. 425 * 426 * Needed because the GNUnet process helpers do not support 427 * an execp equivalent at present. 428 * 429 * @param binary_name name to search for 430 * @return resolved path, NULL if the binary was not found 431 */ 432 static char * 433 resolve_path (const char *binary_name) 434 { 435 char *path_env; 436 char full_path[2048]; 437 char *dir; 438 char *path_copy; 439 440 if (NULL != strchr (binary_name, 441 '/')) 442 return GNUNET_strdup (binary_name); 443 path_env = getenv ("PATH"); 444 if (NULL == path_env) 445 return NULL; 446 path_copy = GNUNET_strdup (path_env); 447 dir = strtok (path_copy, ":"); 448 while (NULL != dir) 449 { 450 snprintf (full_path, 451 sizeof(full_path), 452 "%s/%s", 453 dir, 454 binary_name); 455 if (0 == access (full_path, 456 X_OK)) 457 { 458 GNUNET_free (path_copy); 459 return GNUNET_strdup (full_path); 460 } 461 dir = strtok (NULL, ":"); 462 } 463 GNUNET_free (path_copy); 464 return NULL; 465 } 466 467 468 /** 469 * Transmit the TAN to the given address. 470 * 471 * @param[in,out] bc context to submit TAN for 472 */ 473 static void 474 send_tan (struct ChallengeContext *bc) 475 { 476 struct GNUNET_DISK_PipeHandle *p; 477 struct GNUNET_DISK_FileHandle *pipe_stdin; 478 void *msg; 479 size_t msg_len; 480 481 p = GNUNET_DISK_pipe (GNUNET_DISK_PF_BLOCKING_RW); 482 if (NULL == p) 483 { 484 enum MHD_Result mres; 485 486 GNUNET_break (0); 487 mres = TALER_MHD_reply_with_error ( 488 bc->hc->connection, 489 MHD_HTTP_BAD_GATEWAY, 490 TALER_EC_CHALLENGER_HELPER_EXEC_FAILED, 491 "pipe"); 492 bc->status = (MHD_YES == mres) 493 ? GNUNET_NO 494 : GNUNET_SYSERR; 495 return; 496 } 497 { 498 char *address; 499 char *binary_path = NULL; 500 char **cmd_argv; 501 const char *extra_args[2]; 502 503 address = json_dumps (bc->address, 504 JSON_COMPACT); 505 extra_args[0] = address; 506 extra_args[1] = NULL; 507 cmd_argv = TALER_words_split (CH_auth_command, 508 extra_args); 509 #if DEBUG 510 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 511 "Running auth command `%s' on address `%s'\n", 512 CH_auth_command, 513 address); 514 #endif 515 bc->child = GNUNET_process_create (GNUNET_OS_INHERIT_STD_ERR); 516 GNUNET_assert (GNUNET_OK == 517 GNUNET_process_set_options ( 518 bc->child, 519 GNUNET_process_option_inherit_rpipe (p, 520 STDIN_FILENO))); 521 if (NULL != cmd_argv[0]) 522 binary_path = resolve_path (cmd_argv[0]); 523 if ( (NULL == binary_path) || 524 (GNUNET_OK != 525 GNUNET_process_run_command_argv (bc->child, 526 binary_path, 527 (const char **) cmd_argv)) ) 528 { 529 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, 530 "exec"); 531 GNUNET_process_destroy (bc->child); 532 bc->child = NULL; 533 } 534 GNUNET_free (binary_path); 535 TALER_words_destroy (cmd_argv); 536 free (address); 537 } 538 if (NULL == bc->child) 539 { 540 enum MHD_Result mres; 541 542 GNUNET_break (0); 543 GNUNET_break (GNUNET_OK == 544 GNUNET_DISK_pipe_close (p)); 545 mres = TALER_MHD_reply_with_error ( 546 bc->hc->connection, 547 MHD_HTTP_BAD_GATEWAY, 548 TALER_EC_CHALLENGER_HELPER_EXEC_FAILED, 549 "exec"); 550 bc->status = (MHD_YES == mres) 551 ? GNUNET_NO 552 : GNUNET_SYSERR; 553 return; 554 } 555 pipe_stdin = GNUNET_DISK_pipe_detach_end (p, 556 GNUNET_DISK_PIPE_END_WRITE); 557 GNUNET_assert (NULL != pipe_stdin); 558 GNUNET_break (GNUNET_OK == 559 GNUNET_DISK_pipe_close (p)); 560 if (0 != CH_message_template_len) 561 { 562 json_t *root; 563 int mret; 564 565 root = GNUNET_JSON_PACK ( 566 GNUNET_JSON_pack_object_incref ("address", 567 bc->address), 568 GNUNET_JSON_pack_int64 ("pin", 569 bc->tan)); 570 mret = TALER_TEMPLATING_fill2 (CH_message_template, 571 CH_message_template_len, 572 root, 573 &msg, 574 &msg_len); 575 json_decref (root); 576 if (0 != mret) 577 { 578 enum MHD_Result mres; 579 580 GNUNET_break (0); 581 mres = TALER_MHD_reply_with_error ( 582 bc->hc->connection, 583 MHD_HTTP_INTERNAL_SERVER_ERROR, 584 TALER_EC_GENERIC_FAILED_TO_EXPAND_TEMPLATE, 585 NULL); 586 GNUNET_DISK_file_close (pipe_stdin); 587 bc->status = (MHD_YES == mres) 588 ? GNUNET_NO 589 : GNUNET_SYSERR; 590 return; 591 } 592 } 593 else 594 { 595 char *cmsg; 596 597 GNUNET_asprintf (&cmsg, 598 "TAN: %u", 599 (unsigned int) bc->tan); 600 msg_len = strlen (cmsg); 601 msg = cmsg; 602 } 603 { 604 const char *off = msg; 605 size_t left = msg_len; 606 607 while (0 != left) 608 { 609 ssize_t ret; 610 611 ret = GNUNET_DISK_file_write (pipe_stdin, 612 off, 613 left); 614 if (ret <= 0) 615 { 616 enum MHD_Result mres; 617 618 GNUNET_break (0); 619 mres = TALER_MHD_reply_with_error ( 620 bc->hc->connection, 621 MHD_HTTP_BAD_GATEWAY, 622 TALER_EC_CHALLENGER_HELPER_EXEC_FAILED, 623 "write"); 624 GNUNET_DISK_file_close (pipe_stdin); 625 GNUNET_free (msg); 626 bc->status = (MHD_YES == mres) 627 ? GNUNET_NO 628 : GNUNET_SYSERR; 629 return; 630 } 631 off += (size_t) ret; 632 left -= (size_t) ret; 633 } 634 GNUNET_DISK_file_close (pipe_stdin); 635 } 636 GNUNET_free (msg); 637 bc->cwh = GNUNET_wait_child (bc->child, 638 &child_done_cb, 639 bc); 640 /* The TAN is now in the hands of the helper; if it terminates 641 successfully, the main handler promotes it in the database. */ 642 bc->pin_pending = true; 643 MHD_suspend_connection (bc->hc->connection); 644 bc->suspended = GNUNET_YES; 645 GNUNET_CONTAINER_DLL_insert (bc_head, 646 bc_tail, 647 bc); 648 } 649 650 651 /** 652 * Store the value accumulated in @a bc->data under @a bc->last_key in 653 * the address object of @a bc, and free both. If the key or the value 654 * is not valid UTF-8 (and thus not representable in JSON), the field is 655 * dropped and its name is remembered in @a bc->bad_key so that the main 656 * handler can fail the request with a 400. 657 * 658 * Both strings are raw bytes from the client, so failure here must 659 * never be fatal to the process. 660 * 661 * @param[in,out] bc context to update 662 */ 663 static void 664 flush_field (struct ChallengeContext *bc) 665 { 666 json_t *jkey; 667 json_t *jval; 668 669 /* json_string() returns NULL if the input is not valid UTF-8. */ 670 jkey = json_string (bc->last_key); 671 jval = json_string (NULL != bc->data 672 ? bc->data 673 : ""); 674 if ( (NULL == jkey) || 675 (NULL == jval) ) 676 { 677 GNUNET_break_op (0); 678 if (NULL == bc->bad_key) 679 bc->bad_key = GNUNET_strdup ( 680 (NULL != jkey) 681 ? bc->last_key 682 : "<field name is not valid UTF-8>"); 683 } 684 else 685 { 686 GNUNET_assert (0 == 687 json_object_set (bc->address, 688 bc->last_key, 689 jval)); 690 } 691 json_decref (jkey); 692 json_decref (jval); 693 GNUNET_free (bc->last_key); 694 GNUNET_free (bc->data); 695 bc->data_len = 0; 696 } 697 698 699 /** 700 * Iterator over key-value pairs where the value may be made available 701 * in increments and/or may not be zero-terminated. Used for 702 * processing POST data. 703 * 704 * @param cls a `struct ChallengeContext *` 705 * @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD 706 * @param key 0-terminated key for the value 707 * @param filename name of the uploaded file, NULL if not known 708 * @param content_type mime-type of the data, NULL if not known 709 * @param transfer_encoding encoding of the data, NULL if not known 710 * @param data pointer to @a size bytes of data at the 711 * specified offset 712 * @param off offset of data in the overall value 713 * @param size number of bytes in @a data available 714 * @return #MHD_YES to continue iterating, 715 * #MHD_NO to abort the iteration 716 */ 717 static enum MHD_Result 718 post_iter (void *cls, 719 enum MHD_ValueKind kind, 720 const char *key, 721 const char *filename, 722 const char *content_type, 723 const char *transfer_encoding, 724 const char *data, 725 uint64_t off, 726 size_t size) 727 { 728 struct ChallengeContext *bc = cls; 729 730 (void) filename; 731 (void) content_type; 732 (void) transfer_encoding; 733 (void) off; 734 if (MHD_POSTDATA_KIND != kind) 735 return MHD_YES; 736 if (bc->too_big) 737 return MHD_YES; /* discard the rest, we already have our answer */ 738 if ( (NULL != bc->last_key) && 739 (0 != strcmp (key, 740 bc->last_key)) ) 741 { 742 flush_field (bc); 743 } 744 if (NULL == bc->last_key) 745 { 746 bc->last_key = GNUNET_strdup (key); 747 } 748 /* Hard cap independent of Content-Length: TALER_MHD_check_content_length() 749 does not reject requests that omit Content-Length (e.g. chunked uploads), 750 so without this guard an attacker could stream an unbounded field value. */ 751 if (bc->data_len + size > 1024) 752 { 753 GNUNET_break_op (0); 754 bc->too_big = true; 755 /* Returning MHD_NO here would put the post processor into an error 756 state and make MHD tear the connection down without a response; 757 keep going (discarding the data) so that the handler can reply 758 with a proper 413. */ 759 return MHD_YES; 760 } 761 bc->data = GNUNET_realloc (bc->data, 762 bc->data_len + size + 1); 763 memcpy (bc->data + bc->data_len, 764 data, 765 size); 766 bc->data_len += size; 767 bc->data[bc->data_len] = '\0'; 768 return MHD_YES; 769 } 770 771 772 /** 773 * Check if the given address satisfies our restrictions. 774 * 775 * @param address address data provided by the client 776 * @param[out] ec set to the error code to report if the check failed; 777 * #TALER_EC_CHALLENGER_ADDRESS_RESTRICTION_VIOLATED if the value 778 * supplied by the user is at fault, and 779 * #TALER_EC_CHALLENGER_ADDRESS_RESTRICTION_MALFORMED if our own 780 * configuration is at fault 781 * @return NULL on success, otherwise the key that failed 782 */ 783 static const char * 784 check_restrictions (const json_t *address, 785 enum TALER_ErrorCode *ec) 786 { 787 const char *key; 788 const json_t *val; 789 790 *ec = TALER_EC_CHALLENGER_ADDRESS_RESTRICTION_VIOLATED; 791 json_object_foreach ((json_t *) CH_restrictions, key, val) 792 { 793 const char *str = json_string_value ( 794 json_object_get (address, 795 key)); 796 const char *regex = json_string_value ( 797 json_object_get ( 798 val, 799 "regex")); 800 regex_t re; 801 802 if (NULL == str) 803 return key; /* missing is not allowed */ 804 if (NULL == regex) 805 { 806 /* regex must be specified */ 807 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 808 "Regex missing for `%s'\n", 809 key); 810 *ec = TALER_EC_CHALLENGER_ADDRESS_RESTRICTION_MALFORMED; 811 return key; 812 } 813 if (0 != regcomp (&re, 814 regex, 815 REG_EXTENDED)) 816 { 817 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 818 "Invalid regex `%s' address restriction specified for `%s'\n", 819 regex, 820 key); 821 /* Fail closed: a restriction that cannot be compiled must not be 822 treated as "no restriction". */ 823 *ec = TALER_EC_CHALLENGER_ADDRESS_RESTRICTION_MALFORMED; 824 return key; 825 } 826 { 827 regmatch_t m; 828 829 /* Anchor the match: the pattern must match the ENTIRE value, not just a 830 substring, otherwise e.g. "[0-9]{4}" would accept any value that 831 merely contains four digits. */ 832 if ( (0 != regexec (&re, 833 str, 834 1, 835 &m, 836 0)) || 837 (0 != m.rm_so) || 838 ('\0' != str[m.rm_eo]) ) 839 { 840 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 841 "Client input `%s' rejected as it does not match address restriction `%s' specified for `%s'\n", 842 str, 843 regex, 844 key); 845 regfree (&re); 846 return key; 847 } 848 } 849 regfree (&re); 850 } 851 return NULL; 852 } 853 854 855 /** 856 * Check if @a a1 and @a a2 are equal, ignoring the 857 * "read_only" field. 858 * 859 * @param a1 addr to compare 860 * @param a2 addr to compare 861 * @return true if both are equal 862 */ 863 static bool 864 addr_equal (const json_t *a1, 865 const json_t *a2) 866 { 867 bool ret; 868 json_t *j1 = json_deep_copy (a1); 869 json_t *j2 = json_deep_copy (a2); 870 871 GNUNET_assert (NULL != j1); 872 GNUNET_assert (NULL != j2); 873 json_object_del (j1, 874 "read_only"); 875 json_object_del (j2, 876 "read_only"); 877 ret = (1 == json_equal (j1, j2)); 878 json_decref (j1); 879 json_decref (j2); 880 return ret; 881 } 882 883 884 enum MHD_Result 885 CH_handler_challenge (struct CH_HandlerContext *hc, 886 const char *upload_data, 887 size_t *upload_data_size) 888 { 889 struct ChallengeContext *bc = hc->ctx; 890 891 if (NULL == bc) 892 { 893 /* first call, setup internals */ 894 bc = GNUNET_new (struct ChallengeContext); 895 bc->status = GNUNET_OK; 896 bc->hc = hc; 897 hc->cc = &cleanup_ctx; 898 hc->ctx = bc; 899 bc->pst = GNUNET_OS_PROCESS_UNKNOWN; 900 bc->tan 901 = GNUNET_CRYPTO_random_u32 (100000000); 902 if (GNUNET_OK != 903 GNUNET_STRINGS_string_to_data (hc->path, 904 strlen (hc->path), 905 &bc->nonce, 906 sizeof (bc->nonce))) 907 { 908 GNUNET_break_op (0); 909 /* The nonce is present but unusable; that is a malformed request, 910 not a missing parameter and not an unknown validation. /authorize 911 and /solve answer the same way. */ 912 return TALER_MHD_reply_with_error ( 913 hc->connection, 914 MHD_HTTP_BAD_REQUEST, 915 TALER_EC_GENERIC_PARAMETER_MALFORMED, 916 "nonce"); 917 } 918 TALER_MHD_check_content_length (hc->connection, 919 1024); 920 { 921 const char *ct; 922 923 ct = MHD_lookup_connection_value (hc->connection, 924 MHD_HEADER_KIND, 925 MHD_HTTP_HEADER_CONTENT_TYPE); 926 bc->is_json = ( (NULL != ct) && 927 (0 == strcasecmp (ct, 928 "application/json")) ); 929 if (! bc->is_json) 930 bc->address = json_object (); 931 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 932 "Processing /challenge upload with %s encoding...\n", 933 ct); 934 } 935 if (! bc->is_json) 936 { 937 bc->pp = MHD_create_post_processor (hc->connection, 938 1024, 939 &post_iter, 940 bc); 941 if (NULL == bc->pp) 942 { 943 GNUNET_break_op (0); 944 return TALER_MHD_reply_with_error ( 945 hc->connection, 946 MHD_HTTP_UNSUPPORTED_MEDIA_TYPE, 947 TALER_EC_GENERIC_PARAMETER_MALFORMED, 948 MHD_HTTP_HEADER_CONTENT_TYPE); 949 } 950 } 951 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 952 "Awaiting /challenge upload (%u)...\n", 953 (unsigned int) *upload_data_size); 954 return MHD_YES; 955 } 956 GNUNET_assert (GNUNET_YES != bc->suspended); 957 if (GNUNET_SYSERR == bc->suspended) 958 { 959 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 960 "/challenge ends in shutdown\n"); 961 return MHD_NO; 962 } 963 /* Handle case where helper process failed */ 964 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 965 "Checking child process status: %d / %d (%s)\n", 966 (int) bc->pst, 967 (int) bc->exit_code, 968 NULL == bc->child ? "dead" : "running"); 969 if ( (GNUNET_OS_PROCESS_UNKNOWN != bc->pst) && 970 (NULL == bc->child) && 971 ( (GNUNET_OS_PROCESS_EXITED != bc->pst) || 972 (! helper_reported_success (bc->exit_code)) ) ) 973 { 974 char es[32]; 975 unsigned int http_status; 976 enum TALER_ErrorCode ec; 977 978 if (GNUNET_OS_PROCESS_EXITED != bc->pst) 979 { 980 /* Killed by a signal or otherwise abnormal: there is no exit code to 981 classify. */ 982 http_status = MHD_HTTP_BAD_GATEWAY; 983 ec = TALER_EC_CHALLENGER_HELPER_EXEC_FAILED; 984 } 985 else 986 { 987 ec = classify_helper_status (bc->exit_code, 988 &http_status); 989 } 990 GNUNET_snprintf (es, 991 sizeof (es), 992 "%u/%d", 993 (unsigned int) bc->exit_code, 994 bc->pst); 995 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 996 "Helper failed with status %d/%d\n", 997 (int) bc->pst, 998 (int) bc->exit_code); 999 return TALER_MHD_reply_with_error ( 1000 hc->connection, 1001 http_status, 1002 ec, 1003 es); 1004 } 1005 /* handle upload */ 1006 if (bc->is_json) 1007 { 1008 if (NULL == bc->address) 1009 { 1010 enum GNUNET_GenericReturnValue res; 1011 1012 res = TALER_MHD_parse_post_json (hc->connection, 1013 &bc->jbuffer, 1014 upload_data, 1015 upload_data_size, 1016 &bc->address); 1017 if (GNUNET_SYSERR != res) 1018 return MHD_YES; 1019 GNUNET_break (0); 1020 return MHD_NO; 1021 } 1022 else 1023 { 1024 GNUNET_break (0 == *upload_data_size); 1025 } 1026 } 1027 else if (0 != *upload_data_size) 1028 { 1029 enum MHD_Result res; 1030 1031 res = MHD_post_process (bc->pp, 1032 upload_data, 1033 *upload_data_size); 1034 *upload_data_size = 0; 1035 if (MHD_YES == res) 1036 return MHD_YES; 1037 GNUNET_break (0); 1038 return MHD_NO; 1039 } 1040 if (bc->too_big) 1041 { 1042 GNUNET_break_op (0); 1043 return TALER_MHD_reply_with_error ( 1044 hc->connection, 1045 MHD_HTTP_CONTENT_TOO_LARGE, 1046 TALER_EC_GENERIC_UPLOAD_EXCEEDS_LIMIT, 1047 NULL); 1048 } 1049 if (NULL != bc->last_key) 1050 { 1051 flush_field (bc); 1052 } 1053 if (NULL != bc->bad_key) 1054 { 1055 return reply_error (bc, 1056 MHD_HTTP_BAD_REQUEST, 1057 TALER_EC_GENERIC_PARAMETER_MALFORMED, 1058 bc->bad_key); 1059 } 1060 if (! json_is_object (bc->address)) 1061 { 1062 /* The address is echoed back with GNUNET_JSON_pack_object_incref() and 1063 (if a message template is configured) expanded by send_tan(), both of 1064 which assert on anything that is not an object; refuse it here 1065 instead. Only reachable through an "application/json" upload, as the 1066 form encodings always build an object. */ 1067 GNUNET_break_op (0); 1068 return reply_error (bc, 1069 MHD_HTTP_BAD_REQUEST, 1070 TALER_EC_GENERIC_PARAMETER_MALFORMED, 1071 "address"); 1072 } 1073 #if DEBUG 1074 { 1075 char *address; 1076 1077 address = json_dumps (bc->address, 1078 JSON_COMPACT); 1079 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1080 "Submitted address is `%s'\n", 1081 address); 1082 free (address); 1083 } 1084 #endif 1085 { 1086 const char *bad_field; 1087 enum TALER_ErrorCode ec; 1088 1089 bad_field = check_restrictions (bc->address, 1090 &ec); 1091 if (NULL != bad_field) 1092 { 1093 bool misconfigured 1094 = (TALER_EC_CHALLENGER_ADDRESS_RESTRICTION_MALFORMED == ec); 1095 1096 /* A restriction we cannot evaluate is our fault, not the user's, and 1097 must not be reported as a bad request. */ 1098 if (misconfigured) 1099 GNUNET_break (0); 1100 else 1101 GNUNET_break_op (0); 1102 return reply_error (bc, 1103 misconfigured 1104 ? MHD_HTTP_INTERNAL_SERVER_ERROR 1105 : MHD_HTTP_BAD_REQUEST, 1106 ec, 1107 bad_field); 1108 } 1109 } 1110 if (! bc->db_finished) 1111 { 1112 for (unsigned int r = 0; r < MAX_RETRIES; r++) 1113 { 1114 enum GNUNET_DB_QueryStatus qs; 1115 json_t *old_address; 1116 json_t *ro; 1117 1118 GNUNET_assert (NULL == bc->client_redirect_uri); 1119 qs = CHALLENGERDB_get_validation_address (CH_context, 1120 &bc->nonce, 1121 &old_address); 1122 switch (qs) 1123 { 1124 case GNUNET_DB_STATUS_HARD_ERROR: 1125 GNUNET_break (0); 1126 return reply_error (bc, 1127 MHD_HTTP_INTERNAL_SERVER_ERROR, 1128 TALER_EC_GENERIC_DB_FETCH_FAILED, 1129 "get_validation_address"); 1130 case GNUNET_DB_STATUS_SOFT_ERROR: 1131 if (r < MAX_RETRIES - 1) 1132 continue; 1133 GNUNET_break (0); 1134 return reply_error (bc, 1135 MHD_HTTP_INTERNAL_SERVER_ERROR, 1136 TALER_EC_GENERIC_DB_FETCH_FAILED, 1137 "get_validation_address"); 1138 case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS: 1139 GNUNET_break_op (0); 1140 return reply_error (bc, 1141 MHD_HTTP_NOT_FOUND, 1142 TALER_EC_CHALLENGER_GENERIC_VALIDATION_UNKNOWN, 1143 NULL); 1144 case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT: 1145 break; 1146 } 1147 ro = json_object_get (old_address, 1148 "read_only"); 1149 if ( (NULL != ro) && 1150 (json_boolean_value (ro)) && 1151 (! addr_equal (old_address, 1152 bc->address)) ) 1153 { 1154 GNUNET_break_op (0); 1155 json_decref (old_address); 1156 return reply_error (bc, 1157 MHD_HTTP_FORBIDDEN, 1158 TALER_EC_CHALLENGER_CLIENT_FORBIDDEN_READ_ONLY, 1159 NULL); 1160 } 1161 if (NULL != ro) 1162 GNUNET_assert (0 == 1163 json_object_set (bc->address, 1164 "read_only", 1165 ro)); 1166 json_decref (old_address); 1167 1168 qs = CHALLENGERDB_do_challenge_address (CH_context, 1169 &bc->nonce, 1170 bc->address, 1171 CH_pin_retransmission_frequency, 1172 &bc->tan, 1173 &bc->state, 1174 &bc->last_tx_time, 1175 &bc->pin_attempts_left, 1176 &bc->pin_transmissions_left, 1177 &bc->retransmit, 1178 &bc->client_redirect_uri, 1179 &bc->address_refused, 1180 &bc->solved, 1181 &bc->failed); 1182 switch (qs) 1183 { 1184 case GNUNET_DB_STATUS_HARD_ERROR: 1185 GNUNET_break (0); 1186 return reply_error (bc, 1187 MHD_HTTP_INTERNAL_SERVER_ERROR, 1188 TALER_EC_GENERIC_DB_STORE_FAILED, 1189 "do_challenge_address"); 1190 case GNUNET_DB_STATUS_SOFT_ERROR: 1191 if (r < MAX_RETRIES - 1) 1192 continue; 1193 GNUNET_break (0); 1194 return reply_error (bc, 1195 MHD_HTTP_INTERNAL_SERVER_ERROR, 1196 TALER_EC_GENERIC_DB_STORE_FAILED, 1197 "do_challenge_address"); 1198 case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS: 1199 GNUNET_break_op (0); 1200 return reply_error (bc, 1201 MHD_HTTP_NOT_FOUND, 1202 TALER_EC_CHALLENGER_GENERIC_VALIDATION_UNKNOWN, 1203 NULL); 1204 case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT: 1205 break; 1206 } 1207 break; 1208 } 1209 bc->db_finished = true; 1210 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1211 "Database interaction done (challenge %s)\n", 1212 bc->solved ? "solved" : "unsolved"); 1213 if (bc->solved) 1214 { 1215 enum GNUNET_GenericReturnValue ret; 1216 char *url; 1217 1218 ret = CH_build_full_redirect_url (&bc->nonce, 1219 hc->connection, 1220 &url); 1221 if (GNUNET_OK != ret) 1222 return (GNUNET_NO == ret) ? MHD_YES : MHD_NO; 1223 ret = TALER_MHD_REPLY_JSON_PACK ( 1224 hc->connection, 1225 MHD_HTTP_OK, 1226 GNUNET_JSON_pack_string ("type", 1227 "completed"), 1228 GNUNET_JSON_pack_string ("redirect_url", 1229 url) 1230 ); 1231 GNUNET_free (url); 1232 return ret; 1233 } 1234 if (bc->failed) 1235 { 1236 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1237 "Validation failed, client exhausted all chances\n"); 1238 return CH_reply_validation_failed (hc->connection, 1239 bc->client_redirect_uri, 1240 bc->state); 1241 } 1242 if (bc->address_refused) 1243 { 1244 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1245 "Address changes exhausted address change limit for this process\n"); 1246 return reply_error (bc, 1247 MHD_HTTP_TOO_MANY_REQUESTS, 1248 TALER_EC_CHALLENGER_TOO_MANY_ADDRESS_CHANGES, 1249 "client exceeded authorization attempts limit (too many addresses attempted)"); 1250 1251 } 1252 if ( (! bc->retransmit) && 1253 (0 == bc->pin_transmissions_left) ) 1254 { 1255 /* Note: only the *transmission* budget being exhausted is terminal. 1256 If merely the cooldown blocks the transmission, we fall through and 1257 report "transmitted":false with the retransmission_time. */ 1258 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1259 "TAN transmission limit exhausted for this validation\n"); 1260 return reply_error (bc, 1261 MHD_HTTP_TOO_MANY_REQUESTS, 1262 TALER_EC_CHALLENGER_TOO_MANY_PIN_TRANSMISSIONS, 1263 "client exceeded authorization attempts limit (too many TANs)"); 1264 } 1265 1266 if (bc->retransmit) 1267 { 1268 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1269 "Transmitting TAN\n"); 1270 /* (Re)transmit TAN */ 1271 send_tan (bc); 1272 if (GNUNET_YES == bc->suspended) 1273 { 1274 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1275 "Suspending request after TAN transmission\n"); 1276 return MHD_YES; 1277 } 1278 /* Did we already try to generate a response? */ 1279 if (GNUNET_OK != bc->status) 1280 return (GNUNET_NO == bc->status) 1281 ? MHD_YES 1282 : MHD_NO; 1283 } 1284 } 1285 1286 if (bc->pin_pending) 1287 { 1288 /* The helper terminated successfully (checked above), so the TAN really 1289 went out and only now becomes the TAN we accept. Had the helper 1290 failed, we returned 502 above and the previous TAN (if any) remains 1291 valid. */ 1292 bc->pin_pending = false; 1293 for (unsigned int r = 0; r<MAX_RETRIES; r++) 1294 { 1295 enum GNUNET_DB_QueryStatus qs; 1296 1297 qs = CHALLENGERDB_do_challenge_address_confirm_pin ( 1298 CH_context, 1299 &bc->nonce, 1300 &bc->pin_attempts_left); 1301 switch (qs) 1302 { 1303 case GNUNET_DB_STATUS_HARD_ERROR: 1304 GNUNET_break (0); 1305 return reply_error (bc, 1306 MHD_HTTP_INTERNAL_SERVER_ERROR, 1307 TALER_EC_GENERIC_DB_STORE_FAILED, 1308 "do_challenge_address_confirm_pin"); 1309 case GNUNET_DB_STATUS_SOFT_ERROR: 1310 if (r < MAX_RETRIES - 1) 1311 continue; 1312 GNUNET_break (0); 1313 return reply_error (bc, 1314 MHD_HTTP_INTERNAL_SERVER_ERROR, 1315 TALER_EC_GENERIC_DB_STORE_FAILED, 1316 "do_challenge_address_confirm_pin"); 1317 case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS: 1318 /* Validation was solved or removed while we were transmitting; 1319 there is nothing to promote, but the TAN did go out. */ 1320 GNUNET_break_op (0); 1321 break; 1322 case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT: 1323 break; 1324 } 1325 break; 1326 } 1327 } 1328 1329 { 1330 json_t *args; 1331 struct MHD_Response *resp; 1332 unsigned int http_status; 1333 enum MHD_Result res; 1334 1335 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 1336 "Returning success from challenge with %u attempts left\n", 1337 (unsigned int) bc->pin_attempts_left); 1338 args = GNUNET_JSON_PACK ( 1339 GNUNET_JSON_pack_uint64 ("attempts_left", 1340 bc->pin_attempts_left), 1341 GNUNET_JSON_pack_string ("type", 1342 "created"), 1343 GNUNET_JSON_pack_object_incref ("address", 1344 bc->address), 1345 GNUNET_JSON_pack_bool ("transmitted", 1346 bc->retransmit), 1347 GNUNET_JSON_pack_timestamp ("retransmission_time", 1348 GNUNET_TIME_absolute_to_timestamp ( 1349 GNUNET_TIME_absolute_add ( 1350 bc->last_tx_time, 1351 CH_pin_retransmission_frequency))) 1352 ); 1353 http_status = MHD_HTTP_OK; 1354 resp = TALER_MHD_make_json_steal (args); 1355 GNUNET_break (MHD_YES == 1356 MHD_add_response_header (resp, 1357 MHD_HTTP_HEADER_CACHE_CONTROL, 1358 "no-store,no-cache")); 1359 res = MHD_queue_response (hc->connection, 1360 http_status, 1361 resp); 1362 MHD_destroy_response (resp); 1363 return res; 1364 } 1365 }