gpst.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. /*
  2. * OpenConnect (SSL + DTLS) VPN client
  3. *
  4. * Copyright © 2016-2017 Daniel Lenski
  5. *
  6. * Author: Daniel Lenski <dlenski@gmail.com>
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public License
  10. * version 2.1, as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. */
  17. #include <config.h>
  18. #include "openconnect-internal.h"
  19. #ifdef HAVE_LZ4
  20. #include <lz4.h>
  21. #endif
  22. #include <unistd.h>
  23. #include <fcntl.h>
  24. #include <sys/types.h>
  25. #ifdef _WIN32
  26. #include "win32-ipicmp.h"
  27. #else
  28. #include <sys/wait.h>
  29. /* The BSDs require the first two headers before netinet/ip.h
  30. * (Linux and macOS already #include them within netinet/ip.h)
  31. */
  32. #include <netinet/in_systm.h>
  33. #include <netinet/in.h>
  34. #include <netinet/ip.h>
  35. #include <netinet/ip_icmp.h>
  36. #include <netinet/ip6.h>
  37. #include <netinet/icmp6.h>
  38. #endif
  39. #if defined(__linux__)
  40. /* For TCP_INFO */
  41. # include <linux/tcp.h>
  42. #endif
  43. #include <time.h>
  44. #include <string.h>
  45. #include <ctype.h>
  46. #include <errno.h>
  47. #include <stdlib.h>
  48. #include <stdio.h>
  49. #include <stdarg.h>
  50. /*
  51. * Data packets are encapsulated in the SSL stream as follows:
  52. *
  53. * 0000: Magic "\x1a\x2b\x3c\x4d"
  54. * 0004: Big-endian EtherType (0x0800 for IPv4)
  55. * 0006: Big-endian 16-bit length (not including 16-byte header)
  56. * 0008: Always "\x01\0\0\0\0\0\0\0"
  57. * 0010: data payload
  58. */
  59. /* Strange initialisers here to work around GCC PR#10676 (which was
  60. * fixed in GCC 4.6 but it takes a while for some systems to catch
  61. * up. */
  62. static const struct pkt dpd_pkt = {
  63. .next = NULL,
  64. { .gpst.hdr = { 0x1a, 0x2b, 0x3c, 0x4d } }
  65. };
  66. static int filter_opts(struct oc_text_buf *buf, const char *query, const char *incexc, int include)
  67. {
  68. const char *f, *endf, *eq;
  69. const char *found, *comma;
  70. for (f = query; *f; f=(*endf) ? endf+1 : endf) {
  71. endf = strchrnul(f, '&');
  72. eq = strchr(f, '=');
  73. if (!eq || eq > endf)
  74. eq = endf;
  75. for (found = incexc; *found; found=(*comma) ? comma+1 : comma) {
  76. comma = strchrnul(found, ',');
  77. if (!strncmp(found, f, MAX(comma-found, eq-f)))
  78. break;
  79. }
  80. if ((include && *found) || (!include && !*found)) {
  81. if (buf->pos && buf->data[buf->pos-1] != '?' && buf->data[buf->pos-1] != '&')
  82. buf_append(buf, "&");
  83. buf_append_bytes(buf, f, (int)(endf-f));
  84. }
  85. }
  86. return buf_error(buf);
  87. }
  88. /* Parse this JavaScript-y mess:
  89. "var respStatus = \"Challenge|Error\";\n"
  90. "var respMsg = \"<prompt>\";\n"
  91. "thisForm.inputStr.value = "<inputStr>";\n"
  92. */
  93. static int parse_javascript(char *buf, char **prompt, char **inputStr)
  94. {
  95. const char *start, *end = buf;
  96. int status;
  97. const char *pre_status = "var respStatus = \"",
  98. *pre_prompt = "var respMsg = \"",
  99. *pre_inputStr = "thisForm.inputStr.value = \"";
  100. /* Status */
  101. while (isspace(*end))
  102. end++;
  103. if (strncmp(end, pre_status, strlen(pre_status)))
  104. goto err;
  105. start = end+strlen(pre_status);
  106. end = strchr(start, '\n');
  107. if (!end || end[-1] != ';' || end[-2] != '"')
  108. goto err;
  109. if (!strncmp(start, "Challenge", 8)) status = 0;
  110. else if (!strncmp(start, "Error", 5)) status = 1;
  111. else goto err;
  112. /* Prompt */
  113. while (isspace(*end))
  114. end++;
  115. if (strncmp(end, pre_prompt, strlen(pre_prompt)))
  116. goto err;
  117. start = end+strlen(pre_prompt);
  118. end = strchr(start, '\n');
  119. if (!end || end[-1] != ';' || end[-2] != '"' || (end<start+2))
  120. goto err;
  121. if (prompt)
  122. *prompt = strndup(start, end-start-2);
  123. /* inputStr */
  124. while (isspace(*end))
  125. end++;
  126. if (strncmp(end, pre_inputStr, strlen(pre_inputStr)))
  127. goto err2;
  128. start = end+strlen(pre_inputStr);
  129. end = strchr(start, '\n');
  130. if (!end || end[-1] != ';' || end[-2] != '"' || (end<start+2))
  131. goto err2;
  132. if (inputStr)
  133. *inputStr = strndup(start, end-start-2);
  134. while (isspace(*end))
  135. end++;
  136. if (*end != '\0')
  137. goto err3;
  138. return status;
  139. err3:
  140. if (inputStr) free(*inputStr);
  141. err2:
  142. if (prompt) free(*prompt);
  143. err:
  144. return -EINVAL;
  145. }
  146. int gpst_xml_or_error(struct openconnect_info *vpninfo, char *response,
  147. int (*xml_cb)(struct openconnect_info *, xmlNode *xml_node, void *cb_data),
  148. int (*challenge_cb)(struct openconnect_info *, char *prompt, char *inputStr, void *cb_data),
  149. void *cb_data)
  150. {
  151. xmlDocPtr xml_doc;
  152. xmlNode *xml_node;
  153. char *err = NULL;
  154. char *prompt = NULL, *inputStr = NULL;
  155. int result = -EINVAL;
  156. if (!response) {
  157. vpn_progress(vpninfo, PRG_ERR,
  158. _("Empty response from server\n"));
  159. return -EINVAL;
  160. }
  161. /* We need to distinguish XML from non-XML input, since GlobalProtect servers can
  162. * provide challenge-based 2FA in either XML or Javascript-y format with no
  163. * warning. See the discovery of this at
  164. * https://github.com/dlenski/openconnect/issues/109#issuecomment-391025707
  165. *
  166. * However, we also want to be able to use XML_PARSE_RECOVER in order to
  167. * parse XML leniently. With this flag, xmlReadMemory won't return NULL,
  168. * but will return an "empty" XML document, with a NULL root node.
  169. */
  170. xml_doc = xmlReadMemory(response, strlen(response), NULL, NULL,
  171. XML_PARSE_NOERROR|XML_PARSE_RECOVER);
  172. xml_node = xmlDocGetRootElement(xml_doc);
  173. if (!xml_node) {
  174. /* is it Javascript? */
  175. result = parse_javascript(response, &prompt, &inputStr);
  176. switch (result) {
  177. case 1:
  178. vpn_progress(vpninfo, PRG_ERR, _("%s\n"), prompt);
  179. break;
  180. case 0:
  181. vpn_progress(vpninfo, PRG_INFO, _("Challenge: %s\n"), prompt);
  182. result = challenge_cb ? challenge_cb(vpninfo, prompt, inputStr, cb_data) : -EINVAL;
  183. break;
  184. default:
  185. vpn_progress(vpninfo, PRG_ERR, _("Failed to parse non-XML server response\n"));
  186. vpn_progress(vpninfo, PRG_DEBUG, _("Response was: %s\n"), response);
  187. goto out;
  188. }
  189. free(prompt);
  190. free(inputStr);
  191. } else {
  192. xml_node = xmlDocGetRootElement(xml_doc);
  193. /* is it <response status="error"><error>..</error></response> ? */
  194. if (xmlnode_is_named(xml_node, "response")
  195. && !xmlnode_match_prop(xml_node, "status", "error")) {
  196. for (xml_node=xml_node->children; xml_node; xml_node=xml_node->next) {
  197. if (!xmlnode_get_val(xml_node, "error", &err))
  198. goto out;
  199. }
  200. }
  201. /* Is it <prelogin-response><status>Error</status><msg>..</msg></prelogin-response> ? */
  202. else if (xmlnode_is_named(xml_node, "prelogin-response")) {
  203. char *s = NULL;
  204. int has_err = 0;
  205. xmlNode *x;
  206. for (x=xml_node->children; x; x=x->next) {
  207. if (!xmlnode_get_val(x, "status", &s))
  208. has_err = strcmp(s, "Success");
  209. else
  210. xmlnode_get_val(x, "msg", &err);
  211. }
  212. free(s);
  213. if (has_err)
  214. goto out;
  215. free(err);
  216. err = NULL;
  217. goto xml_callback;
  218. }
  219. /* is it <challenge><user>user.name</user><inputstr>...</inputstr><respmsg>...</respmsg></challenge> */
  220. else if (xmlnode_is_named(xml_node, "challenge")) {
  221. for (xml_node=xml_node->children; xml_node; xml_node=xml_node->next) {
  222. xmlnode_get_val(xml_node, "inputstr", &inputStr);
  223. xmlnode_get_val(xml_node, "respmsg", &prompt);
  224. /* XXX: override the username passed to the next form from <user> ? */
  225. }
  226. result = challenge_cb ? challenge_cb(vpninfo, prompt, inputStr, cb_data) : -EINVAL;
  227. free(prompt);
  228. free(inputStr);
  229. }
  230. /* invoke XML callback (or default to success) */
  231. else
  232. xml_callback:
  233. result = xml_cb ? xml_cb(vpninfo, xml_node, cb_data) : 0;
  234. if (result == -EINVAL) {
  235. vpn_progress(vpninfo, PRG_ERR,
  236. _("Failed to parse XML server response\n"));
  237. vpn_progress(vpninfo, PRG_DEBUG,
  238. _("Response was: %s\n"), response);
  239. }
  240. }
  241. out:
  242. if (err) {
  243. if (!strcmp(err, "GlobalProtect gateway does not exist")
  244. || !strcmp(err, "GlobalProtect portal does not exist")) {
  245. vpn_progress(vpninfo, PRG_DEBUG, "%s\n", err);
  246. result = -EEXIST;
  247. } else if (!strcmp(err, "Invalid authentication cookie") /* equivalent to custom HTTP status 512 */
  248. || !strcmp(err, "Portal name not found") /* cookie is bogus */
  249. || !strcmp(err, "Valid client certificate is required") /* equivalent to custom HTTP status 513 */
  250. || !strcmp(err, "Allow Automatic Restoration of SSL VPN is disabled")) {
  251. /* Any of these errors indicates that retrying won't help us reconnect (EPERM signals this to mainloop.) */
  252. vpn_progress(vpninfo, PRG_ERR, "%s\n", err);
  253. result = -EPERM;
  254. } else {
  255. vpn_progress(vpninfo, PRG_ERR, "%s\n", err);
  256. result = -EINVAL;
  257. }
  258. free(err);
  259. }
  260. if (xml_doc)
  261. xmlFreeDoc(xml_doc);
  262. return result;
  263. }
  264. #define ESP_HEADER_SIZE (4 /* SPI */ + 4 /* sequence number */)
  265. #define ESP_FOOTER_SIZE (1 /* pad length */ + 1 /* next header */)
  266. #ifdef HAVE_ESP
  267. static int check_hmac_algo(struct openconnect_info *v, const char *s)
  268. {
  269. if (!strcmp(s, "sha1")) return HMAC_SHA1;
  270. if (!strcmp(s, "md5")) return HMAC_MD5;
  271. if (!strcmp(s, "sha256")) return HMAC_SHA256;
  272. vpn_progress(v, PRG_ERR, _("Unknown ESP MAC algorithm: %s\n"), s);
  273. return -ENOENT;
  274. }
  275. static int check_enc_algo(struct openconnect_info *v, const char *s)
  276. {
  277. if (!strcmp(s, "aes128") || !strcmp(s, "aes-128-cbc")) return ENC_AES_128_CBC;
  278. if (!strcmp(s, "aes-256-cbc")) return ENC_AES_256_CBC;
  279. vpn_progress(v, PRG_ERR, _("Unknown ESP encryption algorithm: %s\n"), s);
  280. return -ENOENT;
  281. }
  282. /* Reads <KEYTAG/><bits>N</bits><val>hex digits</val></KEYTAG> and saves the
  283. * key in dest, returning its length in bytes.
  284. */
  285. static int xml_to_key(xmlNode *xml_node, unsigned char *dest, int dest_size)
  286. {
  287. int explen = -1, len = 0;
  288. xmlNode *child;
  289. char *p, *s = NULL;
  290. for (child = xml_node->children; child; child=child->next) {
  291. if (xmlnode_get_val(child, "bits", &s) == 0) {
  292. explen = atoi(s);
  293. if (explen & 0x07) goto out;
  294. explen >>= 3;
  295. } else if (xmlnode_get_val(child, "val", &s) == 0) {
  296. for (p=s; p[0] && p[1]; p+=2)
  297. if (len++ < dest_size)
  298. *dest++ = unhex(p);
  299. }
  300. }
  301. out:
  302. free(s);
  303. return (len == explen) ? len : -EINVAL;
  304. }
  305. #endif
  306. /* Return value:
  307. * < 0, on error
  308. * = 0, on success; *form is populated
  309. */
  310. static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_node, void *cb_data)
  311. {
  312. xmlNode *member;
  313. int n_dns = 0, esp_keys = 0, esp_v4 = 0, esp_v6 = 0;
  314. int ret = 0;
  315. char *s = NULL;
  316. int ii;
  317. uint32_t esp_magic = 0;
  318. struct in6_addr esp6_magic;
  319. if (!xml_node || !xmlnode_is_named(xml_node, "response"))
  320. return -EINVAL;
  321. struct oc_vpn_option *new_opts = NULL;
  322. struct oc_ip_info new_ip_info = {};
  323. memset(vpninfo->esp_magic, 0, sizeof(vpninfo->esp_magic));
  324. vpninfo->esp_replay_protect = 1;
  325. vpninfo->ssl_times.rekey_method = REKEY_NONE;
  326. /* Parse config */
  327. for (xml_node = xml_node->children; xml_node; xml_node=xml_node->next) {
  328. if (!xmlnode_get_val(xml_node, "ip-address", &s))
  329. new_ip_info.addr = add_option_steal(&new_opts, "ipaddr", &s);
  330. else if (!xmlnode_get_val(xml_node, "ip-address-v6", &s)) {
  331. if (!vpninfo->disable_ipv6)
  332. new_ip_info.addr6 = add_option_steal(&new_opts, "ipaddr6", &s);
  333. } else if (!xmlnode_get_val(xml_node, "netmask", &s)) {
  334. new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
  335. } else if (!xmlnode_get_val(xml_node, "mtu", &s))
  336. new_ip_info.mtu = atoi(s);
  337. else if (!xmlnode_get_val(xml_node, "lifetime", &s))
  338. vpninfo->auth_expiration = time(NULL) + atol(s);
  339. else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
  340. if (strcmp(s, "no"))
  341. vpn_progress(vpninfo, PRG_DEBUG,
  342. _("WARNING: Config XML contains <quarantine> tag with value of \"%s\".\n"
  343. " VPN connectivity may be disabled or limited.\n"), s);
  344. } else if (!xmlnode_get_val(xml_node, "disconnect-on-idle", &s)) {
  345. int sec = atoi(s);
  346. vpn_progress(vpninfo, PRG_INFO, _("Idle timeout is %d minutes.\n"), sec/60);
  347. vpninfo->idle_timeout = sec;
  348. } else if (!xmlnode_get_val(xml_node, "ssl-tunnel-url", &s)) {
  349. free(vpninfo->urlpath);
  350. vpninfo->urlpath = s;
  351. if (strcmp(s, "/ssl-tunnel-connect.sslvpn"))
  352. vpn_progress(vpninfo, PRG_INFO, _("Non-standard SSL tunnel path: %s\n"), s);
  353. s = NULL;
  354. } else if (!xmlnode_get_val(xml_node, "timeout", &s)) {
  355. int sec = atoi(s);
  356. vpn_progress(vpninfo, PRG_INFO, _("Tunnel timeout (rekey interval) is %d minutes.\n"), sec/60);
  357. vpninfo->ssl_times.last_rekey = time(NULL);
  358. vpninfo->ssl_times.rekey = sec - 60;
  359. vpninfo->ssl_times.rekey_method = REKEY_TUNNEL;
  360. } else if (!xmlnode_get_val(xml_node, "gw-address", &s)) {
  361. /* As remarked in oncp.c, "this is a tunnel; having a
  362. * gateway is meaningless." See esp_send_probes_gp for the
  363. * gory details of what this field actually means.
  364. */
  365. if (vpninfo->peer_addr->sa_family == IPPROTO_IP &&
  366. vpninfo->ip_info.gateway_addr && strcmp(s, vpninfo->ip_info.gateway_addr))
  367. vpn_progress(vpninfo, PRG_DEBUG,
  368. _("Gateway address in config XML (%s) differs from external gateway address (%s).\n"), s, new_ip_info.gateway_addr);
  369. esp_magic = inet_addr(s);
  370. esp_v4 = 1;
  371. } else if (!xmlnode_get_val(xml_node, "gw-address-v6", &s)) {
  372. if (vpninfo->peer_addr->sa_family == IPPROTO_IPV6 &&
  373. vpninfo->ip_info.gateway_addr && strcmp(s, vpninfo->ip_info.gateway_addr))
  374. vpn_progress(vpninfo, PRG_DEBUG,
  375. _("IPv6 gateway address in config XML (%s) differs from external gateway address (%s).\n"), s, vpninfo->ip_info.gateway_addr);
  376. inet_pton(AF_INET6, s, &esp6_magic);
  377. esp_v6 = 1;
  378. } else if (!xmlnode_get_val(xml_node, "connected-gw-ip", &s)) {
  379. if (vpninfo->ip_info.gateway_addr && strcmp(s, vpninfo->ip_info.gateway_addr))
  380. vpn_progress(vpninfo, PRG_DEBUG, _("Config XML <connected-gw-ip> address (%s) differs from external\n"
  381. "gateway address (%s). Please report this to\n"
  382. "<%s>, including any problems\n"
  383. "with ESP or other apparent loss of connectivity or performance.\n"),
  384. s, vpninfo->ip_info.gateway_addr, "openconnect-devel@lists.infradead.org");
  385. } else if (xmlnode_is_named(xml_node, "dns-v6") ||
  386. xmlnode_is_named(xml_node, "dns")) {
  387. for (member = xml_node->children; member && n_dns<3; member=member->next) {
  388. if (!xmlnode_get_val(member, "member", &s)) {
  389. for (ii=0; ii<n_dns; ii++)
  390. /* XX: frequent duplicates between <dns> and <dns-v6> */
  391. if (!strcmp(s, new_ip_info.dns[ii]))
  392. break;
  393. if (ii==n_dns)
  394. new_ip_info.dns[n_dns++] = add_option_steal(&new_opts, "DNS", &s);
  395. }
  396. }
  397. } else if (xmlnode_is_named(xml_node, "wins")) {
  398. for (ii=0, member = xml_node->children; member && ii<3; member=member->next)
  399. if (!xmlnode_get_val(member, "member", &s))
  400. new_ip_info.nbns[ii++] = add_option_steal(&new_opts, "WINS", &s);
  401. } else if (xmlnode_is_named(xml_node, "dns-suffix")) {
  402. struct oc_text_buf *domains = buf_alloc();
  403. for (member = xml_node->children; member; member=member->next)
  404. if (!xmlnode_get_val(member, "member", &s))
  405. buf_append(domains, "%s ", s);
  406. if (buf_error(domains) == 0 && domains->pos > 0) {
  407. domains->data[domains->pos-1] = '\0';
  408. new_ip_info.domain = add_option_steal(&new_opts, "search", &domains->data);
  409. }
  410. buf_free(domains);
  411. } else if (xmlnode_is_named(xml_node, "access-routes-v6") || xmlnode_is_named(xml_node, "exclude-access-routes-v6") ||
  412. xmlnode_is_named(xml_node, "access-routes") || xmlnode_is_named(xml_node, "exclude-access-routes")) {
  413. for (member = xml_node->children; member; member=member->next) {
  414. if (!xmlnode_get_val(member, "member", &s)) {
  415. struct oc_split_include *inc = malloc(sizeof(*inc));
  416. if (!inc) {
  417. ret = -ENOMEM;
  418. goto err;
  419. }
  420. if (xmlnode_is_named(xml_node, "access-routes")) {
  421. inc->route = add_option_steal(&new_opts, "split-include", &s);
  422. inc->next = new_ip_info.split_includes;
  423. new_ip_info.split_includes = inc;
  424. } else {
  425. inc->route = add_option_steal(&new_opts, "split-exclude", &s);
  426. inc->next = new_ip_info.split_excludes;
  427. new_ip_info.split_excludes = inc;
  428. }
  429. }
  430. }
  431. } else if (xmlnode_is_named(xml_node, "ipsec")) {
  432. #ifdef HAVE_ESP
  433. if (vpninfo->dtls_state != DTLS_DISABLED) {
  434. int c = (vpninfo->current_esp_in ^= 1);
  435. struct esp *ei = &vpninfo->esp_in[c], *eo = &vpninfo->esp_out;
  436. vpninfo->old_esp_maxseq = vpninfo->esp_in[c^1].seq + 32;
  437. for (member = xml_node->children; member; member=member->next) {
  438. if (!xmlnode_get_val(member, "udp-port", &s)) udp_sockaddr(vpninfo, atoi(s));
  439. else if (!xmlnode_get_val(member, "enc-algo", &s)) vpninfo->esp_enc = check_enc_algo(vpninfo, s);
  440. else if (!xmlnode_get_val(member, "hmac-algo", &s)) vpninfo->esp_hmac = check_hmac_algo(vpninfo, s);
  441. else if (!xmlnode_get_val(member, "c2s-spi", &s)) eo->spi = htonl(strtoul(s, NULL, 16));
  442. else if (!xmlnode_get_val(member, "s2c-spi", &s)) ei->spi = htonl(strtoul(s, NULL, 16));
  443. else if (xmlnode_is_named(member, "ekey-c2s")) vpninfo->enc_key_len = xml_to_key(member, eo->enc_key, sizeof(eo->enc_key));
  444. else if (xmlnode_is_named(member, "ekey-s2c")) vpninfo->enc_key_len = xml_to_key(member, ei->enc_key, sizeof(ei->enc_key));
  445. else if (xmlnode_is_named(member, "akey-c2s")) vpninfo->hmac_key_len = xml_to_key(member, eo->hmac_key, sizeof(eo->hmac_key));
  446. else if (xmlnode_is_named(member, "akey-s2c")) vpninfo->hmac_key_len = xml_to_key(member, ei->hmac_key, sizeof(ei->hmac_key));
  447. else if (!xmlnode_get_val(member, "ipsec-mode", &s) && strcmp(s, "esp-tunnel"))
  448. vpn_progress(vpninfo, PRG_ERR, _("GlobalProtect config sent ipsec-mode=%s (expected esp-tunnel)\n"), s);
  449. }
  450. if (!(vpninfo->esp_enc > 0 && vpninfo->esp_hmac > 0 && vpninfo->enc_key_len > 0 && vpninfo->hmac_key_len > 0))
  451. vpn_progress(vpninfo, PRG_ERR, "Server's ESP configuration is incomplete or uses unknown algorithms.\n");
  452. else
  453. esp_keys = 1;
  454. }
  455. #else
  456. vpn_progress(vpninfo, PRG_DEBUG, _("Ignoring ESP keys since ESP support not available in this build\n"));
  457. #endif
  458. } else if (xmlnode_is_named(xml_node, "need-tunnel")
  459. || xmlnode_is_named(xml_node, "bw-c2s")
  460. || xmlnode_is_named(xml_node, "bw-s2c")
  461. || xmlnode_is_named(xml_node, "default-gateway")
  462. || xmlnode_is_named(xml_node, "default-gateway-v6")
  463. || xmlnode_is_named(xml_node, "no-direct-access-to-local-network")
  464. || xmlnode_is_named(xml_node, "ip-address-preferred")
  465. || xmlnode_is_named(xml_node, "ip-address-v6-preferred")
  466. || xmlnode_is_named(xml_node, "ipv6-connection")
  467. || xmlnode_is_named(xml_node, "portal")
  468. || xmlnode_is_named(xml_node, "user")) {
  469. /* XX: Do these have any potential value at all for routing configuration or diagnostics? */
  470. } else if (xml_node->type == XML_ELEMENT_NODE) {
  471. free(s);
  472. s = (char *)xmlNodeGetContent(xml_node);
  473. if (strchr((char *)xml_node->name, '6'))
  474. vpn_progress(vpninfo, PRG_ERR, _("Potential IPv6-related GlobalProtect config tag <%s>: %s\n"), xml_node->name, s);
  475. else
  476. vpn_progress(vpninfo, PRG_DEBUG, _("Unknown GlobalProtect config tag <%s>: %s\n"), xml_node->name, s);
  477. }
  478. }
  479. /* Set 10-second DPD/keepalive (same as Windows client) unless
  480. * overridden with --force-dpd */
  481. if (!vpninfo->ssl_times.dpd)
  482. vpninfo->ssl_times.dpd = 10;
  483. vpninfo->ssl_times.keepalive = vpninfo->esp_ssl_fallback = vpninfo->ssl_times.dpd;
  484. /* Warn about IPv6 config, if present, and ESP config, if absent */
  485. if (new_ip_info.addr6)
  486. vpn_progress(vpninfo, PRG_ERR,
  487. _("GlobalProtect IPv6 support is experimental. Please report results to <%s>.\n"),
  488. "openconnect-devel@lists.infradead.org");
  489. #ifdef HAVE_ESP
  490. if (esp_keys && esp_v6 && new_ip_info.addr6) {
  491. /* We got ESP keys, an IPv6 esp_magic address, and an IPv6 address */
  492. vpninfo->esp_magic_af = AF_INET6;
  493. memcpy(vpninfo->esp_magic, &esp6_magic, sizeof(esp6_magic));
  494. setup_esp_keys:
  495. if (openconnect_setup_esp_keys(vpninfo, 0)) {
  496. vpn_progress(vpninfo, PRG_ERR, "Failed to setup ESP keys.\n");
  497. } else {
  498. /* prevent race condition between esp_mainloop() and gpst_mainloop() timers */
  499. vpninfo->dtls_times.last_rekey = time(&vpninfo->new_dtls_started);
  500. vpninfo->delay_tunnel_reason = "awaiting GPST ESP connection";
  501. }
  502. } else if (esp_keys && esp_v4 && new_ip_info.addr) {
  503. /* We got ESP keys, an IPv4 esp_magic address, and an IPv4 address */
  504. vpninfo->esp_magic_af = AF_INET;
  505. memcpy(vpninfo->esp_magic, &esp_magic, sizeof(esp_magic));
  506. goto setup_esp_keys;
  507. } else if (vpninfo->dtls_state != DTLS_DISABLED)
  508. vpn_progress(vpninfo, PRG_ERR,
  509. _("Did not receive ESP keys and matching gateway in GlobalProtect config; tunnel will be TLS only.\n"));
  510. #endif
  511. free(s);
  512. ret = install_vpn_opts(vpninfo, new_opts, &new_ip_info);
  513. if (ret) {
  514. err:
  515. free_optlist(new_opts);
  516. free_split_routes(&new_ip_info);
  517. }
  518. return ret;
  519. }
  520. static int gpst_get_config(struct openconnect_info *vpninfo)
  521. {
  522. char *orig_path;
  523. int result;
  524. struct oc_text_buf *request_body = buf_alloc();
  525. const char *old_addr = vpninfo->ip_info.addr;
  526. const char *old_addr6 = vpninfo->ip_info.addr6;
  527. char *xml_buf = NULL;
  528. /* submit getconfig request */
  529. buf_append(request_body, "client-type=1&protocol-version=p1&internal=no&app-version=5.1.5-8");
  530. append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
  531. append_opt(request_body, "clientos", gpst_os_name(vpninfo));
  532. append_opt(request_body, "os-version", vpninfo->platname);
  533. append_opt(request_body, "hmac-algo", "sha1,md5,sha256");
  534. append_opt(request_body, "enc-algo", "aes-128-cbc,aes-256-cbc");
  535. if (old_addr || old_addr6) {
  536. append_opt(request_body, "preferred-ip", old_addr);
  537. append_opt(request_body, "preferred-ipv6", old_addr6);
  538. filter_opts(request_body, vpninfo->cookie, "preferred-ip,preferred-ipv6", 0);
  539. } else
  540. buf_append(request_body, "&%s", vpninfo->cookie);
  541. if ((result = buf_error(request_body)))
  542. goto out;
  543. orig_path = vpninfo->urlpath;
  544. vpninfo->urlpath = strdup("ssl-vpn/getconfig.esp");
  545. result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
  546. free(vpninfo->urlpath);
  547. vpninfo->urlpath = orig_path;
  548. /* parse getconfig result */
  549. if (result >= 0)
  550. result = gpst_xml_or_error(vpninfo, xml_buf, gpst_parse_config_xml, NULL, NULL);
  551. if (result) {
  552. /* XX: if our "cookie" is bogus (doesn't include at least 'user', 'authcookie',
  553. * and 'portal' fields) the server will respond like this.
  554. */
  555. if (result == -EINVAL && xml_buf && !strcmp(xml_buf, "errors getting SSL/VPN config"))
  556. result = -EPERM;
  557. goto out;
  558. }
  559. if (!vpninfo->ip_info.mtu) {
  560. /* FIXME: GP gateway config always seems to be <mtu>0</mtu> */
  561. char *no_esp_reason = NULL;
  562. #ifdef HAVE_ESP
  563. if (vpninfo->dtls_state == DTLS_DISABLED)
  564. no_esp_reason = _("ESP disabled");
  565. else if (vpninfo->dtls_state == DTLS_NOSECRET)
  566. no_esp_reason = _("No ESP keys received");
  567. #else
  568. no_esp_reason = _("ESP support not available in this build");
  569. #endif
  570. if (!no_esp_reason)
  571. vpninfo->ip_info.mtu = calculate_mtu(
  572. vpninfo, 1,
  573. ESP_HEADER_SIZE + vpninfo->hmac_out_len + MAX_IV_SIZE, /* ESP header size */
  574. ESP_FOOTER_SIZE, /* ESP footer (contributes to payload before padding) */
  575. 16 /* blocksize for both AES-128 and AES-256 */ );
  576. else
  577. vpninfo->ip_info.mtu = calculate_mtu(vpninfo, 0, TLS_OVERHEAD, 0, 1);
  578. vpn_progress(vpninfo, PRG_ERR,
  579. _("No MTU received. Calculated %d for %s%s\n"), vpninfo->ip_info.mtu,
  580. no_esp_reason ? "SSL tunnel. " : "ESP tunnel", no_esp_reason ? : "");
  581. /* return -EINVAL; */
  582. }
  583. out:
  584. buf_free(request_body);
  585. free(xml_buf);
  586. return result;
  587. }
  588. static int gpst_connect(struct openconnect_info *vpninfo)
  589. {
  590. int ret;
  591. struct oc_text_buf *reqbuf;
  592. static const char start_tunnel[12] = "START_TUNNEL"; /* NOT zero-terminated */
  593. char buf[256];
  594. /* We do NOT actually start the HTTPS tunnel if ESP is enabled and we received
  595. * ESP keys, because the ESP keys become invalid as soon as the HTTPS tunnel
  596. * is connected! >:-(
  597. */
  598. if (vpninfo->dtls_state != DTLS_DISABLED && vpninfo->dtls_state != DTLS_NOSECRET)
  599. return 0;
  600. /* Connect to SSL VPN tunnel */
  601. vpn_progress(vpninfo, PRG_DEBUG,
  602. _("Connecting to HTTPS tunnel endpoint ...\n"));
  603. ret = openconnect_open_https(vpninfo);
  604. if (ret)
  605. return ret;
  606. reqbuf = buf_alloc();
  607. buf_append(reqbuf, "GET %s?", vpninfo->urlpath);
  608. filter_opts(reqbuf, vpninfo->cookie, "user,authcookie", 1);
  609. buf_append(reqbuf, " HTTP/1.1\r\n\r\n");
  610. if ((ret = buf_error(reqbuf)))
  611. goto out;
  612. if (vpninfo->dump_http_traffic)
  613. dump_buf(vpninfo, '>', reqbuf->data);
  614. vpninfo->ssl_write(vpninfo, reqbuf->data, reqbuf->pos);
  615. if ((ret = vpninfo->ssl_read(vpninfo, buf, 12)) < 0) {
  616. if (ret == -EINTR)
  617. goto out;
  618. vpn_progress(vpninfo, PRG_ERR,
  619. _("Error fetching GET-tunnel HTTPS response.\n"));
  620. ret = -EINVAL;
  621. goto out;
  622. }
  623. if (!strncmp(buf, start_tunnel, sizeof(start_tunnel))) {
  624. ret = 0;
  625. } else if (ret==0) {
  626. vpn_progress(vpninfo, PRG_ERR,
  627. _("Gateway disconnected immediately after GET-tunnel request.\n"));
  628. ret = -EPIPE;
  629. } else {
  630. if (ret==sizeof(start_tunnel)) {
  631. ret = vpninfo->ssl_gets(vpninfo, buf+sizeof(start_tunnel), sizeof(buf)-sizeof(start_tunnel));
  632. ret = (ret>0 ? ret : 0) + sizeof(start_tunnel);
  633. }
  634. int status = check_http_status(buf, ret);
  635. /* XX: GP servers return 502 when they don't like the cookie */
  636. if (status == 502)
  637. ret = -EPERM;
  638. else {
  639. vpn_progress(vpninfo, PRG_ERR, _("Got unexpected HTTP response: %.*s\n"),
  640. ret, buf);
  641. ret = -EINVAL;
  642. }
  643. }
  644. if (ret < 0)
  645. openconnect_close_https(vpninfo, 0);
  646. else {
  647. monitor_fd_new(vpninfo, ssl);
  648. monitor_read_fd(vpninfo, ssl);
  649. monitor_except_fd(vpninfo, ssl);
  650. vpninfo->ssl_times.last_rx = vpninfo->ssl_times.last_tx = time(NULL);
  651. /* connecting the HTTPS tunnel totally invalidates the ESP keys,
  652. hence shutdown */
  653. if (vpninfo->proto->udp_shutdown)
  654. vpninfo->proto->udp_shutdown(vpninfo);
  655. }
  656. out:
  657. buf_free(reqbuf);
  658. return ret;
  659. }
  660. static int parse_hip_report_check(struct openconnect_info *vpninfo, xmlNode *xml_node, void *cb_data)
  661. {
  662. char *s = NULL;
  663. int result = -EINVAL;
  664. if (!xml_node || !xmlnode_is_named(xml_node, "response"))
  665. goto out;
  666. for (xml_node = xml_node->children; xml_node; xml_node=xml_node->next) {
  667. if (!xmlnode_get_val(xml_node, "hip-report-needed", &s)) {
  668. if (!strcmp(s, "no"))
  669. result = 0;
  670. else if (!strcmp(s, "yes"))
  671. result = -EAGAIN;
  672. else
  673. result = -EINVAL;
  674. goto out;
  675. }
  676. }
  677. out:
  678. free(s);
  679. return result;
  680. }
  681. /* Unlike CSD, the HIP security checker runs during the connection
  682. * phase, not during the authentication phase.
  683. *
  684. * The HIP security checker will (probably) ask us to resubmit the
  685. * HIP report if either of the following changes:
  686. * - Client IP address
  687. * - Client HIP report md5sum
  688. *
  689. * I'm not sure what the md5sum is computed over in the official
  690. * client, but it doesn't really matter.
  691. *
  692. * We just need an identifier for the combination of the local host
  693. * and the VPN gateway which won't change when our IP address
  694. * or authcookie are changed.
  695. */
  696. static int build_csd_token(struct openconnect_info *vpninfo)
  697. {
  698. struct oc_text_buf *buf;
  699. unsigned char md5[16];
  700. int i;
  701. if (vpninfo->csd_token)
  702. return 0;
  703. vpninfo->csd_token = malloc(MD5_SIZE * 2 + 1);
  704. if (!vpninfo->csd_token)
  705. return -ENOMEM;
  706. /* use cookie (excluding volatile authcookie and preferred-ip/ipv6) to build md5sum */
  707. buf = buf_alloc();
  708. filter_opts(buf, vpninfo->cookie, "authcookie,preferred-ip,preferred-ipv6", 0);
  709. if (buf_error(buf))
  710. goto out;
  711. /* save as csd_token */
  712. openconnect_md5(md5, buf->data, buf->pos);
  713. for (i=0; i < MD5_SIZE; i++)
  714. sprintf(&vpninfo->csd_token[i*2], "%02x", md5[i]);
  715. out:
  716. return buf_free(buf);
  717. }
  718. /* check if HIP report is needed (to ssl-vpn/hipreportcheck.esp) or submit HIP report contents (to ssl-vpn/hipreport.esp) */
  719. static int check_or_submit_hip_report(struct openconnect_info *vpninfo, const char *report)
  720. {
  721. int result;
  722. struct oc_text_buf *request_body = buf_alloc();
  723. char *xml_buf=NULL, *orig_path;
  724. /* cookie gives us these fields: authcookie, portal, user, domain, computer, and (maybe the unnecessary) preferred-ip/ipv6 */
  725. buf_append(request_body, "client-role=global-protect-full&%s", vpninfo->cookie);
  726. if (vpninfo->ip_info.addr)
  727. append_opt(request_body, "client-ip", vpninfo->ip_info.addr);
  728. if (vpninfo->ip_info.addr6)
  729. append_opt(request_body, "client-ipv6", vpninfo->ip_info.addr6);
  730. if (report) {
  731. /* XML report contains many characters requiring URL-encoding (%xx) */
  732. buf_ensure_space(request_body, strlen(report)*3);
  733. append_opt(request_body, "report", report);
  734. } else {
  735. result = build_csd_token(vpninfo);
  736. if (result)
  737. goto out;
  738. append_opt(request_body, "md5", vpninfo->csd_token);
  739. }
  740. if ((result = buf_error(request_body)))
  741. goto out;
  742. orig_path = vpninfo->urlpath;
  743. vpninfo->urlpath = strdup(report ? "ssl-vpn/hipreport.esp" : "ssl-vpn/hipreportcheck.esp");
  744. result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
  745. free(vpninfo->urlpath);
  746. vpninfo->urlpath = orig_path;
  747. if (result >= 0)
  748. result = gpst_xml_or_error(vpninfo, xml_buf, report ? NULL : parse_hip_report_check, NULL, NULL);
  749. out:
  750. buf_free(request_body);
  751. free(xml_buf);
  752. return result;
  753. }
  754. static int run_hip_script(struct openconnect_info *vpninfo)
  755. {
  756. #if !defined(_WIN32) && !defined(__native_client__)
  757. int pipefd[2];
  758. int ret;
  759. pid_t child;
  760. #endif
  761. if (!vpninfo->csd_wrapper) {
  762. /* Only warn once */
  763. if (!vpninfo->last_trojan) {
  764. vpn_progress(vpninfo, PRG_ERR,
  765. _("WARNING: Server asked us to submit HIP report with md5sum %s.\n"
  766. " VPN connectivity may be disabled or limited without HIP report submission.\n %s\n"),
  767. vpninfo->csd_token,
  768. #if defined(_WIN32) || defined(__native_client__)
  769. _("However, running the HIP report submission script on this platform is not yet implemented.")
  770. #else
  771. _("You need to provide a --csd-wrapper argument with the HIP report submission script.")
  772. #endif
  773. );
  774. /* XXX: Many GlobalProtect VPNs work fine despite allegedly requiring HIP report submission */
  775. }
  776. return 0;
  777. }
  778. #if defined(_WIN32) || defined(__native_client__)
  779. vpn_progress(vpninfo, PRG_ERR,
  780. _("Error: Running the 'HIP Report' script on this platform is not yet implemented.\n"));
  781. return -EPERM;
  782. #else
  783. vpn_progress(vpninfo, PRG_INFO,
  784. _("Trying to run HIP Trojan script '%s'.\n"),
  785. vpninfo->csd_wrapper);
  786. #ifdef __linux__
  787. if (pipe2(pipefd, O_CLOEXEC))
  788. #endif
  789. {
  790. if (pipe(pipefd)) {
  791. vpn_progress(vpninfo, PRG_ERR, _("Failed to create pipe for HIP script\n"));
  792. return -EPERM;
  793. }
  794. set_fd_cloexec(pipefd[0]);
  795. set_fd_cloexec(pipefd[1]);
  796. }
  797. child = fork();
  798. if (child == -1) {
  799. vpn_progress(vpninfo, PRG_ERR, _("Failed to fork for HIP script\n"));
  800. return -EPERM;
  801. } else if (child > 0) {
  802. /* in parent: read report from child */
  803. struct oc_text_buf *report_buf = buf_alloc();
  804. char b[256];
  805. int i, status;
  806. close(pipefd[1]);
  807. buf_truncate(report_buf);
  808. while ((i = read(pipefd[0], b, sizeof(b))) > 0)
  809. buf_append_bytes(report_buf, b, i);
  810. waitpid(child, &status, 0);
  811. if (!WIFEXITED(status)) {
  812. vpn_progress(vpninfo, PRG_ERR,
  813. _("HIP script '%s' exited abnormally\n"),
  814. vpninfo->csd_wrapper);
  815. ret = -EINVAL;
  816. } else if (WEXITSTATUS(status) != 0) {
  817. vpn_progress(vpninfo, PRG_ERR,
  818. _("HIP script '%s' returned non-zero status: %d\n"),
  819. vpninfo->csd_wrapper, WEXITSTATUS(status));
  820. ret = -EINVAL;
  821. } else {
  822. vpn_progress(vpninfo, PRG_INFO,
  823. _("HIP script '%s' completed successfully (report is %d bytes).\n"),
  824. vpninfo->csd_wrapper, report_buf->pos);
  825. ret = check_or_submit_hip_report(vpninfo, report_buf->data);
  826. if (ret < 0)
  827. vpn_progress(vpninfo, PRG_ERR, _("HIP report submission failed.\n"));
  828. else {
  829. vpn_progress(vpninfo, PRG_INFO, _("HIP report submitted successfully.\n"));
  830. ret = 0;
  831. }
  832. }
  833. buf_free(report_buf);
  834. return ret;
  835. } else {
  836. /* in child: run HIP script */
  837. const char *hip_argv[32];
  838. int i = 0;
  839. close(pipefd[0]);
  840. /* The duplicated fd does not have O_CLOEXEC */
  841. dup2(pipefd[1], 1);
  842. if (set_csd_user(vpninfo) < 0)
  843. exit(1);
  844. hip_argv[i++] = openconnect_utf8_to_legacy(vpninfo, vpninfo->csd_wrapper);
  845. hip_argv[i++] = "--cookie";
  846. hip_argv[i++] = vpninfo->cookie;
  847. if (vpninfo->ip_info.addr) {
  848. hip_argv[i++] = "--client-ip";
  849. hip_argv[i++] = vpninfo->ip_info.addr;
  850. }
  851. if (vpninfo->ip_info.addr6) {
  852. hip_argv[i++] = "--client-ipv6";
  853. hip_argv[i++] = vpninfo->ip_info.addr6;
  854. }
  855. hip_argv[i++] = "--md5";
  856. hip_argv[i++] = vpninfo->csd_token;
  857. hip_argv[i++] = "--client-os";
  858. hip_argv[i++] = gpst_os_name(vpninfo);
  859. hip_argv[i++] = NULL;
  860. execv(hip_argv[0], (char **)hip_argv);
  861. vpn_progress(vpninfo, PRG_ERR,
  862. _("Failed to exec HIP script %s\n"), hip_argv[0]);
  863. exit(1);
  864. }
  865. #endif /* !_WIN32 && !__native_client__ */
  866. }
  867. static int check_and_maybe_submit_hip_report(struct openconnect_info *vpninfo)
  868. {
  869. int ret;
  870. ret = check_or_submit_hip_report(vpninfo, NULL);
  871. if (ret == -EAGAIN) {
  872. vpn_progress(vpninfo, PRG_DEBUG,
  873. _("Gateway says HIP report submission is needed.\n"));
  874. ret = run_hip_script(vpninfo);
  875. } else if (ret == 0)
  876. vpn_progress(vpninfo, PRG_DEBUG,
  877. _("Gateway says no HIP report submission is needed.\n"));
  878. return ret;
  879. }
  880. int gpst_setup(struct openconnect_info *vpninfo)
  881. {
  882. int ret;
  883. /* ESP keys are invalid as soon as we (re-)fetch the configuration, hence shutdown */
  884. if (vpninfo->proto->udp_shutdown)
  885. vpninfo->proto->udp_shutdown(vpninfo);
  886. /* Get configuration */
  887. ret = gpst_get_config(vpninfo);
  888. if (ret)
  889. goto out;
  890. /* Always check HIP after getting configuration */
  891. ret = check_and_maybe_submit_hip_report(vpninfo);
  892. if (ret)
  893. goto out;
  894. /* XX: last_trojan is used both as a sentinel to detect the
  895. * first time we check/submit HIP, and for the mainloop to timeout
  896. * when periodic re-checking is required.
  897. */
  898. vpninfo->last_trojan = time(NULL);
  899. /* Default HIP re-checking to 3600 seconds unless already set by
  900. * --force-trojan or portal config.
  901. */
  902. if (!vpninfo->trojan_interval)
  903. vpninfo->trojan_interval = 3600;
  904. /* Connect tunnel immediately if ESP is not going to be used */
  905. ret = gpst_connect(vpninfo);
  906. out:
  907. return ret;
  908. }
  909. int gpst_mainloop(struct openconnect_info *vpninfo, int *timeout, int readable)
  910. {
  911. int ret;
  912. int work_done = 0;
  913. uint16_t ethertype;
  914. uint32_t one, zero, magic;
  915. /* Starting the HTTPS tunnel kills ESP, so we avoid starting
  916. * it if the ESP tunnel is connected or connecting.
  917. */
  918. switch (vpninfo->dtls_state) {
  919. case DTLS_CONNECTING: /* Can never happen */
  920. case DTLS_CONNECTED:
  921. openconnect_close_https(vpninfo, 0); /* don't keep stale HTTPS socket */
  922. vpn_progress(vpninfo, PRG_INFO,
  923. _("ESP tunnel connected; exiting HTTPS mainloop.\n"));
  924. vpninfo->dtls_state = DTLS_ESTABLISHED;
  925. /* Now that we are connected, let's ensure timeout is less than
  926. * or equal to DTLS DPD/keepalive else we might over sleep, eg
  927. * if timeout is set to DTLS attempt period from ESP mainloop,
  928. * and falsely detect dead peer. */
  929. if (vpninfo->dtls_times.dpd)
  930. if (*timeout > vpninfo->dtls_times.dpd * 1000)
  931. *timeout = vpninfo->dtls_times.dpd * 1000;
  932. /* fall through */
  933. case DTLS_ESTABLISHED:
  934. /* Rekey or check-and-resubmit HIP if needed */
  935. if (keepalive_action(&vpninfo->ssl_times, timeout) == KA_REKEY)
  936. goto do_rekey;
  937. else if (trojan_check_deadline(vpninfo, timeout))
  938. goto do_recheck_hip;
  939. return 0;
  940. case DTLS_SECRET:
  941. case DTLS_SLEEPING:
  942. /* Allow 5 seconds after configuration for ESP to start */
  943. if (!ka_check_deadline(timeout, time(NULL), vpninfo->new_dtls_started + 5)) {
  944. vpninfo->delay_tunnel_reason = "awaiting GPST ESP connection";
  945. return 0;
  946. }
  947. /* ... before we switch to HTTPS instead */
  948. vpn_progress(vpninfo, PRG_ERR,
  949. _("Failed to connect ESP tunnel; using HTTPS instead.\n"));
  950. /* XX: gpst_connect does nothing if ESP is enabled and has secrets */
  951. vpninfo->dtls_state = DTLS_NOSECRET;
  952. if (gpst_connect(vpninfo)) {
  953. vpninfo->quit_reason = "GPST connect failed";
  954. return 1;
  955. }
  956. break;
  957. case DTLS_NOSECRET:
  958. /* HTTPS tunnel already started, or getconfig.esp did not provide any ESP keys */
  959. case DTLS_DISABLED:
  960. /* ESP is disabled */
  961. ;
  962. }
  963. if (vpninfo->ssl_fd == -1)
  964. goto do_reconnect;
  965. while (readable) {
  966. /* Some servers send us packets that are larger than
  967. negotiated MTU. We reserve some extra space to
  968. handle that */
  969. int receive_mtu = MAX(16384, vpninfo->ip_info.mtu);
  970. int len, payload_len;
  971. if (!vpninfo->cstp_pkt) {
  972. vpninfo->cstp_pkt = alloc_pkt(vpninfo, receive_mtu);
  973. if (!vpninfo->cstp_pkt) {
  974. vpn_progress(vpninfo, PRG_ERR, _("Allocation failed\n"));
  975. break;
  976. }
  977. }
  978. len = ssl_nonblock_read(vpninfo, 0, vpninfo->cstp_pkt->gpst.hdr, receive_mtu + 16);
  979. if (!len)
  980. break;
  981. if (len < 0) {
  982. vpn_progress(vpninfo, PRG_ERR, _("Packet receive error: %s\n"), strerror(-len));
  983. goto do_reconnect;
  984. }
  985. if (len < 16) {
  986. vpn_progress(vpninfo, PRG_ERR, _("Short packet received (%d bytes)\n"), len);
  987. vpninfo->quit_reason = "Short packet received";
  988. return 1;
  989. }
  990. /* check packet header */
  991. magic = load_be32(vpninfo->cstp_pkt->gpst.hdr);
  992. ethertype = load_be16(vpninfo->cstp_pkt->gpst.hdr + 4);
  993. payload_len = load_be16(vpninfo->cstp_pkt->gpst.hdr + 6);
  994. one = load_le32(vpninfo->cstp_pkt->gpst.hdr + 8);
  995. zero = load_le32(vpninfo->cstp_pkt->gpst.hdr + 12);
  996. if (magic != 0x1a2b3c4d)
  997. goto unknown_pkt;
  998. if (len != 16 + payload_len) {
  999. vpn_progress(vpninfo, PRG_ERR,
  1000. _("Unexpected packet length. SSL_read returned %d (includes 16 header bytes) but header payload_len is %d\n"),
  1001. len, payload_len);
  1002. dump_buf_hex(vpninfo, PRG_ERR, '<', vpninfo->cstp_pkt->gpst.hdr, 16);
  1003. continue;
  1004. }
  1005. vpninfo->ssl_times.last_rx = time(NULL);
  1006. switch (ethertype) {
  1007. case 0:
  1008. vpn_progress(vpninfo, PRG_DEBUG,
  1009. _("Got GPST DPD/keepalive response\n"));
  1010. if (one != 0 || zero != 0) {
  1011. vpn_progress(vpninfo, PRG_DEBUG,
  1012. _("Expected 0000000000000000 as last 8 bytes of DPD/keepalive packet header, but got:\n"));
  1013. dump_buf_hex(vpninfo, PRG_DEBUG, '<', vpninfo->cstp_pkt->gpst.hdr + 8, 8);
  1014. }
  1015. continue;
  1016. case 0x0800:
  1017. case 0x86DD:
  1018. vpn_progress(vpninfo, PRG_TRACE,
  1019. _("Received IPv%d data packet of %d bytes\n"),
  1020. ethertype == 0x86DD ? 6 : 4, payload_len);
  1021. if (one != 1 || zero != 0) {
  1022. vpn_progress(vpninfo, PRG_DEBUG,
  1023. _("Expected 0100000000000000 as last 8 bytes of data packet header, but got:\n"));
  1024. dump_buf_hex(vpninfo, PRG_DEBUG, '<', vpninfo->cstp_pkt->gpst.hdr + 8, 8);
  1025. }
  1026. vpninfo->cstp_pkt->len = payload_len;
  1027. queue_packet(&vpninfo->incoming_queue, vpninfo->cstp_pkt);
  1028. vpninfo->cstp_pkt = NULL;
  1029. work_done = 1;
  1030. continue;
  1031. }
  1032. unknown_pkt:
  1033. vpn_progress(vpninfo, PRG_ERR,
  1034. _("Unknown packet. Header dump follows:\n"));
  1035. dump_buf_hex(vpninfo, PRG_ERR, '<', vpninfo->cstp_pkt->gpst.hdr, 16);
  1036. vpninfo->quit_reason = "Unknown packet received";
  1037. return 1;
  1038. }
  1039. /* If SSL_write() fails we are expected to try again. With exactly
  1040. the same data, at exactly the same location. So we keep the
  1041. packet we had before.... */
  1042. if (vpninfo->current_ssl_pkt) {
  1043. handle_outgoing:
  1044. vpninfo->ssl_times.last_tx = time(NULL);
  1045. unmonitor_write_fd(vpninfo, ssl);
  1046. ret = ssl_nonblock_write(vpninfo, 0,
  1047. vpninfo->current_ssl_pkt->gpst.hdr,
  1048. vpninfo->current_ssl_pkt->len + 16);
  1049. if (ret < 0)
  1050. goto do_reconnect;
  1051. else if (!ret) {
  1052. switch (ka_stalled_action(&vpninfo->ssl_times, timeout)) {
  1053. case KA_REKEY:
  1054. goto do_rekey;
  1055. case KA_DPD_DEAD:
  1056. goto peer_dead;
  1057. case KA_NONE:
  1058. return work_done;
  1059. }
  1060. }
  1061. if (ret != vpninfo->current_ssl_pkt->len + 16) {
  1062. vpn_progress(vpninfo, PRG_ERR,
  1063. _("SSL wrote too few bytes! Asked for %d, sent %d\n"),
  1064. vpninfo->current_ssl_pkt->len + 16, ret);
  1065. vpninfo->quit_reason = "Internal error";
  1066. return 1;
  1067. }
  1068. /* Don't free the 'special' packets */
  1069. if (vpninfo->current_ssl_pkt != &dpd_pkt)
  1070. free_pkt(vpninfo, vpninfo->current_ssl_pkt);
  1071. vpninfo->current_ssl_pkt = NULL;
  1072. }
  1073. if (trojan_check_deadline(vpninfo, timeout)) {
  1074. do_recheck_hip:
  1075. vpn_progress(vpninfo, PRG_INFO, _("GlobalProtect HIP check due\n"));
  1076. /* We could just be lazy and treat this as a reconnect, but that
  1077. * would require us to repull the routing configuration and new ESP
  1078. * keys, instead of just redoing the HIP check/submission.
  1079. *
  1080. * Therefore we'll just close the HTTPS tunnel (if up),
  1081. * redo the HIP check/submission, and reconnect the HTTPS tunnel
  1082. * if needed.
  1083. */
  1084. openconnect_close_https(vpninfo, 0);
  1085. ret = check_and_maybe_submit_hip_report(vpninfo);
  1086. if (ret) {
  1087. vpn_progress(vpninfo, PRG_ERR, _("HIP check or report failed\n"));
  1088. vpninfo->quit_reason = "HIP check or report failed";
  1089. return ret;
  1090. }
  1091. /* XX: no need to do_reconnect, since ESP doesn't need reconnection */
  1092. if (gpst_connect(vpninfo))
  1093. vpninfo->quit_reason = "GPST connect failed";
  1094. return 1;
  1095. }
  1096. switch (keepalive_action(&vpninfo->ssl_times, timeout)) {
  1097. case KA_REKEY:
  1098. do_rekey:
  1099. vpn_progress(vpninfo, PRG_INFO, _("GlobalProtect rekey due\n"));
  1100. goto do_reconnect;
  1101. case KA_DPD_DEAD:
  1102. peer_dead:
  1103. vpn_progress(vpninfo, PRG_ERR,
  1104. _("GPST Dead Peer Detection detected dead peer!\n"));
  1105. do_reconnect:
  1106. ret = ssl_reconnect(vpninfo);
  1107. if (ret) {
  1108. vpn_progress(vpninfo, PRG_ERR, _("Reconnect failed\n"));
  1109. vpninfo->quit_reason = "GPST connect failed";
  1110. return ret;
  1111. }
  1112. if (vpninfo->proto->udp_setup)
  1113. vpninfo->proto->udp_setup(vpninfo);
  1114. return 1;
  1115. case KA_KEEPALIVE:
  1116. /* No need to send an explicit keepalive
  1117. if we have real data to send */
  1118. if (vpninfo->dtls_state != DTLS_ESTABLISHED &&
  1119. vpninfo->outgoing_queue.head)
  1120. break;
  1121. /* fall through */
  1122. case KA_DPD:
  1123. vpn_progress(vpninfo, PRG_DEBUG, _("Send GPST DPD/keepalive request\n"));
  1124. vpninfo->current_ssl_pkt = (struct pkt *)&dpd_pkt;
  1125. goto handle_outgoing;
  1126. }
  1127. /* Service outgoing packet queue */
  1128. while (vpninfo->dtls_state != DTLS_ESTABLISHED &&
  1129. (vpninfo->current_ssl_pkt = dequeue_packet(&vpninfo->outgoing_queue))) {
  1130. struct pkt *this = vpninfo->current_ssl_pkt;
  1131. /* IPv4 or IPv6 EtherType */
  1132. int ethertype = this->len && (this->data[0] & 0xF0) == 0x60 ? 0x86DD : 0x0800;
  1133. /* store header */
  1134. store_be32(this->gpst.hdr, 0x1a2b3c4d);
  1135. store_be16(this->gpst.hdr + 4, ethertype);
  1136. store_be16(this->gpst.hdr + 6, this->len);
  1137. store_le32(this->gpst.hdr + 8, 1);
  1138. store_le32(this->gpst.hdr + 12, 0);
  1139. vpn_progress(vpninfo, PRG_TRACE,
  1140. _("Sending IPv%d data packet of %d bytes\n"),
  1141. (ethertype == 0x86DD ? 6 : 4), this->len);
  1142. goto handle_outgoing;
  1143. }
  1144. /* Work is not done if we just got rid of packets off the queue */
  1145. return work_done;
  1146. }
  1147. int gpst_sso_detect_done(struct openconnect_info *vpninfo,
  1148. const struct oc_webview_result *result)
  1149. {
  1150. int i;
  1151. for (i=0; result->headers != NULL && result->headers[i] != NULL; i+=2) {
  1152. const char *hname = result->headers[i], *hval = result->headers[i+1];
  1153. if (!strcmp(hname, "saml-username")) {
  1154. free(vpninfo->sso_username);
  1155. vpninfo->sso_username = strdup(hval);
  1156. } else if (!strcmp(hname, "prelogin-cookie") ||
  1157. !strcmp(hname, "portal-userauthcookie")) {
  1158. free(vpninfo->sso_token_cookie);
  1159. free(vpninfo->sso_cookie_value);
  1160. vpninfo->sso_token_cookie = strdup(hname);
  1161. vpninfo->sso_cookie_value = strdup(hval);
  1162. }
  1163. }
  1164. if (vpninfo->sso_username && vpninfo->sso_token_cookie && vpninfo->sso_cookie_value) {
  1165. /* Not actually used at the moment, so don't fail if not set by the caller */
  1166. if (result->uri)
  1167. vpninfo->sso_login_final = strdup(result->uri);
  1168. return 0;
  1169. } else
  1170. return -EAGAIN;
  1171. }
  1172. #ifdef HAVE_ESP
  1173. static inline uint32_t csum_partial(uint16_t *buf, int nwords)
  1174. {
  1175. uint32_t sum = 0;
  1176. for(sum=0; nwords>0; nwords--)
  1177. sum += ntohs(*buf++);
  1178. return sum;
  1179. }
  1180. static inline uint16_t csum_finish(uint32_t sum)
  1181. {
  1182. sum = (sum >> 16) + (sum &0xffff);
  1183. sum += (sum >> 16);
  1184. return htons((uint16_t)(~sum));
  1185. }
  1186. static inline uint16_t csum(uint16_t *buf, int nwords)
  1187. {
  1188. return csum_finish(csum_partial(buf, nwords));
  1189. }
  1190. static char magic_ping_payload[16] = "monitor\x00\x00pan ha ";
  1191. int gpst_esp_send_probes(struct openconnect_info *vpninfo)
  1192. {
  1193. /* The GlobalProtect VPN initiates and maintains the ESP connection
  1194. * using specially-crafted ICMP ("ping") packets.
  1195. *
  1196. * 1) These ping packets have a special magic payload. It must
  1197. * include at least the 16 bytes below. The Windows client actually
  1198. * sends this 56-byte version, but the remaining bytes don't
  1199. * seem to matter:
  1200. *
  1201. * "monitor\x00\x00pan ha 0123456789:;<=>? !\"#$%&\'()*+,-./\x10\x11\x12\x13\x14\x15\x16\x17";
  1202. *
  1203. * 2) The ping packets are addressed to the IP supplied in the
  1204. * config XML as <gw-address>. In most cases, this is the
  1205. * same as the *external* IP address of the VPN gateway
  1206. * (vpninfo->ip_info.gateway_addr), but in some cases it is a
  1207. * separate address.
  1208. *
  1209. * Don't blame me. I didn't design this.
  1210. */
  1211. const int icmplen = ICMP_MINLEN + sizeof(magic_ping_payload);
  1212. int plen, seq;
  1213. if (vpninfo->esp_magic_af == AF_INET6)
  1214. plen = sizeof(struct ip6_hdr) + icmplen;
  1215. else
  1216. plen = sizeof(struct ip) + icmplen;
  1217. struct pkt *pkt = alloc_pkt(vpninfo, plen + vpninfo->pkt_trailer);
  1218. if (!pkt)
  1219. return -ENOMEM;
  1220. if (vpninfo->dtls_fd == -1) {
  1221. int fd = udp_connect(vpninfo);
  1222. if (fd < 0) {
  1223. free_pkt(vpninfo, pkt);
  1224. return fd;
  1225. }
  1226. /* We are not connected until we get an ESP packet back */
  1227. vpninfo->dtls_state = DTLS_SLEEPING;
  1228. vpninfo->dtls_fd = fd;
  1229. monitor_fd_new(vpninfo, dtls);
  1230. monitor_read_fd(vpninfo, dtls);
  1231. monitor_except_fd(vpninfo, dtls);
  1232. }
  1233. for (seq=1; seq <= (vpninfo->dtls_state==DTLS_ESTABLISHED ? 1 : 3); seq++) {
  1234. if (vpninfo->esp_magic_af == AF_INET6) {
  1235. memset(pkt, 0, sizeof(*pkt) + plen);
  1236. pkt->len = plen;
  1237. struct ip6_hdr *iph = (void *)pkt->data;
  1238. struct icmp6_hdr *icmph = (void *)(pkt->data + sizeof(*iph));
  1239. /* IPv6 Header */
  1240. iph->ip6_flow = htonl((6 << 28) + /* version 6 */
  1241. (0 << 20) + /* traffic class; match Windows client */
  1242. (0 << 0)); /* flow ID; match Windows client */
  1243. iph->ip6_nxt = IPPROTO_ICMPV6;
  1244. iph->ip6_plen = htons(icmplen);
  1245. iph->ip6_hlim = 128; /* what the Windows client uses */
  1246. inet_pton(AF_INET6, vpninfo->ip_info.addr6, &iph->ip6_src);
  1247. memcpy(&iph->ip6_dst, vpninfo->esp_magic, 16);
  1248. /* ICMPv6 echo request */
  1249. icmph->icmp6_type = ICMP6_ECHO_REQUEST;
  1250. icmph->icmp6_code = 0;
  1251. /* Windows client seemingly uses random IDs here but fall back to
  1252. * 0x4747 even if only to keep Coverity happy about error checking. */
  1253. if (openconnect_random(&icmph->icmp6_data16[0], 2))
  1254. icmph->icmp6_data16[0] = htons(0x4747);
  1255. icmph->icmp6_data16[1] = htons(seq); /* sequence */
  1256. /* required to get gateway to respond */
  1257. memcpy(&icmph[1], magic_ping_payload, sizeof(magic_ping_payload));
  1258. /*
  1259. * IPv6 upper-layer checksums include a pseudo-header
  1260. * for IPv6 which contains the source address, the
  1261. * destination address, the upper-layer packet length
  1262. * and next-header field. See RFC8200 §8.1. The
  1263. * checksum is as follows:
  1264. *
  1265. * checksum 32 bytes of real IPv6 header:
  1266. * src addr (16 bytes)
  1267. * dst addr (16 bytes)
  1268. * 8 bytes more:
  1269. * length of ICMPv6 in bytes (be32)
  1270. * 3 bytes of 0
  1271. * next header byte (IPPROTO_ICMPV6)
  1272. * Then the actual ICMPv6 bytes
  1273. */
  1274. uint32_t sum = csum_partial((uint16_t *)&iph->ip6_src, 8); /* 8 uint16_t */
  1275. sum += csum_partial((uint16_t *)&iph->ip6_dst, 8); /* 8 uint16_t */
  1276. /* The easiest way to checksum the following 8-byte
  1277. * part of the pseudo-header without horridly violating
  1278. * C type aliasing rules is *not* to build it in memory
  1279. * at all. We know the length fits in 16 bits so the
  1280. * partial checksum of 00 00 LL LL 00 00 00 NH ends up
  1281. * being just LLLL + NH.
  1282. */
  1283. sum += IPPROTO_ICMPV6;
  1284. sum += ICMP_MINLEN + sizeof(magic_ping_payload);
  1285. sum += csum_partial((uint16_t *)icmph, icmplen / 2);
  1286. icmph->icmp6_cksum = csum_finish(sum);
  1287. } else {
  1288. memset(pkt, 0, sizeof(*pkt) + plen);
  1289. pkt->len = plen;
  1290. struct ip *iph = (void *)pkt->data;
  1291. struct icmp *icmph = (void *)(pkt->data + sizeof(*iph));
  1292. char *pmagic = (void *)(pkt->data + sizeof(*iph) + ICMP_MINLEN);
  1293. /* IP Header */
  1294. iph->ip_hl = 5;
  1295. iph->ip_v = 4;
  1296. iph->ip_len = htons(sizeof(*iph) + icmplen);
  1297. iph->ip_id = htons(0x4747); /* what the Windows client uses */
  1298. iph->ip_off = htons(IP_DF); /* don't fragment, frag offset = 0 */
  1299. iph->ip_ttl = 64; /* hops */
  1300. iph->ip_p = IPPROTO_ICMP;
  1301. iph->ip_src.s_addr = inet_addr(vpninfo->ip_info.addr);
  1302. memcpy(&iph->ip_dst.s_addr, vpninfo->esp_magic, 4);
  1303. iph->ip_sum = csum((uint16_t *)iph, sizeof(*iph)/2);
  1304. /* ICMP echo request */
  1305. icmph->icmp_type = ICMP_ECHO;
  1306. icmph->icmp_hun.ih_idseq.icd_id = htons(0x4747);
  1307. icmph->icmp_hun.ih_idseq.icd_seq = htons(seq);
  1308. memcpy(pmagic, magic_ping_payload, sizeof(magic_ping_payload)); /* required to get gateway to respond */
  1309. icmph->icmp_cksum = csum((uint16_t *)icmph, (ICMP_MINLEN+sizeof(magic_ping_payload))/2);
  1310. }
  1311. if (vpninfo->dtls_state != DTLS_ESTABLISHED) {
  1312. vpn_progress(vpninfo, PRG_TRACE, _("ICMPv%d probe packet (seq %d) for GlobalProtect ESP:\n"),
  1313. vpninfo->esp_magic_af == AF_INET6 ? 6 : 4, seq);
  1314. dump_buf_hex(vpninfo, PRG_TRACE, '>', pkt->data, pkt->len);
  1315. }
  1316. int pktlen = construct_esp_packet(vpninfo, pkt, vpninfo->esp_magic_af == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IPIP);
  1317. if (pktlen < 0 ||
  1318. send(vpninfo->dtls_fd, (void *)&pkt->esp, pktlen, 0) < 0)
  1319. vpn_progress(vpninfo, PRG_DEBUG, _("Failed to send ESP probe\n"));
  1320. }
  1321. free_pkt(vpninfo, pkt);
  1322. vpninfo->dtls_times.last_tx = time(&vpninfo->new_dtls_started);
  1323. return 0;
  1324. }
  1325. int gpst_esp_catch_probe(struct openconnect_info *vpninfo, struct pkt *pkt)
  1326. {
  1327. if (vpninfo->esp_magic_af == AF_INET6) {
  1328. struct ip6_hdr *iph = (void *)(pkt->data);
  1329. return ( pkt->len >= 41 && (ntohl(iph->ip6_flow) >> 28)==6 /* IPv6 header */
  1330. && iph->ip6_nxt == IPPROTO_ICMPV6 /* IPv6 next header field = ICMPv6 */
  1331. && !memcmp(&iph->ip6_src, vpninfo->esp_magic, 16) /* source == magic address */
  1332. && pkt->len >= 40 + ICMP_MINLEN + sizeof(magic_ping_payload) /* No short-packet segfaults */
  1333. && pkt->data[40]==ICMP6_ECHO_REPLY /* ICMPv6 reply */
  1334. && !memcmp(&pkt->data[40 + ICMP_MINLEN], magic_ping_payload, sizeof(magic_ping_payload)) /* Same magic payload in response */
  1335. );
  1336. } else {
  1337. struct ip *iph = (void *)(pkt->data);
  1338. return ( pkt->len >= 21 && iph->ip_v==4 /* IPv4 header */
  1339. && iph->ip_p==IPPROTO_ICMP /* IPv4 protocol field == ICMP */
  1340. && !memcmp(&iph->ip_src.s_addr, vpninfo->esp_magic, 4) /* source == magic address */
  1341. && pkt->len >= (iph->ip_hl<<2) + ICMP_MINLEN + sizeof(magic_ping_payload) /* No short-packet segfaults */
  1342. && pkt->data[iph->ip_hl<<2]==ICMP_ECHOREPLY /* ICMP reply */
  1343. && !memcmp(&pkt->data[(iph->ip_hl<<2) + ICMP_MINLEN], magic_ping_payload, sizeof(magic_ping_payload)) /* Same magic payload in response */
  1344. );
  1345. }
  1346. }
  1347. #endif /* HAVE_ESP */