ppp.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  1. /*
  2. * OpenConnect (SSL + DTLS) VPN client
  3. *
  4. * Copyright © 2020-2021 David Woodhouse, Daniel Lenski
  5. *
  6. * Authors: David Woodhouse <dwmw2@infradead.org>, 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. #include "ppp.h"
  20. #include <errno.h>
  21. static const uint16_t fcstab[256] = {
  22. 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
  23. 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
  24. 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
  25. 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
  26. 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
  27. 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
  28. 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
  29. 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
  30. 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
  31. 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
  32. 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
  33. 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
  34. 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
  35. 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
  36. 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
  37. 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
  38. 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
  39. 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
  40. 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
  41. 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
  42. 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
  43. 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
  44. 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
  45. 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
  46. 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
  47. 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
  48. 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
  49. 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
  50. 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
  51. 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
  52. 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
  53. 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
  54. };
  55. #define foldfcs(fcs, c) ( ( (fcs) >> 8 ) ^ fcstab[(fcs ^ (c)) & 0xff] )
  56. #define NEED_ESCAPE(c, map) ( (((c) < 0x20) && (map && (1UL << (c)))) || ((c) == 0x7d) || ((c) == 0x7e) )
  57. #define HDLC_OUT(outp, c, map) do { \
  58. if (NEED_ESCAPE((c), map)) { \
  59. *outp++ = 0x7d; \
  60. *outp++ = (c) ^ 0x20; \
  61. } else \
  62. *outp++ = (c); \
  63. } while (0)
  64. static struct pkt *hdlc_into_new_pkt(struct openconnect_info *vpninfo, struct pkt *old, int asyncmap)
  65. {
  66. int len = old->len + old->ppp.hlen;
  67. const unsigned char *inp = old->data - old->ppp.hlen, *endp = inp + len;
  68. unsigned char *outp;
  69. uint16_t fcs = PPPINITFCS16;
  70. /* Every byte in payload and 2-byte FCS potentially expands to two bytes,
  71. * plus 2 for flag (0x7e) at start and end. We know that we will output
  72. * at least 4 bytes so we can stash those in the header. */
  73. struct pkt *p = alloc_pkt(vpninfo, len*2 + 2);
  74. if (!p)
  75. return NULL;
  76. outp = p->data - 4;
  77. *outp++ = 0x7e;
  78. for (; inp < endp; inp++) {
  79. fcs = foldfcs(fcs, *inp);
  80. HDLC_OUT(outp, *inp, asyncmap);
  81. }
  82. /* Append FCS, escaped, little-endian */
  83. fcs ^= 0xffff;
  84. HDLC_OUT(outp, fcs & 0xff, asyncmap);
  85. HDLC_OUT(outp, fcs >> 8, asyncmap);
  86. *outp++ = 0x7e;
  87. p->ppp.hlen = 4;
  88. p->len = outp - p->data;
  89. return p;
  90. }
  91. static int unhdlc_in_place(struct openconnect_info *vpninfo, unsigned char *bytes, int len, unsigned char **next)
  92. {
  93. unsigned char *inp = bytes, *endp = bytes + len;
  94. unsigned char *outp = bytes;
  95. int escape = 0;
  96. uint16_t fcs = PPPINITFCS16;
  97. if (*inp == 0x7e)
  98. inp++;
  99. else
  100. vpn_progress(vpninfo, PRG_TRACE,
  101. _("HDLC initial flag sequence (0x7e) is missing\n"));
  102. while (inp < endp) {
  103. unsigned char c = *inp++;
  104. if (c == 0x7e)
  105. goto done;
  106. else if (escape) {
  107. c ^= 0x20;
  108. escape = 0;
  109. } else if (c == 0x7d) {
  110. escape = 1;
  111. continue;
  112. }
  113. fcs = foldfcs(fcs, c);
  114. *outp++ = c;
  115. }
  116. vpn_progress(vpninfo, PRG_ERR,
  117. _("HDLC buffer ended without FCS and flag sequence (0x7e)\n"));
  118. return -EINVAL;
  119. done:
  120. if (outp < bytes + 2) {
  121. vpn_progress(vpninfo, PRG_ERR,
  122. _("HDLC frame too short (%d bytes)\n"),
  123. (int)(outp - bytes));
  124. return -EINVAL;
  125. }
  126. outp -= 2; /* FCS */
  127. if (next)
  128. *next = inp; /* Pointing at the byte AFTER final 0x7e */
  129. if (fcs != PPPGOODFCS16) {
  130. vpn_progress(vpninfo, PRG_INFO,
  131. _("Bad HDLC packet FCS %04x\n"), fcs);
  132. dump_buf_hex(vpninfo, PRG_INFO, '<', bytes, len);
  133. return -EINVAL;
  134. } else {
  135. vpn_progress(vpninfo, PRG_TRACE,
  136. _("Un-HDLC'ed packet (%ld bytes -> %ld), FCS=0x%04x\n"),
  137. (long)(inp - bytes), (long)(outp - bytes), fcs);
  138. return outp - bytes;
  139. }
  140. }
  141. static const char * const ppps_names[] = {
  142. "DEAD",
  143. "ESTABLISH",
  144. "OPENED",
  145. "AUTHENTICATE",
  146. "NETWORK",
  147. "TERMINATE"
  148. };
  149. static const char * const encap_names[PPP_ENCAP_MAX+1] = {
  150. NULL,
  151. "RFC1661",
  152. "RFC1662 HDLC",
  153. "F5",
  154. "F5 HDLC",
  155. "FORTINET",
  156. };
  157. static const char * const lcp_names[] = {
  158. NULL,
  159. "Configure-Request",
  160. "Configure-Ack",
  161. "Configure-Nak",
  162. "Configure-Reject",
  163. "Terminate-Request",
  164. "Terminate-Ack",
  165. "Code-Reject",
  166. "Protocol-Reject",
  167. "Echo-Request",
  168. "Echo-Reply",
  169. "Discard-Request",
  170. };
  171. static inline const char *proto_names(uint16_t proto)
  172. {
  173. static char unknown[21];
  174. switch (proto) {
  175. case PPP_LCP: return "LCP";
  176. case PPP_IPCP: return "IPCP";
  177. case PPP_IP6CP: return "IP6CP";
  178. case PPP_CCP: return "CCP";
  179. case PPP_IP: return "IPv4";
  180. case PPP_IP6: return "IPv6";
  181. default:
  182. snprintf(unknown, 21, "unknown proto 0x%04x", proto);
  183. return unknown;
  184. }
  185. }
  186. int openconnect_ppp_new(struct openconnect_info *vpninfo,
  187. int encap, int want_ipv4, int want_ipv6)
  188. {
  189. free(vpninfo->ppp);
  190. struct oc_ppp *ppp = vpninfo->ppp = calloc(sizeof(*ppp), 1);
  191. if (!ppp)
  192. return -ENOMEM;
  193. /* Delay tunnel setup during PPP negotiation */
  194. vpninfo->delay_tunnel_reason = "PPP negotiation";
  195. /* Outgoing IPv4 address and IPv6 interface identifier bits,
  196. * if already configured via another mechanism */
  197. if (vpninfo->ip_info.addr)
  198. ppp->out_ipv4_addr.s_addr = inet_addr(vpninfo->ip_info.addr);
  199. if (vpninfo->ip_info.netmask6) {
  200. char *slash = strchr(vpninfo->ip_info.netmask6, '/');
  201. if (slash) *slash=0;
  202. inet_pton(AF_INET6, vpninfo->ip_info.netmask6, &ppp->out_ipv6_addr);
  203. if (slash) *slash='/';
  204. } else if (vpninfo->ip_info.addr6) {
  205. inet_pton(AF_INET6, vpninfo->ip_info.addr6, &ppp->out_ipv6_addr);
  206. }
  207. /* Nameservers to request from peer
  208. * (see https://tools.ietf.org/html/rfc1877#section-1) */
  209. if (!vpninfo->ip_info.dns[0] && !vpninfo->ip_info.nbns[0])
  210. ppp->solicit_peerns = IPCP_DNS0|IPCP_DNS1|IPCP_NBNS0|IPCP_NBNS1;
  211. ppp->encap = encap;
  212. ppp->want_ipv4 = want_ipv4;
  213. ppp->want_ipv6 = want_ipv6 && !vpninfo->disable_ipv6;
  214. return ppp_reset(vpninfo);
  215. }
  216. int ppp_reset(struct openconnect_info *vpninfo)
  217. {
  218. struct oc_ppp *ppp = vpninfo->ppp;
  219. if (!ppp)
  220. return -EINVAL;
  221. memset(&ppp->lcp, 0, sizeof(ppp->lcp));
  222. memset(&ppp->ipcp, 0, sizeof(ppp->ipcp));
  223. memset(&ppp->ip6cp, 0, sizeof(ppp->ip6cp));
  224. ppp->ppp_state = PPPS_DEAD;
  225. ppp->out_asyncmap = 0;
  226. ppp->out_lcp_opts = BIT_MRU | BIT_MAGIC | BIT_PFCOMP | BIT_ACCOMP | BIT_MRU_COAX;
  227. ppp->check_http_response = 0;
  228. switch (ppp->encap) {
  229. case PPP_ENCAP_F5:
  230. ppp->encap_len = 4;
  231. break;
  232. case PPP_ENCAP_FORTINET:
  233. /* XX: Fortinet server rejects asyncmap and header compression. Don't blame me. */
  234. ppp->out_lcp_opts &= ~(BIT_PFCOMP | BIT_ACCOMP);
  235. ppp->encap_len = 6;
  236. break;
  237. case PPP_ENCAP_F5_HDLC:
  238. case PPP_ENCAP_RFC1662_HDLC:
  239. ppp->encap_len = 0;
  240. ppp->hdlc = 1;
  241. break;
  242. case PPP_ENCAP_RFC1661:
  243. ppp->encap_len = 0;
  244. break;
  245. default:
  246. free(ppp);
  247. return -EINVAL;
  248. }
  249. if (ppp->hdlc) ppp->out_lcp_opts |= BIT_ASYNCMAP;
  250. ppp->exp_ppp_hdr_size = 4; /* Address(1), Control(1), Proto(2) */
  251. return 0;
  252. }
  253. static void print_ppp_state(struct openconnect_info *vpninfo, int level)
  254. {
  255. struct oc_ppp *ppp = vpninfo->ppp;
  256. char buf4[20];
  257. char buf6[40];
  258. if (ppp->want_ipv4)
  259. inet_ntop(AF_INET, &ppp->in_ipv4_addr, buf4, sizeof(buf4));
  260. else
  261. snprintf(buf4, sizeof(buf4), "none");
  262. if (ppp->want_ipv6)
  263. inet_ntop(AF_INET6, &ppp->in_ipv6_addr, buf6, sizeof(buf6));
  264. else
  265. snprintf(buf6, sizeof(buf6), "none");
  266. vpn_progress(vpninfo, level, _("Current PPP state: %s (encap %s):\n"),
  267. ppps_names[ppp->ppp_state], encap_names[ppp->encap]);
  268. vpn_progress(vpninfo, level, _(" in: asyncmap=0x%08x, lcp_opts=%d, lcp_magic=0x%08x, ipv4=%s, ipv6=%s\n"),
  269. ppp->in_asyncmap, ppp->in_lcp_opts, (unsigned)ntohl(ppp->in_lcp_magic),
  270. buf4, buf6);
  271. if (ppp->want_ipv4)
  272. inet_ntop(AF_INET, &ppp->out_ipv4_addr, buf4, sizeof(buf4));
  273. if (ppp->want_ipv6)
  274. inet_ntop(AF_INET6, &ppp->out_ipv6_addr, buf6, sizeof(buf6));
  275. vpn_progress(vpninfo, level, _(" out: asyncmap=0x%08x, lcp_opts=%d, lcp_magic=0x%08x, ipv4=%s, ipv6=%s, solicit_peerns=%d, got_peerns=%d\n"),
  276. ppp->out_asyncmap, ppp->out_lcp_opts, (unsigned)ntohl(ppp->out_lcp_magic),
  277. buf4, buf6, ppp->solicit_peerns, ppp->got_peerns);
  278. }
  279. static int buf_append_ppp_tlv(struct oc_text_buf *buf, int tag, int len, const void *data)
  280. {
  281. unsigned char b[2];
  282. b[0] = tag;
  283. b[1] = len + 2;
  284. buf_append_bytes(buf, b, 2);
  285. if (len)
  286. buf_append_bytes(buf, data, len);
  287. return b[1];
  288. }
  289. static int buf_append_ppp_tlv_be16(struct oc_text_buf *buf, int tag, uint16_t value)
  290. {
  291. uint16_t val_be;
  292. store_be16(&val_be, value);
  293. return buf_append_ppp_tlv(buf, tag, 2, &val_be);
  294. }
  295. static int buf_append_ppp_tlv_be32(struct oc_text_buf *buf, int tag, uint32_t value)
  296. {
  297. uint32_t val_be;
  298. store_be32(&val_be, value);
  299. return buf_append_ppp_tlv(buf, tag, 4, &val_be);
  300. }
  301. static int queue_config_packet(struct openconnect_info *vpninfo, uint16_t proto,
  302. int id, int code, int len, const void *payload)
  303. {
  304. struct pkt *p = alloc_pkt(vpninfo, len + 4);
  305. if (!p)
  306. return -ENOMEM;
  307. p->ppp.proto = proto;
  308. p->data[0] = code;
  309. p->data[1] = id;
  310. p->len = 4 + len; /* payload length includes code, id, own 2 bytes */
  311. store_be16(p->data + 2, p->len);
  312. if (len)
  313. memcpy(p->data + 4, payload, len);
  314. queue_packet(&vpninfo->tcp_control_queue, p);
  315. return 0;
  316. }
  317. #define PROTO_TAG_LEN(p, t, l) ((((uint32_t)(p)) << 16) | ((t) << 8) | (l))
  318. static int handle_config_request(struct openconnect_info *vpninfo,
  319. int proto, int id, unsigned char *payload, int len)
  320. {
  321. struct oc_ppp *ppp = vpninfo->ppp;
  322. struct oc_text_buf *rejbuf = NULL, *nakbuf = NULL;
  323. int ret;
  324. struct oc_ncp *ncp;
  325. unsigned char *p;
  326. char abuf[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
  327. switch (proto) {
  328. case PPP_LCP: ncp = &ppp->lcp; break;
  329. case PPP_IPCP: ncp = &ppp->ipcp; break;
  330. case PPP_IP6CP: ncp = &ppp->ip6cp; break;
  331. default: return -EINVAL;
  332. }
  333. for (p = payload ; p+1 < payload+len && p+p[1] <= payload+len; p += p[1]) {
  334. unsigned char t = p[0], l = p[1];
  335. switch (PROTO_TAG_LEN(proto, t, l-2)) {
  336. case PROTO_TAG_LEN(PPP_LCP, LCP_MRU, 2): {
  337. int mru = load_be16(p + 2);
  338. if ((ppp->out_lcp_opts & BIT_MRU_COAX) && mru < vpninfo->ip_info.mtu) {
  339. /* XX: nak-offer our (larger) MTU to the server, but only try this once */
  340. store_be16(p + 2, vpninfo->ip_info.mtu);
  341. ppp->out_lcp_opts &= ~BIT_MRU_COAX;
  342. vpn_progress(vpninfo, PRG_DEBUG,
  343. _("Received MRU %d from server. Nak-offering larger MRU of %d (our MTU)\n"),
  344. mru, vpninfo->ip_info.mtu);
  345. goto nak;
  346. } else {
  347. vpninfo->ip_info.mtu = mru;
  348. vpn_progress(vpninfo, PRG_DEBUG,
  349. _("Received MRU %d from server. Setting our MTU to match.\n"),
  350. mru);
  351. }
  352. break;
  353. }
  354. case PROTO_TAG_LEN(PPP_LCP, LCP_ASYNCMAP, 4):
  355. ppp->in_asyncmap = load_be32(p+2);
  356. vpn_progress(vpninfo, PRG_DEBUG,
  357. _("Received asyncmap of 0x%08x from server\n"),
  358. ppp->in_asyncmap);
  359. break;
  360. case PROTO_TAG_LEN(PPP_LCP, LCP_MAGIC, 4):
  361. memcpy(&ppp->in_lcp_magic, p+2, 4);
  362. vpn_progress(vpninfo, PRG_DEBUG,
  363. _("Received magic number of 0x%08x from server\n"),
  364. (unsigned)ntohl(ppp->in_lcp_magic));
  365. break;
  366. case PROTO_TAG_LEN(PPP_LCP, LCP_PFCOMP, 0):
  367. vpn_progress(vpninfo, PRG_DEBUG,
  368. _("Received protocol field compression from server\n"));
  369. ppp->in_lcp_opts |= BIT_PFCOMP;
  370. break;
  371. case PROTO_TAG_LEN(PPP_LCP, LCP_ACCOMP, 0):
  372. vpn_progress(vpninfo, PRG_DEBUG,
  373. _("Received address and control field compression from server\n"));
  374. ppp->in_lcp_opts |= BIT_ACCOMP;
  375. break;
  376. case PROTO_TAG_LEN(PPP_IPCP, IPCP_IPADDRS, 8):
  377. /* XX: Ancient and deprecated. We're supposed to ignore it if we receive it, unless
  378. * we've been Nak'ed. https://tools.ietf.org/html/rfc1332#section-3.1 */
  379. vpn_progress(vpninfo, PRG_DEBUG,
  380. _("Received deprecated IP-Addresses from server, ignoring\n"));
  381. break;
  382. case PROTO_TAG_LEN(PPP_IPCP, IPCP_IPCOMP, 4):
  383. if (load_be16(p+2) == 0x002d) {
  384. /* Van Jacobson TCP/IP compression. Includes an
  385. * additional 2 payload bytes (Max-Slot-Id, Comp-Slot-Id) */
  386. vpn_progress(vpninfo, PRG_DEBUG,
  387. _("Received Van Jacobson TCP/IP compression from server\n"));
  388. /* No. Just no. */
  389. goto reject;
  390. }
  391. goto unknown;
  392. case PROTO_TAG_LEN(PPP_IPCP, IPCP_IPADDR, 4):
  393. memcpy(&ppp->in_ipv4_addr, p+2, 4);
  394. vpn_progress(vpninfo, PRG_DEBUG,
  395. _("Received peer IPv4 address %s from server\n"),
  396. inet_ntop(AF_INET, &ppp->in_ipv4_addr, abuf, sizeof(abuf)));
  397. break;
  398. case PROTO_TAG_LEN(PPP_IP6CP, IP6CP_INT_ID, 8): {
  399. unsigned char ipv6_ll[16] = {0xfe, 0x80, 0, 0, 0, 0, 0, 0};
  400. /* XX: The server has allegedly sent us its link-local IPv6 address.
  401. * However, on the only server I have access to which supports IPv6,
  402. * this is just a random/garbage value, and `ping6 -I $TUNDEV $THIS_LL_ADDRESS`
  403. * returns an "unreachable" result from the server's actual LL address,
  404. * which is not sent over PPP configuration. This is probably just an
  405. * ignorable vestige of before the days of IPv6 address autoconfiguration.
  406. */
  407. memcpy(ipv6_ll + 8, p+2, 8);
  408. memcpy(&ppp->in_ipv6_addr, ipv6_ll, 16);
  409. vpn_progress(vpninfo, PRG_DEBUG,
  410. _("Received peer IPv6 link-local address %s from server\n"),
  411. inet_ntop(AF_INET6, &ppp->in_ipv6_addr, abuf, sizeof(abuf)));
  412. break;
  413. }
  414. default:
  415. unknown:
  416. vpn_progress(vpninfo, PRG_DEBUG,
  417. _("Received unknown %s TLV (tag %d, len %d+2) from server:\n"),
  418. proto_names(proto), t, l-2);
  419. dump_buf_hex(vpninfo, PRG_DEBUG, '<', p, (int)p[1]);
  420. reject:
  421. if (!rejbuf)
  422. rejbuf = buf_alloc();
  423. if (!rejbuf) {
  424. ret = -ENOMEM;
  425. goto out;
  426. }
  427. buf_append_bytes(rejbuf, p, l);
  428. break;
  429. nak:
  430. if (!nakbuf)
  431. nakbuf = buf_alloc();
  432. if (!nakbuf) {
  433. ret = -ENOMEM;
  434. goto out;
  435. }
  436. buf_append_bytes(nakbuf, p, l);
  437. }
  438. }
  439. ncp->state |= NCP_CONF_REQ_RECEIVED;
  440. if (p != payload+len) {
  441. vpn_progress(vpninfo, PRG_DEBUG,
  442. _("Received %ld extra bytes at end of Config-Request:\n"), (long)(payload + len - p));
  443. dump_buf_hex(vpninfo, PRG_DEBUG, '<', p, payload + len - p);
  444. }
  445. if (rejbuf) {
  446. if ((ret = buf_error(rejbuf)))
  447. goto out;
  448. vpn_progress(vpninfo, PRG_DEBUG, _("Reject %s/id %d config from server\n"), proto_names(proto), id);
  449. if ((ret = queue_config_packet(vpninfo, proto, id, CONFREJ, rejbuf->pos, rejbuf->data)) >= 0) {
  450. ret = 0;
  451. }
  452. }
  453. if (nakbuf) {
  454. if ((ret = buf_error(nakbuf)))
  455. goto out;
  456. vpn_progress(vpninfo, PRG_DEBUG, _("Nak %s/id %d config from server\n"), proto_names(proto), id);
  457. if ((ret = queue_config_packet(vpninfo, proto, id, CONFNAK, nakbuf->pos, nakbuf->data)) >= 0) {
  458. ret = 0;
  459. }
  460. }
  461. if (!rejbuf && !nakbuf) {
  462. vpn_progress(vpninfo, PRG_DEBUG, _("Ack %s/id %d config from server\n"), proto_names(proto), id);
  463. if ((ret = queue_config_packet(vpninfo, proto, id, CONFACK, len, payload)) >= 0) {
  464. ncp->state |= NCP_CONF_ACK_SENT;
  465. ret = 0;
  466. }
  467. }
  468. out:
  469. buf_free(rejbuf);
  470. buf_free(nakbuf);
  471. return ret;
  472. }
  473. static int queue_config_request(struct openconnect_info *vpninfo, int proto)
  474. {
  475. struct oc_ppp *ppp = vpninfo->ppp;
  476. const uint32_t zero = 0;
  477. int ret, id, b;
  478. struct oc_ncp *ncp;
  479. struct oc_text_buf *buf;
  480. buf = buf_alloc();
  481. ret = buf_ensure_space(buf, 64);
  482. if (ret)
  483. goto out;
  484. switch (proto) {
  485. case PPP_LCP:
  486. ncp = &ppp->lcp;
  487. if (!vpninfo->ip_info.mtu) {
  488. int overhead = TLS_OVERHEAD + ppp->encap_len /* TLS and encapsulation overhead */
  489. + (ppp->hdlc ? 4 : 0) /* HDLC framing and FCS */
  490. + (ppp->out_lcp_opts & BIT_ACCOMP ? 0 : 2) /* PPP header AC fields */
  491. + (ppp->out_lcp_opts & BIT_PFCOMP ? 1 : 2); /* PPP header protocol field */
  492. vpninfo->ip_info.mtu = calculate_mtu(vpninfo, 0 /* not UDP */, overhead, 0 /* no footer */, 1 /* no block padding */);
  493. /* XX: HDLC fudge factor (average overhead on random payload is 1/128, we'll use 4x that) */
  494. if (ppp->hdlc)
  495. vpninfo->ip_info.mtu -= vpninfo->ip_info.mtu >> 5;
  496. vpn_progress(vpninfo, PRG_INFO,
  497. _("Requesting calculated MTU of %d\n"), vpninfo->ip_info.mtu);
  498. }
  499. if (ppp->out_lcp_opts & BIT_MRU)
  500. buf_append_ppp_tlv_be16(buf, LCP_MRU, vpninfo->ip_info.mtu);
  501. if (ppp->out_lcp_opts & BIT_ASYNCMAP)
  502. buf_append_ppp_tlv_be32(buf, LCP_ASYNCMAP, ppp->out_asyncmap);
  503. if (ppp->out_lcp_opts & BIT_MAGIC) {
  504. ret = openconnect_random(&ppp->out_lcp_magic, sizeof(ppp->out_lcp_magic));
  505. if (ret)
  506. goto out;
  507. buf_append_ppp_tlv(buf, LCP_MAGIC, 4, &ppp->out_lcp_magic);
  508. }
  509. if (ppp->out_lcp_opts & BIT_PFCOMP)
  510. buf_append_ppp_tlv(buf, LCP_PFCOMP, 0, NULL);
  511. if (ppp->out_lcp_opts & BIT_ACCOMP)
  512. buf_append_ppp_tlv(buf, LCP_ACCOMP, 0, NULL);
  513. break;
  514. case PPP_IPCP:
  515. ncp = &ppp->ipcp;
  516. /* XX: send zero for IPv4/DNS/NBNS to request via NAK */
  517. buf_append_ppp_tlv(buf, IPCP_IPADDR, 4, &ppp->out_ipv4_addr.s_addr);
  518. /* XX: See ppp.h for why bitfields work here */
  519. for (b=0; b<4; b++)
  520. if (ppp->solicit_peerns & (1<<b))
  521. buf_append_ppp_tlv(buf, IPCP_xNS_BASE + b, 4, &zero);
  522. break;
  523. case PPP_IP6CP:
  524. ncp = &ppp->ip6cp;
  525. /* Send zero here if we need a link-local IPv6 address, because
  526. * we don't yet have a global IPv6 address. Otherwise, just send
  527. * the interface bits of our global IPv6 address, to avoid getting
  528. * a CONFREQ/CONFNAK/re-CONFREQ round trip */
  529. buf_append_ppp_tlv(buf, IP6CP_INT_ID, 8, ppp->out_ipv6_addr.s6_addr + 8);
  530. break;
  531. default:
  532. ret = -EINVAL;
  533. goto out;
  534. }
  535. if ((ret = buf_error(buf)) != 0)
  536. goto out;
  537. id = ++ncp->id;
  538. vpn_progress(vpninfo, PRG_DEBUG, _("Sending our %s/id %d config request to server\n"),
  539. proto_names(proto), id);
  540. if ((ret = queue_config_packet(vpninfo, proto, id, CONFREQ, buf->pos, buf->data)) >= 0) {
  541. ncp->state |= NCP_CONF_REQ_SENT;
  542. ret = 0;
  543. }
  544. out:
  545. buf_free(buf);
  546. return ret;
  547. }
  548. static int handle_config_rejnak(struct openconnect_info *vpninfo,
  549. int proto, int id, int code, unsigned char *payload, int len)
  550. {
  551. struct oc_ppp *ppp = vpninfo->ppp;
  552. struct oc_ncp *ncp;
  553. unsigned char *p;
  554. char abuf[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
  555. switch (proto) {
  556. case PPP_LCP: ncp = &ppp->lcp; break;
  557. case PPP_IPCP: ncp = &ppp->ipcp; break;
  558. case PPP_IP6CP: ncp = &ppp->ip6cp; break;
  559. default: return -EINVAL;
  560. }
  561. /* If it isn't a response to our latest ConfReq, we don't care */
  562. if (id != ncp->id)
  563. return 0;
  564. for (p = payload ; p+1 < payload+len && p+p[1] <= payload+len; p += p[1]) {
  565. unsigned char t = p[0], l = p[1];
  566. switch (PROTO_TAG_LEN(proto, t, l-2)) {
  567. case PROTO_TAG_LEN(PPP_LCP, LCP_MRU, 2):
  568. /* XX: If this happens, should we try a smaller MRU? */
  569. vpn_progress(vpninfo, PRG_DEBUG,
  570. _("Server rejected/nak'ed LCP MRU option\n"));
  571. ppp->out_lcp_opts &= ~BIT_MRU;
  572. break;
  573. case PROTO_TAG_LEN(PPP_LCP, LCP_ASYNCMAP, 4):
  574. vpn_progress(vpninfo, PRG_DEBUG,
  575. _("Server rejected/nak'ed LCP asyncmap option\n"));
  576. ppp->out_asyncmap = ASYNCMAP_LCP;
  577. ppp->out_lcp_opts &= ~BIT_ASYNCMAP;
  578. break;
  579. case PROTO_TAG_LEN(PPP_LCP, LCP_MAGIC, 4):
  580. if (code == CONFNAK) {
  581. /* XX: If this happens, we are will select a new magic number in
  582. * our next CONFREQ, in case it's 1984 and our RS-232 nullmodem is
  583. * looped back. (https://tools.ietf.org/html/rfc1661#section-6.4) */
  584. } else {
  585. vpn_progress(vpninfo, PRG_DEBUG,
  586. _("Server rejected LCP magic option\n"));
  587. ppp->out_lcp_opts &= ~BIT_MAGIC;
  588. }
  589. break;
  590. case PROTO_TAG_LEN(PPP_LCP, LCP_PFCOMP, 0):
  591. vpn_progress(vpninfo, PRG_DEBUG,
  592. _("Server rejected/nak'ed LCP PFCOMP option\n"));
  593. ppp->out_lcp_opts &= ~BIT_PFCOMP;
  594. break;
  595. case PROTO_TAG_LEN(PPP_LCP, LCP_ACCOMP, 0):
  596. vpn_progress(vpninfo, PRG_DEBUG,
  597. _("Server rejected/nak'ed LCP ACCOMP option\n"));
  598. ppp->out_lcp_opts &= ~BIT_ACCOMP;
  599. break;
  600. case PROTO_TAG_LEN(PPP_IPCP, IPCP_IPADDR, 4): {
  601. struct in_addr *a = (void *)(p + 2);
  602. inet_ntop(AF_INET, a, abuf, sizeof(abuf));
  603. if (code == CONFNAK && a->s_addr) {
  604. vpn_progress(vpninfo, PRG_DEBUG,
  605. _("Server nak-offered IPv4 address: %s\n"), abuf);
  606. ppp->out_ipv4_addr = *a;
  607. if (vpninfo->ip_info.addr) {
  608. vpn_progress(vpninfo, PRG_ERR,
  609. _("Server rejected Legacy IP address %s\n"),
  610. vpninfo->ip_info.addr);
  611. ppp->want_ipv4 = 0;
  612. }
  613. } else {
  614. vpn_progress(vpninfo, PRG_DEBUG,
  615. _("Server rejected/nak'ed our IPv4 address or request: %s\n"), abuf);
  616. return -EINVAL;
  617. }
  618. break;
  619. }
  620. case PROTO_TAG_LEN(PPP_IPCP, IPCP_xNS_BASE + 0, 4):
  621. case PROTO_TAG_LEN(PPP_IPCP, IPCP_xNS_BASE + 1, 4):
  622. case PROTO_TAG_LEN(PPP_IPCP, IPCP_xNS_BASE + 2, 4):
  623. case PROTO_TAG_LEN(PPP_IPCP, IPCP_xNS_BASE + 3, 4): {
  624. struct in_addr *a = (void *)(p + 2);
  625. /* XX: see ppp.h for why bitfields work here */
  626. int is_dns = t&1;
  627. int entry = (t&2)>>1;
  628. inet_ntop(AF_INET, a, abuf, sizeof(abuf));
  629. if (code == CONFNAK && a->s_addr) {
  630. vpn_progress(vpninfo, PRG_DEBUG,
  631. _("Server nak-offered IPCP request for %s[%d] server: %s\n"),
  632. is_dns ? "DNS" : "NBNS", entry, abuf);
  633. ppp->nameservers[t & 3] = *a;
  634. ppp->got_peerns |= (1<<(t-IPCP_xNS_BASE));
  635. } else {
  636. vpn_progress(vpninfo, PRG_DEBUG,
  637. _("Server rejected/nak'ed IPCP request for %s[%d] server\n"),
  638. is_dns ? "DNS" : "NBNS", entry);
  639. }
  640. /* Stop soliciting */
  641. ppp->solicit_peerns &= ~(1<<(t-IPCP_xNS_BASE));
  642. break;
  643. }
  644. case PROTO_TAG_LEN(PPP_IP6CP, IP6CP_INT_ID, 8): {
  645. uint64_t *val = (void *)(p + 2);
  646. if (code == CONFNAK && *val != 0) {
  647. unsigned char ipv6_ll[16] = {0xfe, 0x80, 0, 0, 0, 0, 0, 0};
  648. memcpy(ipv6_ll + 8, val, 8);
  649. inet_ntop(AF_INET6, ipv6_ll, abuf, sizeof(abuf));
  650. vpn_progress(vpninfo, PRG_DEBUG,
  651. _("Server nak-offered IPv6 link-local address %s\n"), abuf);
  652. /* If we don't already have a valid global IPv6 address, then we are
  653. * supposed to use this one to create a valid link-local IPv6
  654. * address to allow autoconfiguration (https://tools.ietf.org/html/rfc5072)
  655. */
  656. memcpy(&ppp->out_ipv6_addr, ipv6_ll, 16);
  657. } else {
  658. vpn_progress(vpninfo, PRG_INFO,
  659. _("Server rejected/nak'ed our IPv6 interface identifier\n"));
  660. ppp->want_ipv6 = 0;
  661. return 0;
  662. }
  663. break;
  664. }
  665. default:
  666. vpn_progress(vpninfo, PRG_DEBUG,
  667. _("Server rejected/nak'ed %s TLV (tag %d, len %d+2)\n"),
  668. proto_names(proto), t, l-2);
  669. dump_buf_hex(vpninfo, PRG_DEBUG, '<', p, (int)p[1]);
  670. /* XX: Should abort negotiation */
  671. return -EINVAL;
  672. }
  673. }
  674. if (p != payload+len) {
  675. vpn_progress(vpninfo, PRG_DEBUG,
  676. _("Received %ld extra bytes at end of Config-Reject:\n"), (long)(payload + len - p));
  677. dump_buf_hex(vpninfo, PRG_DEBUG, '<', p, payload + len - p);
  678. }
  679. return queue_config_request(vpninfo, proto);
  680. }
  681. static int handle_config_packet(struct openconnect_info *vpninfo,
  682. uint16_t proto, unsigned char *p, int len)
  683. {
  684. struct oc_ppp *ppp = vpninfo->ppp;
  685. int code = p[0], id = p[1];
  686. int ret = 0, add_state = 0;
  687. /* XX: The NCP header consist of 4 bytes: u8 code, u8 id, u16 length (length includes this header) */
  688. if (load_be16(p + 2) > len) {
  689. vpn_progress(vpninfo, PRG_ERR, "PPP config packet too short (header says %d bytes, received %d)\n", load_be16(p+2), len);
  690. dump_buf_hex(vpninfo, PRG_ERR, '<', p, len);
  691. return -EINVAL;
  692. } else if (load_be16(p + 2) < len) {
  693. vpn_progress(vpninfo, PRG_DEBUG, "PPP config packet has junk at end (header says %d bytes, received %d)\n", load_be16(p+2), len);
  694. len = load_be16(p + 2);
  695. }
  696. if (code > 0 && code <= 11)
  697. vpn_progress(vpninfo, PRG_TRACE, _("Received %s/id %d %s from server\n"), proto_names(proto), id, lcp_names[code]);
  698. switch (code) {
  699. case CONFREQ:
  700. ret = handle_config_request(vpninfo, proto, id, p + 4, len - 4);
  701. break;
  702. case CONFACK:
  703. /* XX: we could verify that the ack/reply bytes match the request bytes,
  704. * and the ID is the expected one, but it isn't 1992, so let's not.
  705. */
  706. add_state = NCP_CONF_ACK_RECEIVED;
  707. break;
  708. case ECHOREQ:
  709. if (ppp->ppp_state >= PPPS_OPENED)
  710. ret = queue_config_packet(vpninfo, proto, id, ECHOREP, 4, &ppp->out_lcp_magic);
  711. break;
  712. case TERMREQ:
  713. add_state = NCP_TERM_REQ_RECEIVED;
  714. ret = queue_config_packet(vpninfo, proto, id, TERMACK, 0, NULL);
  715. if (ret >= 0)
  716. add_state = NCP_TERM_ACK_SENT;
  717. goto set_quit_reason;
  718. case TERMACK:
  719. add_state = NCP_TERM_ACK_RECEIVED;
  720. set_quit_reason:
  721. if (!vpninfo->quit_reason && len > 4) {
  722. vpninfo->quit_reason = strndup((char *)(p + 4), len - 4);
  723. vpn_progress(vpninfo, PRG_ERR,
  724. _("Server terminates with reason: %s\n"),
  725. vpninfo->quit_reason);
  726. }
  727. ppp->ppp_state = PPPS_TERMINATE;
  728. vpninfo->delay_close = NO_DELAY_CLOSE;
  729. break;
  730. case ECHOREP:
  731. case DISCREQ:
  732. break;
  733. case CONFREJ:
  734. case CONFNAK:
  735. ret = handle_config_rejnak(vpninfo, proto, id, code, p + 4, len - 4);
  736. break;
  737. case PROTREJ:
  738. /* Only handle rejection of IPCP or IP6CP */
  739. if (proto != PPP_LCP || len < 6)
  740. goto unknown;
  741. proto = load_be16(p + 4);
  742. if (proto == PPP_IPCP) ppp->want_ipv4 = 0;
  743. else if (proto == PPP_IP6CP) ppp->want_ipv6 = 0;
  744. else goto unknown;
  745. vpn_progress(vpninfo, PRG_DEBUG,
  746. _("Server rejected our request to configure IPv%d\n"),
  747. proto == PPP_IP6CP ? 6 : 4);
  748. break;
  749. case CODEREJ:
  750. default:
  751. unknown:
  752. ret = -EINVAL;
  753. }
  754. switch (proto) {
  755. case PPP_LCP: ppp->lcp.state |= add_state; break;
  756. case PPP_IPCP: ppp->ipcp.state |= add_state; break;
  757. case PPP_IP6CP: ppp->ip6cp.state |= add_state; break;
  758. default: return -EINVAL;
  759. }
  760. return ret;
  761. }
  762. static int handle_state_transition(struct openconnect_info *vpninfo, int dtls,
  763. struct keepalive_info *kai, int *timeout)
  764. {
  765. struct oc_ppp *ppp = vpninfo->ppp;
  766. time_t now = time(NULL);
  767. int last_state = ppp->ppp_state, network, ret = 0;
  768. switch (ppp->ppp_state) {
  769. case PPPS_DEAD:
  770. /* Prevent race conditions after recovering dead peer connection */
  771. kai->last_rx = kai->last_tx = now;
  772. /* Drop any failed outgoing packet from previous connection;
  773. * we need to reconfigure before we can send data packets. */
  774. free_pkt(vpninfo, vpninfo->current_ssl_pkt);
  775. vpninfo->current_ssl_pkt = NULL;
  776. vpninfo->partial_rec_size = 0;
  777. ppp->ppp_state = PPPS_ESTABLISH;
  778. /* fall through */
  779. case PPPS_ESTABLISH:
  780. if ((ppp->lcp.state & NCP_CONF_ACK_RECEIVED) && (ppp->lcp.state & NCP_CONF_ACK_SENT))
  781. ppp->ppp_state = PPPS_OPENED;
  782. else {
  783. if (ka_check_deadline(timeout, now, ppp->lcp.last_req + 3)) {
  784. ppp->lcp.last_req = now;
  785. if ((ret = queue_config_request(vpninfo, PPP_LCP)) < 0)
  786. goto out;
  787. }
  788. break;
  789. }
  790. /* fall through */
  791. case PPPS_OPENED:
  792. network = 1;
  793. if (!ppp->want_ipv4 && !ppp->want_ipv6) {
  794. vpninfo->quit_reason = "No network protocols configured";
  795. return -EINVAL;
  796. }
  797. if (ppp->want_ipv4) {
  798. if (!(ppp->ipcp.state & NCP_CONF_ACK_SENT) || !(ppp->ipcp.state & NCP_CONF_ACK_RECEIVED)) {
  799. network = 0;
  800. if (ka_check_deadline(timeout, now, ppp->ipcp.last_req + 3)) {
  801. ppp->ipcp.last_req = now;
  802. if ((ret = queue_config_request(vpninfo, PPP_IPCP)) < 0)
  803. goto out;
  804. }
  805. }
  806. }
  807. if (ppp->want_ipv6) {
  808. if (!(ppp->ip6cp.state & NCP_CONF_ACK_SENT) || !(ppp->ip6cp.state & NCP_CONF_ACK_RECEIVED)) {
  809. network = 0;
  810. if (ka_check_deadline(timeout, now, ppp->ip6cp.last_req + 3)) {
  811. ppp->ip6cp.last_req = now;
  812. if ((ret = queue_config_request(vpninfo, PPP_IP6CP)) < 0)
  813. goto out;
  814. }
  815. }
  816. }
  817. if (!network)
  818. break;
  819. ppp->ppp_state = PPPS_NETWORK;
  820. /* Ensure that we use the addresses we configured on PPP */
  821. if (ppp->want_ipv4 && !vpninfo->ip_info.addr) {
  822. vpninfo->ip_info.addr = add_option_ipaddr(&vpninfo->cstp_options, "ppp_ipv4",
  823. AF_INET, &ppp->out_ipv4_addr);
  824. }
  825. /* Ensure that we use the addresses we configured on PPP */
  826. if (ppp->want_ipv6 && !vpninfo->ip_info.addr6 && !vpninfo->ip_info.netmask6) {
  827. vpninfo->ip_info.addr6 = add_option_ipaddr(&vpninfo->cstp_options, "ppp_ipv6",
  828. AF_INET6, &ppp->out_ipv6_addr);
  829. }
  830. if (ppp->got_peerns & IPCP_NBNS0)
  831. vpninfo->ip_info.nbns[0] = add_option_ipaddr(&vpninfo->cstp_options, "ppp_nbns0",
  832. AF_INET, &ppp->nameservers[0]);
  833. if (ppp->got_peerns & IPCP_DNS0)
  834. vpninfo->ip_info.dns[0] = add_option_ipaddr(&vpninfo->cstp_options, "ppp_dns0",
  835. AF_INET, &ppp->nameservers[1]);
  836. if (ppp->got_peerns & IPCP_NBNS1)
  837. vpninfo->ip_info.nbns[1] = add_option_ipaddr(&vpninfo->cstp_options, "ppp_nbns1",
  838. AF_INET, &ppp->nameservers[2]);
  839. if (ppp->got_peerns & IPCP_DNS1)
  840. vpninfo->ip_info.dns[1] = add_option_ipaddr(&vpninfo->cstp_options, "ppp_dns1",
  841. AF_INET, &ppp->nameservers[3]);
  842. /* on close, we will need to send TERMREQ, then receive TERMACK */
  843. vpninfo->delay_close = DELAY_CLOSE_IMMEDIATE_CALLBACK;
  844. break;
  845. case PPPS_NETWORK:
  846. /* XX: When we pause and reconnect, we expect the auth cookie/session (external to the
  847. * PPP layer) to remain valid, and to negotiate the same IP addresses on reconnection.
  848. *
  849. * However, most servers cancel our session or cancel our IP address allocation if we
  850. * TERMINATE at the PPP layer, so we shouldn't do it when pausing.
  851. */
  852. if (vpninfo->got_cancel_cmd ||
  853. (vpninfo->got_pause_cmd && ppp->terminate_on_pause))
  854. ppp->ppp_state = PPPS_TERMINATE;
  855. else
  856. break;
  857. /* fall through */
  858. case PPPS_TERMINATE:
  859. /* XX: If server terminated, we already ACK'ed it */
  860. if (ppp->lcp.state & NCP_TERM_REQ_RECEIVED)
  861. return -EPIPE;
  862. else if (!(ppp->lcp.state & NCP_TERM_ACK_RECEIVED)) {
  863. /* We need to send a TERMREQ and wait for a TERMACK, but not keep
  864. * retrying for ever if it fails. For TLS, which ought to be
  865. * lossless, we send TERMREQ just once, wait for a second, and
  866. * give up. For DTLS we try three times (with a second between
  867. * them and give up if none of them elicit a TERMACK. */
  868. if (!(ppp->lcp.state & NCP_TERM_REQ_SENT)) {
  869. ppp->lcp.state |= NCP_TERM_REQ_SENT;
  870. ppp->lcp.termreqs_sent = 1;
  871. ppp->lcp.last_req = now;
  872. (void) queue_config_packet(vpninfo, PPP_LCP, ++ppp->lcp.id, TERMREQ, 0, NULL);
  873. vpninfo->delay_close = DELAY_CLOSE_WAIT; /* Wait 1s for TERMACK */
  874. } else if (!ka_check_deadline(timeout, now, ppp->lcp.last_req + 1)) {
  875. vpninfo->delay_close = DELAY_CLOSE_WAIT; /* Still waiting */
  876. } else if (!dtls || ppp->lcp.termreqs_sent >= 3) {
  877. ppp->ppp_state = PPPS_TERMINATE;
  878. } else {
  879. ppp->lcp.termreqs_sent++;
  880. ppp->lcp.last_req = now;
  881. (void) queue_config_packet(vpninfo, PPP_LCP, ++ppp->lcp.id, TERMREQ, 0, NULL);
  882. vpninfo->delay_close = DELAY_CLOSE_WAIT; /* Wait 1s more */
  883. }
  884. }
  885. break;
  886. case PPPS_AUTHENTICATE: /* XX: should never */
  887. default:
  888. vpninfo->quit_reason = "Unexpected state";
  889. return -EINVAL;
  890. }
  891. /* Delay tunnel setup until after PPP negotiation */
  892. vpninfo->delay_tunnel_reason = (ppp->ppp_state < PPPS_NETWORK) ? "PPP negotiation" : NULL;
  893. if (last_state != ppp->ppp_state) {
  894. vpn_progress(vpninfo, PRG_DEBUG,
  895. _("PPP state transition from %s to %s on %s channel\n"),
  896. ppps_names[last_state], ppps_names[ppp->ppp_state],
  897. dtls ? "DTLS" : "TLS");
  898. print_ppp_state(vpninfo, PRG_TRACE);
  899. return 1;
  900. }
  901. out:
  902. return ret;
  903. }
  904. static inline void add_ppp_header(struct pkt *p, struct oc_ppp *ppp, int proto)
  905. {
  906. unsigned char *ph = p->data;
  907. /* XX: store PPP header, in reverse */
  908. *--ph = proto & 0xff;
  909. if (proto > 0xff || !(ppp->out_lcp_opts & BIT_PFCOMP))
  910. *--ph = proto >> 8;
  911. if (proto == PPP_LCP || !(ppp->out_lcp_opts & BIT_ACCOMP)) {
  912. *--ph = 0x03; /* Control */
  913. *--ph = 0xff; /* Address */
  914. }
  915. p->ppp.hlen = p->data - ph;
  916. }
  917. int check_http_status(const char *buf, int len)
  918. {
  919. if (len >= 5 && !memcmp(buf, "HTTP/", 5)) {
  920. const char *eol = memchr(buf, '\r', len) ?: memchr(buf, '\n', len);
  921. const char *sp1 = memchr(buf, ' ', len);
  922. const char *sp2 = sp1 ? memchr(sp1+1, ' ', len - (sp1-buf) + 1) : NULL;
  923. return (sp1 && sp2 && (!eol || sp2<eol)) ? atoi(sp1+1) : 500;
  924. }
  925. return -EINVAL;
  926. }
  927. static int ppp_mainloop(struct openconnect_info *vpninfo, int dtls,
  928. struct keepalive_info *kai, int *timeout, int readable)
  929. {
  930. int ret, magic, rsv_hdr_size;
  931. int work_done = 0;
  932. struct pkt *this;
  933. struct oc_ppp *ppp = vpninfo->ppp;
  934. int proto;
  935. if ((dtls ? vpninfo->dtls_fd : vpninfo->ssl_fd) == -1)
  936. goto do_reconnect;
  937. handle_state_transition(vpninfo, dtls, kai, timeout);
  938. /* FIXME: The poll() handling here is fairly simplistic. Actually,
  939. if the SSL connection stalls it could return a WANT_WRITE error
  940. on _either_ of the SSL_read() or SSL_write() calls. In that case,
  941. we should probably remove POLLIN from the events we're looking for,
  942. and add POLLOUT. As it is, though, it'll just chew CPU time in that
  943. fairly unlikely situation, until the write backlog clears. */
  944. while (readable) {
  945. /* Some servers send us packets that are larger than
  946. negotiated MTU. We reserve some extra space to
  947. handle that */
  948. unsigned char *eh, *ph, *pp, *next;
  949. int receive_mtu = MAX(16384, vpninfo->ip_info.mtu);
  950. int len, payload_len, next_len;
  951. if (!vpninfo->cstp_pkt) {
  952. vpninfo->cstp_pkt = alloc_pkt(vpninfo, receive_mtu);
  953. if (!vpninfo->cstp_pkt) {
  954. vpn_progress(vpninfo, PRG_ERR, _("Allocation failed\n"));
  955. break;
  956. }
  957. }
  958. this = vpninfo->cstp_pkt;
  959. /* XX: PPP header is of variable length. We attempt to
  960. * anticipate the actual length received, so we don't have to memmove
  961. * the payload later. */
  962. rsv_hdr_size = ppp->encap_len + ppp->exp_ppp_hdr_size;
  963. /* This should never happen here as we should complain about it
  964. * before setting ->partial_rec_size in the first place, but be
  965. * paranoid. This would mean we just read zero (or negative!) */
  966. if (vpninfo->partial_rec_size >= receive_mtu + rsv_hdr_size) {
  967. vpninfo->quit_reason = "Payload exceeds MTU";
  968. vpn_progress(vpninfo, PRG_ERR,
  969. _("PPP payload exceeds receive buffer\n"));
  970. return -EINVAL;
  971. }
  972. /* Load the encap header to end up with the payload where we expect it. Also,
  973. * if our previous (D)TLS read contained an incomplete PPP packet, we need
  974. * to append to it. */
  975. eh = this->data - rsv_hdr_size;
  976. len = ssl_nonblock_read(vpninfo, dtls, eh + vpninfo->partial_rec_size,
  977. receive_mtu + rsv_hdr_size - vpninfo->partial_rec_size);
  978. if (!len)
  979. break;
  980. if (len < 0)
  981. goto do_reconnect;
  982. len += vpninfo->partial_rec_size;
  983. vpninfo->partial_rec_size = 0;
  984. /* XX: Some protocols require us to check for an HTTP response in place
  985. * of the first packet
  986. */
  987. if (ppp->check_http_response) {
  988. int status = check_http_status((const char *)eh, len);
  989. ppp->check_http_response = 0;
  990. if (status >= 0) {
  991. vpn_progress(vpninfo, PRG_ERR,_("Got unexpected HTTP response: %.*s\n"),
  992. len, (const char *)eh);
  993. vpninfo->quit_reason = "Received HTTP response (not a PPP packet)";
  994. return (status >= 400 && status <= 499) ? -EPERM : -EINVAL;
  995. }
  996. }
  997. next_pkt:
  998. /* At this point:
  999. * eh: pointer to start of bytes-from-the-wire
  1000. * len: number of bytes-from-the-wire
  1001. */
  1002. if (len < (ppp->encap_len ? : 8)) {
  1003. short_pkt:
  1004. vpn_progress(vpninfo, PRG_DEBUG, _("Short packet received (%d bytes). Waiting for more.\n"), len);
  1005. vpninfo->partial_rec_size = len;
  1006. continue;
  1007. }
  1008. if (vpninfo->dump_http_traffic)
  1009. dump_buf_hex(vpninfo, PRG_DEBUG, '<', eh, len);
  1010. /* Deencapsulate from pre-PPP header */
  1011. switch (ppp->encap) {
  1012. case PPP_ENCAP_F5:
  1013. magic = load_be16(eh);
  1014. payload_len = load_be16(eh + 2);
  1015. next = eh + 4 + payload_len;
  1016. if (magic != 0xf500) {
  1017. bad_encap_header:
  1018. vpn_progress(vpninfo, PRG_ERR,
  1019. _("Unexpected pre-PPP packet header for encap %d.\n"),
  1020. ppp->encap);
  1021. dump_buf_hex(vpninfo, PRG_ERR, '<', eh, len);
  1022. continue;
  1023. }
  1024. if (len < 4 + payload_len) {
  1025. incomplete_pkt:
  1026. /* We've read a partial PPP packet. Save the offset for our next read. */
  1027. vpninfo->partial_rec_size = len;
  1028. if (vpninfo->partial_rec_size >= receive_mtu + rsv_hdr_size) {
  1029. vpninfo->quit_reason = "Payload exceeds MTU";
  1030. vpn_progress(vpninfo, PRG_ERR,
  1031. _("PPP payload len %d exceeds receive buffer %d\n"),
  1032. payload_len, receive_mtu + rsv_hdr_size);
  1033. dump_buf_hex(vpninfo, PRG_ERR, '<', eh, len);
  1034. return -EINVAL;
  1035. }
  1036. vpn_progress(vpninfo, PRG_DEBUG,
  1037. _("PPP packet is incomplete. Received %d bytes on wire (includes %d encap) but header payload_len is %d. Waiting for more.\n"),
  1038. len, ppp->encap_len, payload_len);
  1039. continue;
  1040. }
  1041. break;
  1042. case PPP_ENCAP_FORTINET:
  1043. payload_len = load_be16(eh + 4);
  1044. magic = load_be16(eh + 2);
  1045. next = eh + 6 + payload_len;
  1046. if (magic != 0x5050 || (load_be16(eh) != payload_len + 6))
  1047. goto bad_encap_header;
  1048. if (len < 6 + payload_len)
  1049. goto incomplete_pkt;
  1050. break;
  1051. case PPP_ENCAP_F5_HDLC:
  1052. case PPP_ENCAP_RFC1662_HDLC:
  1053. payload_len = unhdlc_in_place(vpninfo, eh + ppp->encap_len, len - ppp->encap_len, &next);
  1054. if (payload_len < 0)
  1055. continue; /* unhdlc_in_place already logged */
  1056. if (vpninfo->dump_http_traffic)
  1057. dump_buf_hex(vpninfo, PRG_TRACE, '<', eh + ppp->encap_len, payload_len);
  1058. break;
  1059. case PPP_ENCAP_RFC1661:
  1060. payload_len = len;
  1061. next = eh + payload_len;
  1062. break;
  1063. default:
  1064. vpn_progress(vpninfo, PRG_ERR, _("Invalid PPP encapsulation\n"));
  1065. vpninfo->quit_reason = "Invalid encapsulation";
  1066. return -EINVAL;
  1067. }
  1068. ph = eh + ppp->encap_len;
  1069. next_len = eh + len - next;
  1070. if (next_len)
  1071. vpn_progress(vpninfo, PRG_TRACE,
  1072. _("Packet contains %d bytes after payload. Assuming concatenated packet.\n"),
  1073. next_len);
  1074. /* At this point:
  1075. * ph: pointer to start of PPP header
  1076. * payload_len: number of bytes in PPP packet
  1077. *
  1078. * Packet has been un-HDLC'ed, if necessary, and checked for incompleteness
  1079. *
  1080. * next: pointer to next concatenated packet
  1081. * next_len: its length
  1082. */
  1083. /* check PPP header and extract protocol */
  1084. pp = ph;
  1085. if (pp[0] == 0xff && pp[1] == 0x03)
  1086. /* XX: Neither byte is a possible proto value (https://tools.ietf.org/html/rfc1661#section-2) */
  1087. pp += 2;
  1088. proto = *pp++;
  1089. if (!(proto & 1)) {
  1090. proto <<= 8;
  1091. proto += *pp++;
  1092. }
  1093. payload_len -= pp - ph;
  1094. /* At this point:
  1095. * pp: pointer to start of PPP payload
  1096. * payload_len: number of bytes in PPP *payload*
  1097. */
  1098. kai->last_rx = time(NULL);
  1099. switch (proto) {
  1100. case PPP_LCP:
  1101. case PPP_IPCP:
  1102. case PPP_IP6CP:
  1103. if ((proto == PPP_IPCP && !ppp->want_ipv4) || (proto == PPP_IP6CP && !ppp->want_ipv6))
  1104. goto reject;
  1105. if (payload_len < 4)
  1106. goto short_pkt;
  1107. if ((ret = handle_config_packet(vpninfo, proto, pp, payload_len)) < 0)
  1108. return ret;
  1109. else if ((ret = handle_state_transition(vpninfo, dtls, kai, timeout)) < 0)
  1110. return ret;
  1111. break;
  1112. case PPP_IP:
  1113. case PPP_IP6:
  1114. if (ppp->ppp_state != PPPS_NETWORK) {
  1115. vpn_progress(vpninfo, PRG_ERR,
  1116. _("Unexpected IPv%d packet in PPP state %s.\n"),
  1117. (proto == PPP_IP6 ? 6 : 4), ppps_names[ppp->ppp_state]);
  1118. dump_buf_hex(vpninfo, PRG_ERR, '<', pp, payload_len);
  1119. } else {
  1120. vpn_progress(vpninfo, PRG_TRACE,
  1121. _("Received IPv%d data packet of %d bytes over %s\n"),
  1122. proto == PPP_IP6 ? 6 : 4, payload_len,
  1123. dtls ? "DTLS" : "TLS");
  1124. if (pp != this->data) {
  1125. vpn_progress(vpninfo, PRG_TRACE,
  1126. _("Expected %d PPP header bytes but got %ld, shifting payload.\n"),
  1127. ppp->exp_ppp_hdr_size, (long)(pp - ph));
  1128. /* Save it for next time */
  1129. ppp->exp_ppp_hdr_size = pp - ph;
  1130. /* XX: If PPP header was SMALLER than expected, we could
  1131. * be moving a huge packet past the allocated buffer. */
  1132. memmove(this->data, pp, payload_len + next_len);
  1133. next -= (pp - this->data);
  1134. }
  1135. this->len = payload_len;
  1136. queue_packet(&vpninfo->incoming_queue, this);
  1137. /* XX: keep reference in this to build next packet */
  1138. if (this == vpninfo->cstp_pkt)
  1139. vpninfo->cstp_pkt = NULL;
  1140. work_done = 1;
  1141. }
  1142. break;
  1143. default:
  1144. reject:
  1145. vpn_progress(vpninfo, PRG_ERR,
  1146. _("Sending Protocol-Reject for %s. Payload:\n"),
  1147. proto_names(proto));
  1148. dump_buf_hex(vpninfo, PRG_ERR, '>', pp, payload_len);
  1149. /* The rejected protocol MUST occupy 2 bytes prior to the rejected packet contents.
  1150. * (https://tools.ietf.org/html/rfc1661#section-5.7). We can clobber these bytes
  1151. * because we are throwing out this packet anyway.
  1152. *
  1153. * The rejected packet body is fully included, unless it must be truncated to the
  1154. * peer's MRU (taking into account the preceding 4 bytes for PPP header, 4 for LCP
  1155. * config header, and 2 for rejected proto.
  1156. */
  1157. store_be16(pp - 2, proto);
  1158. if ((ret = queue_config_packet(vpninfo, PPP_LCP, ++ppp->lcp.id, PROTREJ,
  1159. MIN(payload_len + 2, (vpninfo->ip_info.mtu ?: 256) - 10),
  1160. pp - 2)) < 0)
  1161. return ret;
  1162. }
  1163. if (next_len) {
  1164. /* Need to copy to a new struct pkt, not just move pointers, because data
  1165. * packets will get stolen for incoming queue and free()'d. Allocate a
  1166. * full sized packet so it can remain in vpninfo->cstp_pkt and be reused
  1167. * for receiving the next packet, if it's something other than data and
  1168. * doesn't get queued and freed. */
  1169. this = vpninfo->cstp_pkt = alloc_pkt(vpninfo, receive_mtu);
  1170. if (!this)
  1171. return -ENOMEM;
  1172. eh = this->data - rsv_hdr_size;
  1173. memcpy(eh, next, next_len);
  1174. len = next_len;
  1175. goto next_pkt;
  1176. }
  1177. }
  1178. /* If SSL_write() fails we are expected to try again. With exactly
  1179. the same data, at exactly the same location. So we keep the
  1180. packet we had before.... */
  1181. if ((this = vpninfo->current_ssl_pkt)) {
  1182. handle_outgoing:
  1183. kai->last_tx = time(NULL);
  1184. if (dtls)
  1185. unmonitor_write_fd(vpninfo, dtls);
  1186. else
  1187. unmonitor_write_fd(vpninfo, ssl);
  1188. ret = ssl_nonblock_write(vpninfo, dtls, this->data - this->ppp.hlen, this->len + this->ppp.hlen);
  1189. if (ret < 0)
  1190. goto do_reconnect;
  1191. else if (!ret) {
  1192. /* -EAGAIN: ssl_nonblock_write() will have added the SSL
  1193. fd to ->select_wfds if appropriate, so we can just
  1194. return and wait. Unless it's been stalled for so long
  1195. that DPD kicks in and we kill the connection. */
  1196. switch (ka_stalled_action(kai, timeout)) {
  1197. case KA_DPD_DEAD:
  1198. goto peer_dead;
  1199. case KA_REKEY:
  1200. goto do_reconnect;
  1201. case KA_NONE:
  1202. return work_done;
  1203. default:
  1204. /* This can never happen because ka_stalled_action()
  1205. * always returns one of the above. */
  1206. break;
  1207. }
  1208. }
  1209. if (ret != this->len + this->ppp.hlen) {
  1210. vpn_progress(vpninfo, PRG_ERR,
  1211. _("SSL wrote too few bytes! Asked for %d, sent %d\n"),
  1212. this->len + this->ppp.hlen, ret);
  1213. vpninfo->quit_reason = "Internal error";
  1214. return 1;
  1215. }
  1216. free_pkt(vpninfo, this);
  1217. vpninfo->current_ssl_pkt = NULL;
  1218. }
  1219. switch (keepalive_action(kai, timeout)) {
  1220. case KA_DPD_DEAD:
  1221. peer_dead:
  1222. vpn_progress(vpninfo, PRG_ERR,
  1223. _("Detected dead peer!\n"));
  1224. /* fall through */
  1225. case KA_REKEY:
  1226. do_reconnect:
  1227. if (dtls) {
  1228. /* This leaves it in state DTLS_SLEEPING, and will allow
  1229. * the protocol to handle any magic required to reopen it. */
  1230. dtls_close(vpninfo);
  1231. } else {
  1232. if (ppp->ppp_state == PPPS_ESTABLISH) {
  1233. vpn_progress(vpninfo, PRG_ERR, _("Failed to establish PPP\n"));
  1234. vpninfo->quit_reason = "Failed to establish PPP";
  1235. return -EPERM;
  1236. }
  1237. ret = ssl_reconnect(vpninfo);
  1238. if (ret) {
  1239. vpn_progress(vpninfo, PRG_ERR, _("Reconnect failed\n"));
  1240. vpninfo->quit_reason = "PPP reconnect failed";
  1241. return ret;
  1242. }
  1243. }
  1244. return 1;
  1245. case KA_KEEPALIVE:
  1246. /* No need to send an explicit keepalive
  1247. if we have real data to send */
  1248. if (vpninfo->tcp_control_queue.head ||
  1249. (ppp->ppp_state == PPPS_NETWORK && vpninfo->outgoing_queue.head))
  1250. break;
  1251. vpn_progress(vpninfo, PRG_DEBUG, _("Send PPP discard request as keepalive\n"));
  1252. queue_config_packet(vpninfo, PPP_LCP, ++ppp->lcp.id, DISCREQ, 0, NULL);
  1253. break;
  1254. case KA_DPD:
  1255. vpn_progress(vpninfo, PRG_DEBUG, _("Send PPP echo request as DPD\n"));
  1256. queue_config_packet(vpninfo, PPP_LCP, ++ppp->lcp.id, ECHOREQ, 4, &ppp->out_lcp_magic);
  1257. }
  1258. /* Service control queue; also, outgoing packet queue, if no DTLS */
  1259. if ((this = vpninfo->current_ssl_pkt = dequeue_packet(&vpninfo->tcp_control_queue))) {
  1260. /* XX: We pre-stash the PPP protocol field in the header for control packets */
  1261. proto = this->ppp.proto;
  1262. handle_state_transition(vpninfo, dtls, kai, timeout);
  1263. } else if (ppp->ppp_state == PPPS_NETWORK &&
  1264. (this = vpninfo->current_ssl_pkt = dequeue_packet(&vpninfo->outgoing_queue))) {
  1265. /* XX: Set protocol for IP packets */
  1266. proto = (this->len && (this->data[0] & 0xf0) == 0x60) ? PPP_IP6 : PPP_IP;
  1267. }
  1268. /* XX: Need 'this = vpninfo->current_ssl_pkt' here, otherwise sanitizer complains about
  1269. * handle_state_transition() potentially freeing vpninfo->current_ssl_pkt.
  1270. *
  1271. * That only occurs in the PPPS_DEAD branch, which is unreachable after the first
  1272. * invocation, but how to convince it of that?
  1273. */
  1274. if ((this = vpninfo->current_ssl_pkt)) {
  1275. unsigned char *eh;
  1276. const char *lcp = NULL;
  1277. int id;
  1278. switch (proto) {
  1279. case PPP_LCP:
  1280. case PPP_IPCP:
  1281. case PPP_IP6CP:
  1282. lcp = lcp_names[this->data[0]];
  1283. id = this->data[1];
  1284. }
  1285. /* Add PPP header */
  1286. add_ppp_header(this, ppp, proto);
  1287. /* XX: Copy the whole packet into new HDLC'ed packet if needed */
  1288. if (ppp->hdlc) {
  1289. /* XX: use worst-case escaping for LCP */
  1290. this = hdlc_into_new_pkt(vpninfo, this,
  1291. proto == PPP_LCP ? ASYNCMAP_LCP : ppp->out_asyncmap);
  1292. if (!this)
  1293. return 1; /* XX */
  1294. free_pkt(vpninfo, vpninfo->current_ssl_pkt);
  1295. vpninfo->current_ssl_pkt = this;
  1296. }
  1297. /* Encapsulate into pre-PPP header */
  1298. eh = this->data - this->ppp.hlen - ppp->encap_len;
  1299. switch (ppp->encap) {
  1300. case PPP_ENCAP_F5:
  1301. store_be16(eh, 0xf500);
  1302. store_be16(eh + 2, this->len + this->ppp.hlen);
  1303. break;
  1304. case PPP_ENCAP_FORTINET:
  1305. /* XX: header contains both TOTAL bytes-on-wire, and (bytes-on-wire excluding this header) */
  1306. store_be16(eh, this->len + this->ppp.hlen + 6);
  1307. store_be16(eh + 2, 0x5050);
  1308. store_be16(eh + 4, this->len + this->ppp.hlen);
  1309. break;
  1310. }
  1311. this->ppp.hlen += ppp->encap_len;
  1312. if (lcp)
  1313. vpn_progress(vpninfo, PRG_TRACE,
  1314. _("Sending PPP %s %s packet over %s (id %d, %d bytes total)\n"),
  1315. proto_names(proto), lcp,
  1316. dtls ? "DTLS" : "TLS",
  1317. id, this->len + this->ppp.hlen);
  1318. else
  1319. vpn_progress(vpninfo, PRG_TRACE,
  1320. _("Sending PPP %s packet over %s (%d bytes total)\n"),
  1321. proto_names(proto),
  1322. dtls ? "DTLS" : "TLS",
  1323. this->len + this->ppp.hlen);
  1324. if (vpninfo->dump_http_traffic)
  1325. dump_buf_hex(vpninfo, PRG_TRACE, '>', this->data - this->ppp.hlen, this->len + this->ppp.hlen);
  1326. vpninfo->current_ssl_pkt = this;
  1327. goto handle_outgoing;
  1328. }
  1329. /* Work is not done if we just got rid of packets off the queue */
  1330. return work_done;
  1331. }
  1332. /* This function in designed to be called from a PPP protocol's
  1333. * ->tcp_connect() function, to allow it to determine whether it
  1334. * should establish the PPP connection immediately or wait for
  1335. * DTLS to have a turn. */
  1336. int ppp_tcp_should_connect(struct openconnect_info *vpninfo)
  1337. {
  1338. switch (vpninfo->dtls_state) {
  1339. case DTLS_DISABLED:
  1340. case DTLS_NOSECRET:
  1341. /* No DTLS here. Connect PPP immediately over TCP */
  1342. return 1;
  1343. case DTLS_SECRET:
  1344. /* When openconnect_make_cstp_connection() is first called,
  1345. * before openconnect_setup_dtls() is called, the state is
  1346. * DTLS_SECRET. In that case, defer the connection to allow
  1347. * DTLS to have a turn. */
  1348. return 0;
  1349. case DTLS_SLEEPING:
  1350. /* On a DTLS connection timeout, the TCP mainloop calls
  1351. * dtls_close() before calling this function to reconnect,
  1352. * so establish the PPP immediately over PPP.
  1353. *
  1354. * (After a connection pause, DTLS_SLEEPING is also seen but
  1355. * the UDP mainloop runs first and the state gets changed
  1356. * to DTLS_CONNECTING before the TCP mainloop runs, so that
  1357. * variant of DTLS_SLEEPING is never seen here.) */
  1358. return 1;
  1359. case DTLS_CONNECTING:
  1360. /* After pause/SIGUSR2, the UDP mainloop will run first and
  1361. * shifts from DTLS_SLEEPING to DTLS_CONNECTING state, before
  1362. * the TCP mainloop invokes this function. So defer the
  1363. * connection to allow DTLS to connect. */
  1364. return 0;
  1365. default:
  1366. case DTLS_CONNECTED:
  1367. case DTLS_ESTABLISHED:
  1368. /* These should never be seen. */
  1369. vpn_progress(vpninfo, PRG_ERR,
  1370. _("PPP connect called with invalid DTLS state %d\n"),
  1371. vpninfo->dtls_state);
  1372. return -EIO;
  1373. }
  1374. }
  1375. int ppp_start_tcp_mainloop(struct openconnect_info *vpninfo)
  1376. {
  1377. int timeout = 0;
  1378. return ppp_mainloop(vpninfo, 0, &vpninfo->ssl_times, &timeout, 1);
  1379. }
  1380. int ppp_tcp_mainloop(struct openconnect_info *vpninfo, int *timeout, int readable)
  1381. {
  1382. /* If we're still attempting DTLS, do nothing yet. */
  1383. switch (vpninfo->dtls_state) {
  1384. case DTLS_ESTABLISHED:
  1385. if (vpninfo->ssl_fd != -1) {
  1386. openconnect_close_https(vpninfo, 0); /* don't keep stale HTTPS socket */
  1387. vpn_progress(vpninfo, PRG_INFO,
  1388. _("DTLS tunnel connected; exiting HTTPS mainloop.\n"));
  1389. }
  1390. /* Now that we are connected, let's ensure timeout is less than
  1391. * or equal to DTLS DPD/keepalive else we might over sleep, e.g.
  1392. * if timeout is set to DTLS attempt period from DTLS mainloop,
  1393. * and falsely detect dead peer. */
  1394. if (vpninfo->dtls_times.dpd)
  1395. if (*timeout > vpninfo->dtls_times.dpd * 1000)
  1396. *timeout = vpninfo->dtls_times.dpd * 1000;
  1397. return 0;
  1398. case DTLS_CONNECTED:
  1399. case DTLS_CONNECTING:
  1400. case DTLS_SECRET:
  1401. if (vpninfo->ppp->ppp_state == PPPS_DEAD) {
  1402. /* Allow 5 seconds after configuration for DTLS to start */
  1403. if (!ka_check_deadline(timeout, time(NULL), vpninfo->new_dtls_started + 5)) {
  1404. vpninfo->delay_tunnel_reason = "awaiting PPP DTLS connection";
  1405. return 0;
  1406. }
  1407. /* It'll try again in a while, but we want it to be in DTLS_SLEEPING
  1408. * so that the tcp_connect() function actually establishes the PPP
  1409. * over TCP. */
  1410. dtls_close(vpninfo);
  1411. }
  1412. /* Fall through */
  1413. case DTLS_SLEEPING:
  1414. /* Should only be seen by the mainloop if DTLS actually *failed*
  1415. * (which includes timing out). */
  1416. if (vpninfo->ppp->ppp_state == PPPS_DEAD) {
  1417. vpn_progress(vpninfo, PRG_ERR,
  1418. _("Failed to connect DTLS tunnel; using HTTPS instead (state %d).\n"),
  1419. vpninfo->dtls_state);
  1420. }
  1421. /* Fall through */
  1422. case DTLS_NOSECRET:
  1423. case DTLS_DISABLED:
  1424. /* The state is PPPS_DEAD until the first time ppp_tcp_mainloop()
  1425. * gets invoked. When f5_connect() actually establishes the tunnel,
  1426. * it does so to start the PPP state machine for the TCP connection.
  1427. */
  1428. if (vpninfo->ssl_fd != -1 && vpninfo->ppp->ppp_state != PPPS_DEAD)
  1429. return ppp_mainloop(vpninfo, 0, &vpninfo->ssl_times, timeout, readable);
  1430. /* This will call *back* into the protocol's ->tcp_connect()
  1431. * but this time DTLS is disabled so it'll actually establish
  1432. * the connection there. We want to make use of the retry
  1433. * handling logic in ssl_reconnect() in the cases where it
  1434. * doesn't succeed immediately.
  1435. *
  1436. * If the connection is already open, try using it directly
  1437. * first, before falling back to a full ssl_reconnect().
  1438. */
  1439. if (vpninfo->ssl_fd == -1 || vpninfo->proto->tcp_connect(vpninfo)) {
  1440. int ret = ssl_reconnect(vpninfo);
  1441. if (ret) {
  1442. vpn_progress(vpninfo, PRG_ERR, _("Establishing PPP tunnel over TLS failed\n"));
  1443. vpninfo->quit_reason = "PPP TLS connect failed";
  1444. return ret;
  1445. }
  1446. vpninfo->delay_tunnel_reason = "DTLS connection pending";
  1447. return 1;
  1448. }
  1449. vpninfo->delay_tunnel_reason = "DTLS connection pending";
  1450. return 1;
  1451. }
  1452. vpn_progress(vpninfo, PRG_ERR, _("Invalid DTLS state %d\n"), vpninfo->dtls_state);
  1453. vpninfo->quit_reason = "Invalid DTLS state";
  1454. return 1;
  1455. }
  1456. int ppp_udp_mainloop(struct openconnect_info *vpninfo, int *timeout, int readable)
  1457. {
  1458. int work_done = 0;
  1459. time_t now = time(NULL);
  1460. switch(vpninfo->dtls_state) {
  1461. case DTLS_CONNECTING:
  1462. if (vpninfo->ppp->ppp_state == PPPS_DEAD)
  1463. vpninfo->delay_tunnel_reason = "DTLS connecting";
  1464. dtls_try_handshake(vpninfo, timeout);
  1465. if (vpninfo->dtls_state == DTLS_CONNECTED)
  1466. goto newly_connected;
  1467. return 0;
  1468. case DTLS_CONNECTED:
  1469. /* First, see if there's a response for us. */
  1470. while(readable) {
  1471. int receive_mtu = MAX(16384, vpninfo->ip_info.mtu);
  1472. int len;
  1473. /* cstp_pkt is used by PPP over either transport, and TCP
  1474. * may be in active use while we attempt to connect DTLS.
  1475. * So use vpninfo->dtls_pkt for this. */
  1476. if (!vpninfo->dtls_pkt)
  1477. vpninfo->dtls_pkt = alloc_pkt(vpninfo, receive_mtu);
  1478. if (!vpninfo->dtls_pkt) {
  1479. vpn_progress(vpninfo, PRG_ERR, _("Allocation failed\n"));
  1480. dtls_close(vpninfo);
  1481. vpninfo->dtls_state = DTLS_DISABLED;
  1482. return 1;
  1483. }
  1484. struct pkt *this = vpninfo->dtls_pkt;
  1485. len = ssl_nonblock_read(vpninfo, 1, this->data, receive_mtu);
  1486. if (!len)
  1487. break;
  1488. if (len < 0) {
  1489. vpn_progress(vpninfo, PRG_ERR,
  1490. _("Failed to receive authentication response from DTLS\n"));
  1491. dtls_close(vpninfo);
  1492. return 1;
  1493. }
  1494. this->len = len;
  1495. if (vpninfo->dump_http_traffic)
  1496. dump_buf_hex(vpninfo, PRG_DEBUG, '<', this->data, len);
  1497. int ret = vpninfo->proto->udp_catch_probe(vpninfo, this);
  1498. if (ret < 0) {
  1499. dtls_close(vpninfo);
  1500. return 1;
  1501. } else if (ret > 0) {
  1502. vpninfo->dtls_state = DTLS_ESTABLISHED;
  1503. vpninfo->dtls_pkt = NULL;
  1504. free_pkt(vpninfo, this);
  1505. /* We are going to take over the PPP now; reset the TCP one */
  1506. ret = ppp_reset(vpninfo);
  1507. if (ret) {
  1508. /* This should never happen */
  1509. vpn_progress(vpninfo, PRG_ERR, _("Reset PPP failed\n"));
  1510. vpninfo->quit_reason = "PPP DTLS connect failed";
  1511. return ret;
  1512. }
  1513. goto established;
  1514. }
  1515. /* This is the ret==0 case, where the packet was recognised
  1516. * neither as a success nor failure. In that case it could
  1517. * be a PPP frame which has been received out of order and
  1518. * made it to us before the OK response. Drop it and keep
  1519. * waiting. */
  1520. }
  1521. /* On first connection, the TCP mainloop will give us five seconds
  1522. * to do the whole exchange and reach DTLS_ESTABLISHED before it
  1523. * gives up and connects over TCP instead. But for opportunistic
  1524. * attempts to "upgrade" to DTLS later, it won't get involved.
  1525. * We still want to time out and give up on this DTLS connection
  1526. * if we failed to authenticate though. So do it here too. */
  1527. if (ka_check_deadline(timeout, now, vpninfo->dtls_times.last_rekey + 5)) {
  1528. vpn_progress(vpninfo, PRG_ERR,
  1529. _("Failed to authenticate DTLS session\n"));
  1530. dtls_close(vpninfo);
  1531. return 1;
  1532. }
  1533. /* Resend the connect request every second */
  1534. if (ka_check_deadline(timeout, now, vpninfo->dtls_times.last_tx + 1)) {
  1535. newly_connected:
  1536. if (buf_error(vpninfo->ppp_dtls_connect_req)) {
  1537. vpn_progress(vpninfo, PRG_ERR,
  1538. _("Error creating connect request for DTLS session\n"));
  1539. dtls_close(vpninfo);
  1540. vpninfo->dtls_state = DTLS_DISABLED;
  1541. return 1;
  1542. }
  1543. if (vpninfo->dump_http_traffic)
  1544. dump_buf_hex(vpninfo, PRG_DEBUG, '>',
  1545. (void *)vpninfo->ppp_dtls_connect_req->data,
  1546. vpninfo->ppp_dtls_connect_req->pos);
  1547. int ret = ssl_nonblock_write(vpninfo, 1,
  1548. vpninfo->ppp_dtls_connect_req->data,
  1549. vpninfo->ppp_dtls_connect_req->pos);
  1550. if (ret < 0) {
  1551. vpn_progress(vpninfo, PRG_ERR,
  1552. _("Failed to write connect request to DTLS session\n"));
  1553. dtls_close(vpninfo);
  1554. vpninfo->dtls_state = DTLS_DISABLED;
  1555. return 1;
  1556. }
  1557. vpninfo->dtls_times.last_tx = now;
  1558. }
  1559. if (vpninfo->ppp->ppp_state == PPPS_DEAD)
  1560. vpninfo->delay_tunnel_reason = "DTLS establishing";
  1561. return 0;
  1562. case DTLS_ESTABLISHED:
  1563. established:
  1564. work_done = ppp_mainloop(vpninfo, 1, &vpninfo->dtls_times, timeout, readable);
  1565. if (vpninfo->dtls_state != DTLS_SLEEPING)
  1566. break;
  1567. /* Fall through */
  1568. case DTLS_SLEEPING:
  1569. /* If the SSL connection isn't open, that must mean we've been paused
  1570. * and resumed. So reconnect immediately regardless of whether we'd
  1571. * just done so, *and* reset the PPP state so that the TCP mainloop
  1572. * doesn't get confused. */
  1573. if (vpninfo->ssl_fd == -1) {
  1574. ppp_reset(vpninfo);
  1575. if (now < vpninfo->new_dtls_started + vpninfo->dtls_attempt_period)
  1576. now = vpninfo->new_dtls_started + vpninfo->dtls_attempt_period;
  1577. }
  1578. if (ka_check_deadline(timeout, now, vpninfo->new_dtls_started + vpninfo->dtls_attempt_period)) {
  1579. vpn_progress(vpninfo, PRG_DEBUG, _("Attempt new DTLS connection\n"));
  1580. dtls_reconnect(vpninfo, timeout);
  1581. work_done = 1;
  1582. }
  1583. }
  1584. return work_done;
  1585. }