1 /* 2 * UPnP WPS Device 3 * Copyright (c) 2000-2003 Intel Corporation 4 * Copyright (c) 2006-2007 Sony Corporation 5 * Copyright (c) 2008-2009 Atheros Communications 6 * Copyright (c) 2009-2010, Jouni Malinen <j@w1.fi> 7 * 8 * See below for more details on licensing and code history. 9 */ 10 11 /* 12 * This has been greatly stripped down from the original file 13 * (upnp_wps_device.c) by Ted Merrill, Atheros Communications 14 * in order to eliminate use of the bulky libupnp library etc. 15 * 16 * History: 17 * upnp_wps_device.c is/was a shim layer between wps_opt_upnp.c and 18 * the libupnp library. 19 * The layering (by Sony) was well done; only a very minor modification 20 * to API of upnp_wps_device.c was required. 21 * libupnp was found to be undesirable because: 22 * -- It consumed too much code and data space 23 * -- It uses multiple threads, making debugging more difficult 24 * and possibly reducing reliability. 25 * -- It uses static variables and only supports one instance. 26 * The shim and libupnp are here replaced by special code written 27 * specifically for the needs of hostapd. 28 * Various shortcuts can and are taken to keep the code size small. 29 * Generally, execution time is not as crucial. 30 * 31 * BUGS: 32 * -- UPnP requires that we be able to resolve domain names. 33 * While uncommon, if we have to do it then it will stall the entire 34 * hostapd program, which is bad. 35 * This is because we use the standard linux getaddrinfo() function 36 * which is syncronous. 37 * An asyncronous solution would be to use the free "ares" library. 38 * -- Does not have a robust output buffering scheme. Uses a single 39 * fixed size output buffer per TCP/HTTP connection, with possible (although 40 * unlikely) possibility of overflow and likely excessive use of RAM. 41 * A better solution would be to write the HTTP output as a buffered stream, 42 * using chunking: (handle header specially, then) generate data with 43 * a printf-like function into a buffer, catching buffer full condition, 44 * then send it out surrounded by http chunking. 45 * -- There is some code that could be separated out into the common 46 * library to be shared with wpa_supplicant. 47 * -- Needs renaming with module prefix to avoid polluting the debugger 48 * namespace and causing possible collisions with other static fncs 49 * and structure declarations when using the debugger. 50 * -- The http error code generation is pretty bogus, hopefully no one cares. 51 * 52 * Author: Ted Merrill, Atheros Communications, based upon earlier work 53 * as explained above and below. 54 * 55 * Copyright: 56 * Copyright 2008 Atheros Communications. 57 * 58 * The original header (of upnp_wps_device.c) reads: 59 * 60 * Copyright (c) 2006-2007 Sony Corporation. All Rights Reserved. 61 * 62 * File Name: upnp_wps_device.c 63 * Description: EAP-WPS UPnP device source 64 * 65 * Redistribution and use in source and binary forms, with or without 66 * modification, are permitted provided that the following conditions 67 * are met: 68 * 69 * * Redistributions of source code must retain the above copyright 70 * notice, this list of conditions and the following disclaimer. 71 * * Redistributions in binary form must reproduce the above copyright 72 * notice, this list of conditions and the following disclaimer in 73 * the documentation and/or other materials provided with the 74 * distribution. 75 * * Neither the name of Sony Corporation nor the names of its 76 * contributors may be used to endorse or promote products derived 77 * from this software without specific prior written permission. 78 * 79 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 80 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 81 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 82 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 83 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 84 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 85 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 86 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 87 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 88 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 89 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 90 * 91 * Portions from Intel libupnp files, e.g. genlib/net/http/httpreadwrite.c 92 * typical header: 93 * 94 * Copyright (c) 2000-2003 Intel Corporation 95 * All rights reserved. 96 * 97 * Redistribution and use in source and binary forms, with or without 98 * modification, are permitted provided that the following conditions are met: 99 * 100 * * Redistributions of source code must retain the above copyright notice, 101 * this list of conditions and the following disclaimer. 102 * * Redistributions in binary form must reproduce the above copyright notice, 103 * this list of conditions and the following disclaimer in the documentation 104 * and/or other materials provided with the distribution. 105 * * Neither name of Intel Corporation nor the names of its contributors 106 * may be used to endorse or promote products derived from this software 107 * without specific prior written permission. 108 * 109 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 110 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 111 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 112 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR 113 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 114 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 115 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 116 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 117 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 118 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 119 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 120 */ 121 122 /* 123 * Overview of WPS over UPnP: 124 * 125 * UPnP is a protocol that allows devices to discover each other and control 126 * each other. In UPnP terminology, a device is either a "device" (a server 127 * that provides information about itself and allows itself to be controlled) 128 * or a "control point" (a client that controls "devices") or possibly both. 129 * This file implements a UPnP "device". 130 * 131 * For us, we use mostly basic UPnP discovery, but the control part of interest 132 * is WPS carried via UPnP messages. There is quite a bit of basic UPnP 133 * discovery to do before we can get to WPS, however. 134 * 135 * UPnP discovery begins with "devices" send out multicast UDP packets to a 136 * certain fixed multicast IP address and port, and "control points" sending 137 * out other such UDP packets. 138 * 139 * The packets sent by devices are NOTIFY packets (not to be confused with TCP 140 * NOTIFY packets that are used later) and those sent by control points are 141 * M-SEARCH packets. These packets contain a simple HTTP style header. The 142 * packets are sent redundantly to get around packet loss. Devices respond to 143 * M-SEARCH packets with HTTP-like UDP packets containing HTTP/1.1 200 OK 144 * messages, which give similar information as the UDP NOTIFY packets. 145 * 146 * The above UDP packets advertise the (arbitrary) TCP ports that the 147 * respective parties will listen to. The control point can then do a HTTP 148 * SUBSCRIBE (something like an HTTP PUT) after which the device can do a 149 * separate HTTP NOTIFY (also like an HTTP PUT) to do event messaging. 150 * 151 * The control point will also do HTTP GET of the "device file" listed in the 152 * original UDP information from the device (see UPNP_WPS_DEVICE_XML_FILE 153 * data), and based on this will do additional GETs... HTTP POSTs are done to 154 * cause an action. 155 * 156 * Beyond some basic information in HTTP headers, additional information is in 157 * the HTTP bodies, in a format set by the SOAP and XML standards, a markup 158 * language related to HTML used for web pages. This language is intended to 159 * provide the ultimate in self-documentation by providing a universal 160 * namespace based on pseudo-URLs called URIs. Note that although a URI looks 161 * like a URL (a web address), they are never accessed as such but are used 162 * only as identifiers. 163 * 164 * The POST of a GetDeviceInfo gets information similar to what might be 165 * obtained from a probe request or response on Wi-Fi. WPS messages M1-M8 166 * are passed via a POST of a PutMessage; the M1-M8 WPS messages are converted 167 * to a bin64 ascii representation for encapsulation. When proxying messages, 168 * WLANEvent and PutWLANResponse are used. 169 * 170 * This of course glosses over a lot of details. 171 */ 172 173 #include "includes.h" 174 175 #include <time.h> 176 #include <net/if.h> 177 #include <netdb.h> 178 #include <sys/ioctl.h> 179 180 #include "common.h" 181 #include "uuid.h" 182 #include "base64.h" 183 #include "wps.h" 184 #include "wps_i.h" 185 #include "wps_upnp.h" 186 #include "wps_upnp_i.h" 187 188 189 /* 190 * UPnP allows a client ("control point") to send a server like us ("device") 191 * a domain name for registration, and we are supposed to resolve it. This is 192 * bad because, using the standard Linux library, we will stall the entire 193 * hostapd waiting for resolution. 194 * 195 * The "correct" solution would be to use an event driven library for domain 196 * name resolution such as "ares". However, this would increase code size 197 * further. Since it is unlikely that we'll actually see such domain names, we 198 * can just refuse to accept them. 199 */ 200 #define NO_DOMAIN_NAME_RESOLUTION 1 /* 1 to allow only dotted ip addresses */ 201 202 203 /* 204 * UPnP does not scale well. If we were in a room with thousands of control 205 * points then potentially we could be expected to handle subscriptions for 206 * each of them, which would exhaust our memory. So we must set a limit. In 207 * practice we are unlikely to see more than one or two. 208 */ 209 #define MAX_SUBSCRIPTIONS 4 /* how many subscribing clients we handle */ 210 #define MAX_ADDR_PER_SUBSCRIPTION 8 211 212 /* Maximum number of Probe Request events per second */ 213 #define MAX_EVENTS_PER_SEC 5 214 215 216 static struct upnp_wps_device_sm *shared_upnp_device = NULL; 217 218 219 /* Write the current date/time per RFC */ 220 void format_date(struct wpabuf *buf) 221 { 222 const char *weekday_str = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat"; 223 const char *month_str = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0" 224 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec"; 225 struct tm *date; 226 time_t t; 227 228 t = time(NULL); 229 date = gmtime(&t); 230 wpabuf_printf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT", 231 &weekday_str[date->tm_wday * 4], date->tm_mday, 232 &month_str[date->tm_mon * 4], date->tm_year + 1900, 233 date->tm_hour, date->tm_min, date->tm_sec); 234 } 235 236 237 /*************************************************************************** 238 * UUIDs (unique identifiers) 239 * 240 * These are supposed to be unique in all the world. 241 * Sometimes permanent ones are used, sometimes temporary ones 242 * based on random numbers... there are different rules for valid content 243 * of different types. 244 * Each uuid is 16 bytes long. 245 **************************************************************************/ 246 247 /* uuid_make -- construct a random UUID 248 * The UPnP documents don't seem to offer any guidelines as to which method to 249 * use for constructing UUIDs for subscriptions. Presumably any method from 250 * rfc4122 is good enough; I've chosen random number method. 251 */ 252 static void uuid_make(u8 uuid[UUID_LEN]) 253 { 254 os_get_random(uuid, UUID_LEN); 255 256 /* Replace certain bits as specified in rfc4122 or X.667 */ 257 uuid[6] &= 0x0f; uuid[6] |= (4 << 4); /* version 4 == random gen */ 258 uuid[8] &= 0x3f; uuid[8] |= 0x80; 259 } 260 261 262 /* 263 * Subscriber address handling. 264 * Since a subscriber may have an arbitrary number of addresses, we have to 265 * add a bunch of code to handle them. 266 * 267 * Addresses are passed in text, and MAY be domain names instead of the (usual 268 * and expected) dotted IP addresses. Resolving domain names consumes a lot of 269 * resources. Worse, we are currently using the standard Linux getaddrinfo() 270 * which will block the entire program until complete or timeout! The proper 271 * solution would be to use the "ares" library or similar with more state 272 * machine steps etc. or just disable domain name resolution by setting 273 * NO_DOMAIN_NAME_RESOLUTION to 1 at top of this file. 274 */ 275 276 /* subscr_addr_delete -- delete single unlinked subscriber address 277 * (be sure to unlink first if need be) 278 */ 279 void subscr_addr_delete(struct subscr_addr *a) 280 { 281 /* 282 * Note: do NOT free domain_and_port or path because they point to 283 * memory within the allocation of "a". 284 */ 285 os_free(a); 286 } 287 288 289 /* subscr_addr_free_all -- unlink and delete list of subscriber addresses. */ 290 static void subscr_addr_free_all(struct subscription *s) 291 { 292 struct subscr_addr *a, *tmp; 293 dl_list_for_each_safe(a, tmp, &s->addr_list, struct subscr_addr, list) 294 { 295 dl_list_del(&a->list); 296 subscr_addr_delete(a); 297 } 298 } 299 300 301 /* subscr_addr_add_url -- add address(es) for one url to subscription */ 302 static void subscr_addr_add_url(struct subscription *s, const char *url, 303 size_t url_len) 304 { 305 int alloc_len; 306 char *scratch_mem = NULL; 307 char *mem; 308 char *host; 309 char *delim; 310 char *path; 311 int port = 80; /* port to send to (default is port 80) */ 312 struct addrinfo hints; 313 struct addrinfo *result = NULL; 314 struct addrinfo *rp; 315 int rerr; 316 size_t host_len, path_len; 317 318 /* url MUST begin with http: */ 319 if (url_len < 7 || os_strncasecmp(url, "http://", 7)) 320 goto fail; 321 url += 7; 322 url_len -= 7; 323 324 /* Make a copy of the string to allow modification during parsing */ 325 scratch_mem = os_malloc(url_len + 1); 326 if (scratch_mem == NULL) 327 goto fail; 328 os_memcpy(scratch_mem, url, url_len); 329 scratch_mem[url_len] = '\0'; 330 wpa_printf(MSG_DEBUG, "WPS UPnP: Adding URL '%s'", scratch_mem); 331 host = scratch_mem; 332 path = os_strchr(host, '/'); 333 if (path) 334 *path++ = '\0'; /* null terminate host */ 335 336 /* Process and remove optional port component */ 337 delim = os_strchr(host, ':'); 338 if (delim) { 339 *delim = '\0'; /* null terminate host name for now */ 340 if (isdigit(delim[1])) 341 port = atol(delim + 1); 342 } 343 344 /* 345 * getaddrinfo does the right thing with dotted decimal notations, or 346 * will resolve domain names. Resolving domain names will unfortunately 347 * hang the entire program until it is resolved or it times out 348 * internal to getaddrinfo; fortunately we think that the use of actual 349 * domain names (vs. dotted decimal notations) should be uncommon. 350 */ 351 os_memset(&hints, 0, sizeof(struct addrinfo)); 352 hints.ai_family = AF_INET; /* IPv4 */ 353 hints.ai_socktype = SOCK_STREAM; 354 #if NO_DOMAIN_NAME_RESOLUTION 355 /* Suppress domain name resolutions that would halt 356 * the program for periods of time 357 */ 358 hints.ai_flags = AI_NUMERICHOST; 359 #else 360 /* Allow domain name resolution. */ 361 hints.ai_flags = 0; 362 #endif 363 hints.ai_protocol = 0; /* Any protocol? */ 364 rerr = getaddrinfo(host, NULL /* fill in port ourselves */, 365 &hints, &result); 366 if (rerr) { 367 wpa_printf(MSG_INFO, "WPS UPnP: Resolve error %d (%s) on: %s", 368 rerr, gai_strerror(rerr), host); 369 goto fail; 370 } 371 372 if (delim) 373 *delim = ':'; /* Restore port */ 374 375 host_len = os_strlen(host); 376 path_len = path ? os_strlen(path) : 0; 377 alloc_len = host_len + 1 + 1 + path_len + 1; 378 379 for (rp = result; rp; rp = rp->ai_next) { 380 struct subscr_addr *a; 381 382 /* Limit no. of address to avoid denial of service attack */ 383 if (dl_list_len(&s->addr_list) >= MAX_ADDR_PER_SUBSCRIPTION) { 384 wpa_printf(MSG_INFO, "WPS UPnP: subscr_addr_add_url: " 385 "Ignoring excessive addresses"); 386 break; 387 } 388 389 a = os_zalloc(sizeof(*a) + alloc_len); 390 if (a == NULL) 391 break; 392 mem = (char *) (a + 1); 393 a->domain_and_port = mem; 394 os_memcpy(mem, host, host_len); 395 mem += host_len + 1; 396 a->path = mem; 397 if (path == NULL || path[0] != '/') 398 *mem++ = '/'; 399 if (path) 400 os_memcpy(mem, path, path_len); 401 os_memcpy(&a->saddr, rp->ai_addr, sizeof(a->saddr)); 402 a->saddr.sin_port = htons(port); 403 404 dl_list_add(&s->addr_list, &a->list); 405 } 406 407 fail: 408 if (result) 409 freeaddrinfo(result); 410 os_free(scratch_mem); 411 } 412 413 414 /* subscr_addr_list_create -- create list from urls in string. 415 * Each url is enclosed by angle brackets. 416 */ 417 static void subscr_addr_list_create(struct subscription *s, 418 const char *url_list) 419 { 420 const char *end; 421 wpa_printf(MSG_DEBUG, "WPS UPnP: Parsing URL list '%s'", url_list); 422 for (;;) { 423 while (*url_list == ' ' || *url_list == '\t') 424 url_list++; 425 if (*url_list != '<') 426 break; 427 url_list++; 428 end = os_strchr(url_list, '>'); 429 if (end == NULL) 430 break; 431 subscr_addr_add_url(s, url_list, end - url_list); 432 url_list = end + 1; 433 } 434 } 435 436 437 int send_wpabuf(int fd, struct wpabuf *buf) 438 { 439 wpa_printf(MSG_DEBUG, "WPS UPnP: Send %lu byte message", 440 (unsigned long) wpabuf_len(buf)); 441 errno = 0; 442 if (write(fd, wpabuf_head(buf), wpabuf_len(buf)) != 443 (int) wpabuf_len(buf)) { 444 wpa_printf(MSG_ERROR, "WPS UPnP: Failed to send buffer: " 445 "errno=%d (%s)", 446 errno, strerror(errno)); 447 return -1; 448 } 449 450 return 0; 451 } 452 453 454 static void wpabuf_put_property(struct wpabuf *buf, const char *name, 455 const char *value) 456 { 457 wpabuf_put_str(buf, "<e:property>"); 458 wpabuf_printf(buf, "<%s>", name); 459 if (value) 460 wpabuf_put_str(buf, value); 461 wpabuf_printf(buf, "</%s>", name); 462 wpabuf_put_str(buf, "</e:property>\n"); 463 } 464 465 466 /** 467 * upnp_wps_device_send_event - Queue event messages for subscribers 468 * @sm: WPS UPnP state machine from upnp_wps_device_init() 469 * 470 * This function queues the last WLANEvent to be sent for all currently 471 * subscribed UPnP control points. sm->wlanevent must have been set with the 472 * encoded data before calling this function. 473 */ 474 static void upnp_wps_device_send_event(struct upnp_wps_device_sm *sm) 475 { 476 /* Enqueue event message for all subscribers */ 477 struct wpabuf *buf; /* holds event message */ 478 int buf_size = 0; 479 struct subscription *s, *tmp; 480 /* Actually, utf-8 is the default, but it doesn't hurt to specify it */ 481 const char *format_head = 482 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" 483 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n"; 484 const char *format_tail = "</e:propertyset>\n"; 485 struct os_time now; 486 487 if (dl_list_empty(&sm->subscriptions)) { 488 /* optimize */ 489 return; 490 } 491 492 if (os_get_time(&now) == 0) { 493 if (now.sec != sm->last_event_sec) { 494 sm->last_event_sec = now.sec; 495 sm->num_events_in_sec = 1; 496 } else { 497 sm->num_events_in_sec++; 498 /* 499 * In theory, this should apply to all WLANEvent 500 * notifications, but EAP messages are of much higher 501 * priority and Probe Request notifications should not 502 * be allowed to drop EAP messages, so only throttle 503 * Probe Request notifications. 504 */ 505 if (sm->num_events_in_sec > MAX_EVENTS_PER_SEC && 506 sm->wlanevent_type == 507 UPNP_WPS_WLANEVENT_TYPE_PROBE) { 508 wpa_printf(MSG_DEBUG, "WPS UPnP: Throttle " 509 "event notifications (%u seen " 510 "during one second)", 511 sm->num_events_in_sec); 512 return; 513 } 514 } 515 } 516 517 /* Determine buffer size needed first */ 518 buf_size += os_strlen(format_head); 519 buf_size += 50 + 2 * os_strlen("WLANEvent"); 520 if (sm->wlanevent) 521 buf_size += os_strlen(sm->wlanevent); 522 buf_size += os_strlen(format_tail); 523 524 buf = wpabuf_alloc(buf_size); 525 if (buf == NULL) 526 return; 527 wpabuf_put_str(buf, format_head); 528 wpabuf_put_property(buf, "WLANEvent", sm->wlanevent); 529 wpabuf_put_str(buf, format_tail); 530 531 wpa_printf(MSG_MSGDUMP, "WPS UPnP: WLANEvent message:\n%s", 532 (char *) wpabuf_head(buf)); 533 534 dl_list_for_each_safe(s, tmp, &sm->subscriptions, struct subscription, 535 list) { 536 event_add(s, buf, 537 sm->wlanevent_type == UPNP_WPS_WLANEVENT_TYPE_PROBE); 538 } 539 540 wpabuf_free(buf); 541 } 542 543 544 /* 545 * Event subscription (subscriber machines register with us to receive event 546 * messages). 547 * This is the result of an incoming HTTP over TCP SUBSCRIBE request. 548 */ 549 550 /* subscription_destroy -- destroy an unlinked subscription 551 * Be sure to unlink first if necessary. 552 */ 553 void subscription_destroy(struct subscription *s) 554 { 555 struct upnp_wps_device_interface *iface; 556 wpa_printf(MSG_DEBUG, "WPS UPnP: Destroy subscription %p", s); 557 subscr_addr_free_all(s); 558 event_delete_all(s); 559 dl_list_for_each(iface, &s->sm->interfaces, 560 struct upnp_wps_device_interface, list) 561 upnp_er_remove_notification(iface->wps->registrar, s); 562 os_free(s); 563 } 564 565 566 /* subscription_list_age -- remove expired subscriptions */ 567 static void subscription_list_age(struct upnp_wps_device_sm *sm, time_t now) 568 { 569 struct subscription *s, *tmp; 570 dl_list_for_each_safe(s, tmp, &sm->subscriptions, 571 struct subscription, list) { 572 if (s->timeout_time > now) 573 break; 574 wpa_printf(MSG_DEBUG, "WPS UPnP: Removing aged subscription"); 575 dl_list_del(&s->list); 576 subscription_destroy(s); 577 } 578 } 579 580 581 /* subscription_find -- return existing subscription matching uuid, if any 582 * returns NULL if not found 583 */ 584 struct subscription * subscription_find(struct upnp_wps_device_sm *sm, 585 const u8 uuid[UUID_LEN]) 586 { 587 struct subscription *s; 588 dl_list_for_each(s, &sm->subscriptions, struct subscription, list) { 589 if (os_memcmp(s->uuid, uuid, UUID_LEN) == 0) 590 return s; /* Found match */ 591 } 592 return NULL; 593 } 594 595 596 static struct wpabuf * build_fake_wsc_ack(void) 597 { 598 struct wpabuf *msg = wpabuf_alloc(100); 599 if (msg == NULL) 600 return NULL; 601 wpabuf_put_u8(msg, UPNP_WPS_WLANEVENT_TYPE_EAP); 602 wpabuf_put_str(msg, "00:00:00:00:00:00"); 603 if (wps_build_version(msg) || 604 wps_build_msg_type(msg, WPS_WSC_ACK)) { 605 wpabuf_free(msg); 606 return NULL; 607 } 608 /* Enrollee Nonce */ 609 wpabuf_put_be16(msg, ATTR_ENROLLEE_NONCE); 610 wpabuf_put_be16(msg, WPS_NONCE_LEN); 611 wpabuf_put(msg, WPS_NONCE_LEN); 612 /* Registrar Nonce */ 613 wpabuf_put_be16(msg, ATTR_REGISTRAR_NONCE); 614 wpabuf_put_be16(msg, WPS_NONCE_LEN); 615 wpabuf_put(msg, WPS_NONCE_LEN); 616 wps_build_wfa_ext(msg, 0, NULL, 0); 617 return msg; 618 } 619 620 621 /* subscription_first_event -- send format/queue event that is automatically 622 * sent on a new subscription. 623 */ 624 static int subscription_first_event(struct subscription *s) 625 { 626 /* 627 * Actually, utf-8 is the default, but it doesn't hurt to specify it. 628 * 629 * APStatus is apparently a bit set, 630 * 0x1 = configuration change (but is always set?) 631 * 0x10 = ap is locked 632 * 633 * Per UPnP spec, we send out the last value of each variable, even 634 * for WLANEvent, whatever it was. 635 */ 636 char *wlan_event; 637 struct wpabuf *buf; 638 int ap_status = 1; /* TODO: add 0x10 if access point is locked */ 639 const char *head = 640 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" 641 "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n"; 642 const char *tail = "</e:propertyset>\n"; 643 char txt[10]; 644 int ret; 645 646 if (s->sm->wlanevent == NULL) { 647 /* 648 * There has been no events before the subscription. However, 649 * UPnP device architecture specification requires all the 650 * evented variables to be included, so generate a dummy event 651 * for this particular case using a WSC_ACK and all-zeros 652 * nonces. The ER (UPnP control point) will ignore this, but at 653 * least it will learn that WLANEvent variable will be used in 654 * event notifications in the future. 655 */ 656 struct wpabuf *msg; 657 wpa_printf(MSG_DEBUG, "WPS UPnP: Use a fake WSC_ACK as the " 658 "initial WLANEvent"); 659 msg = build_fake_wsc_ack(); 660 if (msg) { 661 s->sm->wlanevent = (char *) 662 base64_encode(wpabuf_head(msg), 663 wpabuf_len(msg), NULL); 664 wpabuf_free(msg); 665 } 666 } 667 668 wlan_event = s->sm->wlanevent; 669 if (wlan_event == NULL || *wlan_event == '\0') { 670 wpa_printf(MSG_DEBUG, "WPS UPnP: WLANEvent not known for " 671 "initial event message"); 672 wlan_event = ""; 673 } 674 buf = wpabuf_alloc(500 + os_strlen(wlan_event)); 675 if (buf == NULL) 676 return -1; 677 678 wpabuf_put_str(buf, head); 679 wpabuf_put_property(buf, "STAStatus", "1"); 680 os_snprintf(txt, sizeof(txt), "%d", ap_status); 681 wpabuf_put_property(buf, "APStatus", txt); 682 if (*wlan_event) 683 wpabuf_put_property(buf, "WLANEvent", wlan_event); 684 wpabuf_put_str(buf, tail); 685 686 ret = event_add(s, buf, 0); 687 if (ret) { 688 wpabuf_free(buf); 689 return ret; 690 } 691 wpabuf_free(buf); 692 693 return 0; 694 } 695 696 697 /** 698 * subscription_start - Remember a UPnP control point to send events to. 699 * @sm: WPS UPnP state machine from upnp_wps_device_init() 700 * @callback_urls: Callback URLs 701 * Returns: %NULL on error, or pointer to new subscription structure. 702 */ 703 struct subscription * subscription_start(struct upnp_wps_device_sm *sm, 704 const char *callback_urls) 705 { 706 struct subscription *s; 707 time_t now = time(NULL); 708 time_t expire = now + UPNP_SUBSCRIBE_SEC; 709 710 /* Get rid of expired subscriptions so we have room */ 711 subscription_list_age(sm, now); 712 713 /* If too many subscriptions, remove oldest */ 714 if (dl_list_len(&sm->subscriptions) >= MAX_SUBSCRIPTIONS) { 715 s = dl_list_first(&sm->subscriptions, struct subscription, 716 list); 717 wpa_printf(MSG_INFO, "WPS UPnP: Too many subscriptions, " 718 "trashing oldest"); 719 dl_list_del(&s->list); 720 subscription_destroy(s); 721 } 722 723 s = os_zalloc(sizeof(*s)); 724 if (s == NULL) 725 return NULL; 726 dl_list_init(&s->addr_list); 727 dl_list_init(&s->event_queue); 728 729 s->sm = sm; 730 s->timeout_time = expire; 731 uuid_make(s->uuid); 732 subscr_addr_list_create(s, callback_urls); 733 if (dl_list_empty(&s->addr_list)) { 734 wpa_printf(MSG_DEBUG, "WPS UPnP: No valid callback URLs in " 735 "'%s' - drop subscription", callback_urls); 736 subscription_destroy(s); 737 return NULL; 738 } 739 740 /* Add to end of list, since it has the highest expiration time */ 741 dl_list_add_tail(&sm->subscriptions, &s->list); 742 /* Queue up immediate event message (our last event) 743 * as required by UPnP spec. 744 */ 745 if (subscription_first_event(s)) { 746 wpa_printf(MSG_INFO, "WPS UPnP: Dropping subscriber due to " 747 "event backlog"); 748 dl_list_del(&s->list); 749 subscription_destroy(s); 750 return NULL; 751 } 752 wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription %p started with %s", 753 s, callback_urls); 754 /* Schedule sending this */ 755 event_send_all_later(sm); 756 return s; 757 } 758 759 760 /* subscription_renew -- find subscription and reset timeout */ 761 struct subscription * subscription_renew(struct upnp_wps_device_sm *sm, 762 const u8 uuid[UUID_LEN]) 763 { 764 time_t now = time(NULL); 765 time_t expire = now + UPNP_SUBSCRIBE_SEC; 766 struct subscription *s = subscription_find(sm, uuid); 767 if (s == NULL) 768 return NULL; 769 wpa_printf(MSG_DEBUG, "WPS UPnP: Subscription renewed"); 770 dl_list_del(&s->list); 771 s->timeout_time = expire; 772 /* add back to end of list, since it now has highest expiry */ 773 dl_list_add_tail(&sm->subscriptions, &s->list); 774 return s; 775 } 776 777 778 /** 779 * upnp_wps_device_send_wlan_event - Event notification 780 * @sm: WPS UPnP state machine from upnp_wps_device_init() 781 * @from_mac_addr: Source (Enrollee) MAC address for the event 782 * @ev_type: Event type 783 * @msg: Event data 784 * Returns: 0 on success, -1 on failure 785 * 786 * Tell external Registrars (UPnP control points) that something happened. In 787 * particular, events include WPS messages from clients that are proxied to 788 * external Registrars. 789 */ 790 int upnp_wps_device_send_wlan_event(struct upnp_wps_device_sm *sm, 791 const u8 from_mac_addr[ETH_ALEN], 792 enum upnp_wps_wlanevent_type ev_type, 793 const struct wpabuf *msg) 794 { 795 int ret = -1; 796 char type[2]; 797 const u8 *mac = from_mac_addr; 798 char mac_text[18]; 799 u8 *raw = NULL; 800 size_t raw_len; 801 char *val; 802 size_t val_len; 803 int pos = 0; 804 805 if (!sm) 806 goto fail; 807 808 os_snprintf(type, sizeof(type), "%1u", ev_type); 809 810 raw_len = 1 + 17 + (msg ? wpabuf_len(msg) : 0); 811 raw = os_zalloc(raw_len); 812 if (!raw) 813 goto fail; 814 815 *(raw + pos) = (u8) ev_type; 816 pos += 1; 817 os_snprintf(mac_text, sizeof(mac_text), MACSTR, MAC2STR(mac)); 818 wpa_printf(MSG_DEBUG, "WPS UPnP: Proxying WLANEvent from %s", 819 mac_text); 820 os_memcpy(raw + pos, mac_text, 17); 821 pos += 17; 822 if (msg) { 823 os_memcpy(raw + pos, wpabuf_head(msg), wpabuf_len(msg)); 824 pos += wpabuf_len(msg); 825 } 826 raw_len = pos; 827 828 val = (char *) base64_encode(raw, raw_len, &val_len); 829 if (val == NULL) 830 goto fail; 831 832 os_free(sm->wlanevent); 833 sm->wlanevent = val; 834 sm->wlanevent_type = ev_type; 835 upnp_wps_device_send_event(sm); 836 837 ret = 0; 838 839 fail: 840 os_free(raw); 841 842 return ret; 843 } 844 845 846 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) 847 #include <sys/sysctl.h> 848 #include <net/route.h> 849 #include <net/if_dl.h> 850 851 static int eth_get(const char *device, u8 ea[ETH_ALEN]) 852 { 853 struct if_msghdr *ifm; 854 struct sockaddr_dl *sdl; 855 u_char *p, *buf; 856 size_t len; 857 int mib[] = { CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0 }; 858 859 if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) 860 return -1; 861 if ((buf = os_malloc(len)) == NULL) 862 return -1; 863 if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { 864 os_free(buf); 865 return -1; 866 } 867 for (p = buf; p < buf + len; p += ifm->ifm_msglen) { 868 ifm = (struct if_msghdr *)p; 869 sdl = (struct sockaddr_dl *)(ifm + 1); 870 if (ifm->ifm_type != RTM_IFINFO || 871 (ifm->ifm_addrs & RTA_IFP) == 0) 872 continue; 873 if (sdl->sdl_family != AF_LINK || sdl->sdl_nlen == 0 || 874 os_memcmp(sdl->sdl_data, device, sdl->sdl_nlen) != 0) 875 continue; 876 os_memcpy(ea, LLADDR(sdl), sdl->sdl_alen); 877 break; 878 } 879 os_free(buf); 880 881 if (p >= buf + len) { 882 errno = ESRCH; 883 return -1; 884 } 885 return 0; 886 } 887 #endif /* __FreeBSD__ */ 888 889 890 /** 891 * get_netif_info - Get hw and IP addresses for network device 892 * @net_if: Selected network interface name 893 * @ip_addr: Buffer for returning IP address in network byte order 894 * @ip_addr_text: Buffer for returning a pointer to allocated IP address text 895 * @mac: Buffer for returning MAC address 896 * Returns: 0 on success, -1 on failure 897 */ 898 int get_netif_info(const char *net_if, unsigned *ip_addr, char **ip_addr_text, 899 u8 mac[ETH_ALEN]) 900 { 901 struct ifreq req; 902 int sock = -1; 903 struct sockaddr_in *addr; 904 struct in_addr in_addr; 905 906 *ip_addr_text = os_zalloc(16); 907 if (*ip_addr_text == NULL) 908 goto fail; 909 910 sock = socket(AF_INET, SOCK_DGRAM, 0); 911 if (sock < 0) 912 goto fail; 913 914 os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name)); 915 if (ioctl(sock, SIOCGIFADDR, &req) < 0) { 916 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFADDR failed: %d (%s)", 917 errno, strerror(errno)); 918 goto fail; 919 } 920 addr = (void *) &req.ifr_addr; 921 *ip_addr = addr->sin_addr.s_addr; 922 in_addr.s_addr = *ip_addr; 923 os_snprintf(*ip_addr_text, 16, "%s", inet_ntoa(in_addr)); 924 925 #ifdef __linux__ 926 os_strlcpy(req.ifr_name, net_if, sizeof(req.ifr_name)); 927 if (ioctl(sock, SIOCGIFHWADDR, &req) < 0) { 928 wpa_printf(MSG_ERROR, "WPS UPnP: SIOCGIFHWADDR failed: " 929 "%d (%s)", errno, strerror(errno)); 930 goto fail; 931 } 932 os_memcpy(mac, req.ifr_addr.sa_data, 6); 933 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) 934 if (eth_get(net_if, mac) < 0) { 935 wpa_printf(MSG_ERROR, "WPS UPnP: Failed to get MAC address"); 936 goto fail; 937 } 938 #else 939 #error MAC address fetch not implemented 940 #endif 941 942 close(sock); 943 return 0; 944 945 fail: 946 if (sock >= 0) 947 close(sock); 948 os_free(*ip_addr_text); 949 *ip_addr_text = NULL; 950 return -1; 951 } 952 953 954 static void upnp_wps_free_msearchreply(struct dl_list *head) 955 { 956 struct advertisement_state_machine *a, *tmp; 957 dl_list_for_each_safe(a, tmp, head, struct advertisement_state_machine, 958 list) 959 msearchreply_state_machine_stop(a); 960 } 961 962 963 static void upnp_wps_free_subscriptions(struct dl_list *head, 964 struct wps_registrar *reg) 965 { 966 struct subscription *s, *tmp; 967 dl_list_for_each_safe(s, tmp, head, struct subscription, list) { 968 if (reg && s->reg != reg) 969 continue; 970 dl_list_del(&s->list); 971 subscription_destroy(s); 972 } 973 } 974 975 976 /** 977 * upnp_wps_device_stop - Stop WPS UPnP operations on an interface 978 * @sm: WPS UPnP state machine from upnp_wps_device_init() 979 */ 980 static void upnp_wps_device_stop(struct upnp_wps_device_sm *sm) 981 { 982 if (!sm || !sm->started) 983 return; 984 985 wpa_printf(MSG_DEBUG, "WPS UPnP: Stop device"); 986 web_listener_stop(sm); 987 upnp_wps_free_msearchreply(&sm->msearch_replies); 988 upnp_wps_free_subscriptions(&sm->subscriptions, NULL); 989 990 advertisement_state_machine_stop(sm, 1); 991 992 event_send_stop_all(sm); 993 os_free(sm->wlanevent); 994 sm->wlanevent = NULL; 995 os_free(sm->ip_addr_text); 996 sm->ip_addr_text = NULL; 997 if (sm->multicast_sd >= 0) 998 close(sm->multicast_sd); 999 sm->multicast_sd = -1; 1000 ssdp_listener_stop(sm); 1001 1002 sm->started = 0; 1003 } 1004 1005 1006 /** 1007 * upnp_wps_device_start - Start WPS UPnP operations on an interface 1008 * @sm: WPS UPnP state machine from upnp_wps_device_init() 1009 * @net_if: Selected network interface name 1010 * Returns: 0 on success, -1 on failure 1011 */ 1012 static int upnp_wps_device_start(struct upnp_wps_device_sm *sm, char *net_if) 1013 { 1014 if (!sm || !net_if) 1015 return -1; 1016 1017 if (sm->started) 1018 upnp_wps_device_stop(sm); 1019 1020 sm->multicast_sd = -1; 1021 sm->ssdp_sd = -1; 1022 sm->started = 1; 1023 sm->advertise_count = 0; 1024 1025 /* Fix up linux multicast handling */ 1026 if (add_ssdp_network(net_if)) 1027 goto fail; 1028 1029 /* Determine which IP and mac address we're using */ 1030 if (get_netif_info(net_if, &sm->ip_addr, &sm->ip_addr_text, 1031 sm->mac_addr)) { 1032 wpa_printf(MSG_INFO, "WPS UPnP: Could not get IP/MAC address " 1033 "for %s. Does it have IP address?", net_if); 1034 goto fail; 1035 } 1036 1037 /* Listen for incoming TCP connections so that others 1038 * can fetch our "xml files" from us. 1039 */ 1040 if (web_listener_start(sm)) 1041 goto fail; 1042 1043 /* Set up for receiving discovery (UDP) packets */ 1044 if (ssdp_listener_start(sm)) 1045 goto fail; 1046 1047 /* Set up for sending multicast */ 1048 if (ssdp_open_multicast(sm) < 0) 1049 goto fail; 1050 1051 /* 1052 * Broadcast NOTIFY messages to let the world know we exist. 1053 * This is done via a state machine since the messages should not be 1054 * all sent out at once. 1055 */ 1056 if (advertisement_state_machine_start(sm)) 1057 goto fail; 1058 1059 return 0; 1060 1061 fail: 1062 upnp_wps_device_stop(sm); 1063 return -1; 1064 } 1065 1066 1067 static struct upnp_wps_device_interface * 1068 upnp_wps_get_iface(struct upnp_wps_device_sm *sm, void *priv) 1069 { 1070 struct upnp_wps_device_interface *iface; 1071 dl_list_for_each(iface, &sm->interfaces, 1072 struct upnp_wps_device_interface, list) { 1073 if (iface->priv == priv) 1074 return iface; 1075 } 1076 return NULL; 1077 } 1078 1079 1080 /** 1081 * upnp_wps_device_deinit - Deinitialize WPS UPnP 1082 * @sm: WPS UPnP state machine from upnp_wps_device_init() 1083 * @priv: External context data that was used in upnp_wps_device_init() call 1084 */ 1085 void upnp_wps_device_deinit(struct upnp_wps_device_sm *sm, void *priv) 1086 { 1087 struct upnp_wps_device_interface *iface; 1088 1089 if (!sm) 1090 return; 1091 1092 iface = upnp_wps_get_iface(sm, priv); 1093 if (iface == NULL) { 1094 wpa_printf(MSG_ERROR, "WPS UPnP: Could not find the interface " 1095 "instance to deinit"); 1096 return; 1097 } 1098 wpa_printf(MSG_DEBUG, "WPS UPnP: Deinit interface instance %p", iface); 1099 if (dl_list_len(&sm->interfaces) == 1) { 1100 wpa_printf(MSG_DEBUG, "WPS UPnP: Deinitializing last instance " 1101 "- free global device instance"); 1102 upnp_wps_device_stop(sm); 1103 } else 1104 upnp_wps_free_subscriptions(&sm->subscriptions, 1105 iface->wps->registrar); 1106 dl_list_del(&iface->list); 1107 1108 if (iface->peer.wps) 1109 wps_deinit(iface->peer.wps); 1110 os_free(iface->ctx->ap_pin); 1111 os_free(iface->ctx); 1112 os_free(iface); 1113 1114 if (dl_list_empty(&sm->interfaces)) { 1115 os_free(sm->root_dir); 1116 os_free(sm->desc_url); 1117 os_free(sm); 1118 shared_upnp_device = NULL; 1119 } 1120 } 1121 1122 1123 /** 1124 * upnp_wps_device_init - Initialize WPS UPnP 1125 * @ctx: callback table; we must eventually free it 1126 * @wps: Pointer to longterm WPS context 1127 * @priv: External context data that will be used in callbacks 1128 * @net_if: Selected network interface name 1129 * Returns: WPS UPnP state or %NULL on failure 1130 */ 1131 struct upnp_wps_device_sm * 1132 upnp_wps_device_init(struct upnp_wps_device_ctx *ctx, struct wps_context *wps, 1133 void *priv, char *net_if) 1134 { 1135 struct upnp_wps_device_sm *sm; 1136 struct upnp_wps_device_interface *iface; 1137 int start = 0; 1138 1139 iface = os_zalloc(sizeof(*iface)); 1140 if (iface == NULL) { 1141 os_free(ctx->ap_pin); 1142 os_free(ctx); 1143 return NULL; 1144 } 1145 wpa_printf(MSG_DEBUG, "WPS UPnP: Init interface instance %p", iface); 1146 1147 iface->ctx = ctx; 1148 iface->wps = wps; 1149 iface->priv = priv; 1150 1151 if (shared_upnp_device) { 1152 wpa_printf(MSG_DEBUG, "WPS UPnP: Share existing device " 1153 "context"); 1154 sm = shared_upnp_device; 1155 } else { 1156 wpa_printf(MSG_DEBUG, "WPS UPnP: Initialize device context"); 1157 sm = os_zalloc(sizeof(*sm)); 1158 if (!sm) { 1159 wpa_printf(MSG_ERROR, "WPS UPnP: upnp_wps_device_init " 1160 "failed"); 1161 os_free(iface); 1162 os_free(ctx->ap_pin); 1163 os_free(ctx); 1164 return NULL; 1165 } 1166 shared_upnp_device = sm; 1167 1168 dl_list_init(&sm->msearch_replies); 1169 dl_list_init(&sm->subscriptions); 1170 dl_list_init(&sm->interfaces); 1171 start = 1; 1172 } 1173 1174 dl_list_add(&sm->interfaces, &iface->list); 1175 1176 if (start && upnp_wps_device_start(sm, net_if)) { 1177 upnp_wps_device_deinit(sm, priv); 1178 return NULL; 1179 } 1180 1181 1182 return sm; 1183 } 1184 1185 1186 /** 1187 * upnp_wps_subscribers - Check whether there are any event subscribers 1188 * @sm: WPS UPnP state machine from upnp_wps_device_init() 1189 * Returns: 0 if no subscribers, 1 if subscribers 1190 */ 1191 int upnp_wps_subscribers(struct upnp_wps_device_sm *sm) 1192 { 1193 return !dl_list_empty(&sm->subscriptions); 1194 } 1195 1196 1197 int upnp_wps_set_ap_pin(struct upnp_wps_device_sm *sm, const char *ap_pin) 1198 { 1199 struct upnp_wps_device_interface *iface; 1200 if (sm == NULL) 1201 return 0; 1202 1203 dl_list_for_each(iface, &sm->interfaces, 1204 struct upnp_wps_device_interface, list) { 1205 os_free(iface->ctx->ap_pin); 1206 if (ap_pin) { 1207 iface->ctx->ap_pin = os_strdup(ap_pin); 1208 if (iface->ctx->ap_pin == NULL) 1209 return -1; 1210 } else 1211 iface->ctx->ap_pin = NULL; 1212 } 1213 1214 return 0; 1215 } 1216