Use common implementation for get_cert_XYZ_fingerprint() functions
[platform/upstream/openconnect.git] / http.c
1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008 Intel Corporation.
5  * Copyright © 2008 Nick Andrew <nick@nick-andrew.net>
6  *
7  * Author: David Woodhouse <dwmw2@infradead.org>
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * version 2.1, as published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to:
20  *
21  *   Free Software Foundation, Inc.
22  *   51 Franklin Street, Fifth Floor,
23  *   Boston, MA 02110-1301 USA
24  */
25
26 #define _GNU_SOURCE
27 #include <netdb.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <time.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <sys/stat.h>
34
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include <openssl/engine.h>
38
39 #include "openconnect.h"
40
41 #define MAX_BUF_LEN 131072
42 /*
43  * We didn't really want to have to do this for ourselves -- one might have
44  * thought that it would be available in a library somewhere. But neither
45  * cURL nor Neon have reliable cross-platform ways of either using a cert
46  * from the TPM, or just reading from / writing to a transport which is
47  * provided by their caller.
48  */
49
50 static int process_http_response(struct openconnect_info *vpninfo, int *result,
51                                  int (*header_cb)(struct openconnect_info *, char *, char *),
52                                  char *body, int buf_len)
53 {
54         char buf[MAX_BUF_LEN];
55         int bodylen = 0;
56         int done = 0;
57         int http10 = 0, closeconn = 0;
58         int i;
59
60         if (openconnect_SSL_gets(vpninfo->https_ssl, buf, sizeof(buf)) < 0) {
61                 vpninfo->progress(vpninfo, PRG_ERR, "Error fetching HTTPS response\n");
62                 return -EINVAL;
63         }
64
65  cont:
66         if (!strncmp(buf, "HTTP/1.0 ", 9)) {
67                 http10 = 1;
68                 closeconn = 1;
69         }
70
71         if ((!http10 && strncmp(buf, "HTTP/1.1 ", 9)) || !(*result = atoi(buf+9))) {
72                 vpninfo->progress(vpninfo, PRG_ERR, "Failed to parse HTTP response '%s'\n", buf);
73                 return -EINVAL;
74         }
75
76         vpninfo->progress(vpninfo, PRG_TRACE, "Got HTTP response: %s\n", buf);
77
78         /* Eat headers... */
79         while ((i = openconnect_SSL_gets(vpninfo->https_ssl, buf, sizeof(buf)))) {
80                 char *colon;
81
82                 vpninfo->progress(vpninfo, PRG_TRACE, "%s\n", buf);
83
84                 if (i < 0) {
85                         vpninfo->progress(vpninfo, PRG_ERR, "Error processing HTTP response\n");
86                         return -EINVAL;
87                 }
88                 colon = strchr(buf, ':');
89                 if (!colon) {
90                         vpninfo->progress(vpninfo, PRG_ERR, "Ignoring unknown HTTP response line '%s'\n", buf);
91                         continue;
92                 }
93                 *(colon++) = 0;
94                 if (*colon == ' ')
95                         colon++;
96
97                 if (!strcmp(buf, "Connection") && !strcmp(colon, "Close"))
98                         closeconn = 1;
99
100                 if (!strcmp(buf, "Location")) {
101                         vpninfo->redirect_url = strdup(colon);
102                         if (!vpninfo->redirect_url)
103                                 return -ENOMEM;
104                 }
105                 if (!strcmp(buf, "Content-Length")) {
106                         bodylen = atoi(colon);
107                         if (bodylen < 0 || bodylen > buf_len) {
108                                 vpninfo->progress(vpninfo, PRG_ERR, "Response body too large for buffer (%d > %d)\n",
109                                         bodylen, buf_len);
110                                 return -EINVAL;
111                         }
112                 }
113                 if (!strcmp(buf, "Set-Cookie")) {
114                         struct vpn_option *new, **this;
115                         char *semicolon = strchr(colon, ';');
116                         char *equals = strchr(colon, '=');
117
118                         if (semicolon)
119                                 *semicolon = 0;
120
121                         if (!equals) {
122                                 vpninfo->progress(vpninfo, PRG_ERR, "Invalid cookie offered: %s\n", buf);
123                                 return -EINVAL;
124                         }
125                         *(equals++) = 0;
126
127                         if (*equals) {
128                                 new = malloc(sizeof(*new));
129                                 if (!new) {
130                                         vpninfo->progress(vpninfo, PRG_ERR, "No memory for allocating cookies\n");
131                                         return -ENOMEM;
132                                 }
133                                 new->next = NULL;
134                                 new->option = strdup(colon);
135                                 new->value = strdup(equals);
136                         } else {
137                                 /* Kill cookie; don't replace it */
138                                 new = NULL;
139                         }
140                         for (this = &vpninfo->cookies; *this; this = &(*this)->next) {
141                                 if (!strcmp(colon, (*this)->option)) {
142                                         /* Replace existing cookie */
143                                         if (new)
144                                                 new->next = (*this)->next;
145                                         else
146                                                 new = (*this)->next;
147
148                                         free((*this)->option);
149                                         free((*this)->value);
150                                         free(*this);
151                                         *this = new;
152                                         break;
153                                 }
154                         }
155                         if (new && !*this) {
156                                 *this = new;
157                                 new->next = NULL;
158                         }
159                 }
160                 if (!strcmp(buf, "Transfer-Encoding")) {
161                         if (!strcmp(colon, "chunked"))
162                                 bodylen = -1;
163                         else {
164                                 vpninfo->progress(vpninfo, PRG_ERR, "Unknown Transfer-Encoding: %s\n", colon);
165                                 return -EINVAL;
166                         }
167                 }
168                 if (header_cb && !strncmp(buf, "X-", 2))
169                         header_cb(vpninfo, buf, colon);
170         }
171
172         /* Handle 'HTTP/1.1 100 Continue'. Not that we should ever see it */
173         if (*result == 100)
174                 goto cont;
175
176         /* Now the body, if there is one */
177         if (!bodylen)
178                 goto fin;
179
180         if (http10) {
181                 /* HTTP 1.0 response. Just eat all we can. */
182                 while (1) {
183                         i = SSL_read(vpninfo->https_ssl, body + done, bodylen - done);
184                         if (i < 0)
185                                 goto fin;
186                         done += i;
187                 }
188         }
189         /* If we were given Content-Length, it's nice and easy... */
190         if (bodylen > 0) {
191                 while (done < bodylen) {
192                         i = SSL_read(vpninfo->https_ssl, body + done, bodylen - done);
193                         if (i < 0) {
194                                 vpninfo->progress(vpninfo, PRG_ERR, "Error reading HTTP response body\n");
195                                 return -EINVAL;
196                         }
197                         done += i;
198                 }
199                 goto fin;
200         }
201
202         /* ... else, chunked */
203         while ((i = openconnect_SSL_gets(vpninfo->https_ssl, buf, sizeof(buf)))) {
204                 int chunklen, lastchunk = 0;
205
206                 if (i < 0) {
207                         vpninfo->progress(vpninfo, PRG_ERR, "Error fetching chunk header\n");
208                         exit(1);
209                 }
210                 chunklen = strtol(buf, NULL, 16);
211                 if (!chunklen) {
212                         lastchunk = 1;
213                         goto skip;
214                 }
215                 if (chunklen + done > buf_len) {
216                         vpninfo->progress(vpninfo, PRG_ERR, "Response body too large for buffer (%d > %d)\n",
217                                 chunklen + done, buf_len);
218                         return -EINVAL;
219                 }
220                 while (chunklen) {
221                         i = SSL_read(vpninfo->https_ssl, body + done, chunklen);
222                         if (i < 0) {
223                                 vpninfo->progress(vpninfo, PRG_ERR, "Error reading HTTP response body\n");
224                                 return -EINVAL;
225                         }
226                         chunklen -= i;
227                         done += i;
228                 }
229         skip:
230                 if ((i = openconnect_SSL_gets(vpninfo->https_ssl, buf, sizeof(buf)))) {
231                         if (i < 0) {
232                                 vpninfo->progress(vpninfo, PRG_ERR, "Error fetching HTTP response body\n");
233                         } else {
234                                 vpninfo->progress(vpninfo, PRG_ERR, "Error in chunked decoding. Expected '', got: '%s'",
235                                         buf);
236                         }
237                         return -EINVAL;
238                 }
239
240                 if (lastchunk)
241                         break;
242         }
243  fin:
244         if (closeconn) {
245                 SSL_free(vpninfo->https_ssl);
246                 vpninfo->https_ssl = NULL;
247                 close(vpninfo->ssl_fd);
248                 vpninfo->ssl_fd = -1;
249         }
250         body[done] = 0;
251         return done;
252 }
253
254 static int fetch_config(struct openconnect_info *vpninfo, char *fu, char *bu,
255                         char *server_sha1)
256 {
257         struct vpn_option *opt;
258         char buf[MAX_BUF_LEN];
259         int result, buflen;
260         unsigned char local_sha1_bin[SHA_DIGEST_LENGTH];
261         char local_sha1_ascii[(SHA_DIGEST_LENGTH * 2)+1];
262         EVP_MD_CTX c;
263         int i;
264
265         sprintf(buf, "GET %s%s HTTP/1.1\r\n", fu, bu);
266         sprintf(buf + strlen(buf), "Host: %s\r\n", vpninfo->hostname);
267         sprintf(buf + strlen(buf),  "User-Agent: %s\r\n", vpninfo->useragent);
268         sprintf(buf + strlen(buf),  "Accept: */*\r\n");
269         sprintf(buf + strlen(buf),  "Accept-Encoding: identity\r\n");
270
271         if (vpninfo->cookies) {
272                 sprintf(buf + strlen(buf),  "Cookie: ");
273                 for (opt = vpninfo->cookies; opt; opt = opt->next)
274                         sprintf(buf + strlen(buf),  "%s=%s%s", opt->option,
275                                       opt->value, opt->next ? "; " : "\r\n");
276         }
277         sprintf(buf + strlen(buf),  "X-Transcend-Version: 1\r\n\r\n");
278
279         SSL_write(vpninfo->https_ssl, buf, strlen(buf));
280
281         buflen = process_http_response(vpninfo, &result, NULL, buf, MAX_BUF_LEN);
282         if (buflen < 0) {
283                 /* We'll already have complained about whatever offended us */
284                 return -EINVAL;
285         }
286
287         if (result != 200)
288                 return -EINVAL;
289
290
291         EVP_MD_CTX_init(&c);
292         EVP_Digest(buf, buflen, local_sha1_bin, NULL, EVP_sha1(), NULL);
293         EVP_MD_CTX_cleanup(&c);
294
295         for (i = 0; i < SHA_DIGEST_LENGTH; i++)
296                 sprintf(&local_sha1_ascii[i*2], "%02x", local_sha1_bin[i]);
297
298         if (strcasecmp(server_sha1, local_sha1_ascii)) {
299                 vpninfo->progress(vpninfo, PRG_ERR, "Downloaded config file did not match intended SHA1\n");
300                 return -EINVAL;
301         }
302
303         return vpninfo->write_new_config(vpninfo, buf, buflen);
304 }
305
306 static int run_csd_script(struct openconnect_info *vpninfo, char *buf, int buflen)
307 {
308         char fname[16];
309         int fd;
310
311         sprintf(fname, "/tmp/csdXXXXXX");
312         fd = mkstemp(fname);
313         if (fd < 0) {
314                 int err = -errno;
315                 vpninfo->progress(vpninfo, PRG_ERR, "Failed to open temporary CSD script file: %s\n",
316                                   strerror(errno));
317                 return err;
318         }
319         write(fd, buf, buflen);
320         fchmod(fd, 0700);
321         close(fd);
322
323         if (!fork()) {
324                 X509 *cert = SSL_get_peer_certificate(vpninfo->https_ssl);
325                 char certbuf[EVP_MAX_MD_SIZE * 2 + 1];
326                 char *csd_argv[32];
327                 int i = 0;
328
329                 csd_argv[i++] = fname;
330                 csd_argv[i++] = "-ticket";
331                 asprintf(&csd_argv[i++], "\"%s\"", vpninfo->csd_ticket);
332                 csd_argv[i++] = "-stub";
333                 csd_argv[i++] = "\"0\"";
334                 csd_argv[i++] = "-group";
335                 asprintf(&csd_argv[i++], "\"%s\"", vpninfo->authgroup?:"");
336                 get_cert_md5_fingerprint(vpninfo, cert, certbuf);
337                 csd_argv[i++] = "-certhash";
338                 asprintf(&csd_argv[i++], "\"%s:%s\"", certbuf, vpninfo->cert_md5_fingerprint ?: "");
339                 csd_argv[i++] = "-url";
340                 asprintf(&csd_argv[i++], "\"https://%s%s\"", vpninfo->hostname, vpninfo->csd_starturl);
341                 /* WTF would it want to know this for? */
342                 csd_argv[i++] = "-vpnclient";
343                 csd_argv[i++] = "\"/opt/cisco/vpn/bin/vpnui";
344                 csd_argv[i++] = "-connect";
345                 asprintf(&csd_argv[i++], "https://%s/%s", vpninfo->hostname, vpninfo->csd_preurl);
346                 csd_argv[i++] = "-connectparam";
347                 asprintf(&csd_argv[i++], "#csdtoken=%s\"", vpninfo->csd_token);
348                 csd_argv[i++] = "-langselen";
349                 csd_argv[i++] = NULL;
350
351                 execv(fname, csd_argv);
352                 vpninfo->progress(vpninfo, PRG_ERR, "Failed to exec CSD script %s\n", fname);
353                 exit(1);
354         }
355
356         free(vpninfo->csd_stuburl);
357         vpninfo->csd_stuburl = NULL;
358         vpninfo->urlpath = strdup(vpninfo->csd_waiturl +
359                                   (vpninfo->csd_waiturl[0] == '/' ? 1 : 0));
360         vpninfo->csd_waiturl = NULL;
361         vpninfo->csd_scriptname = strdup(fname);
362         return 0;
363 }
364
365 /* Return value:
366  *  < 0, on error
367  *  = 0, no cookie (user cancel)
368  *  = 1, obtained cookie
369  */
370 int openconnect_obtain_cookie(struct openconnect_info *vpninfo)
371 {
372         struct vpn_option *opt, *next;
373         char buf[MAX_BUF_LEN];
374         int result, buflen;
375         char request_body[2048];
376         char *request_body_type = NULL;
377         char *method = "GET";
378
379  retry:
380         if (!vpninfo->https_ssl && openconnect_open_https(vpninfo)) {
381                 vpninfo->progress(vpninfo, PRG_ERR, "Failed to open HTTPS connection to %s\n",
382                         vpninfo->hostname);
383                 return -EINVAL;
384         }
385
386         /*
387          * It would be nice to use cURL for this, but we really need to guarantee
388          * that we'll be using OpenSSL (for the TPM stuff), and it doesn't seem
389          * to have any way to let us provide our own socket read/write functions.
390          * We can only provide a socket _open_ function. Which would require having
391          * a socketpair() and servicing the "other" end of it.
392          *
393          * So we process the HTTP for ourselves...
394          */
395         sprintf(buf, "%s /%s HTTP/1.1\r\n", method, vpninfo->urlpath ?: "");
396         sprintf(buf + strlen(buf), "Host: %s\r\n", vpninfo->hostname);
397         sprintf(buf + strlen(buf),  "User-Agent: %s\r\n", vpninfo->useragent);
398         sprintf(buf + strlen(buf),  "Accept: */*\r\n");
399         sprintf(buf + strlen(buf),  "Accept-Encoding: identity\r\n");
400
401         if (vpninfo->cookies) {
402                 sprintf(buf + strlen(buf),  "Cookie: ");
403                 for (opt = vpninfo->cookies; opt; opt = opt->next)
404                         sprintf(buf + strlen(buf),  "%s=%s%s", opt->option,
405                                       opt->value, opt->next ? "; " : "\r\n");
406         }
407         if (request_body_type) {
408                 sprintf(buf + strlen(buf),  "Content-Type: %s\r\n",
409                               request_body_type);
410                 sprintf(buf + strlen(buf),  "Content-Length: %zd\r\n",
411                               strlen(request_body));
412         }
413         sprintf(buf + strlen(buf),  "X-Transcend-Version: 1\r\n\r\n");
414         if (request_body_type)
415                 sprintf(buf + strlen(buf), "%s", request_body);
416
417         vpninfo->progress(vpninfo, PRG_INFO, "%s %s/%s\n", method,
418                           vpninfo->hostname, vpninfo->urlpath ?: "");
419
420         SSL_write(vpninfo->https_ssl, buf, strlen(buf));
421
422         buflen = process_http_response(vpninfo, &result, NULL, buf, MAX_BUF_LEN);
423         if (buflen < 0) {
424                 /* We'll already have complained about whatever offended us */
425                 exit(1);
426         }
427
428         if (result != 200 && vpninfo->redirect_url) {
429         redirect:
430                 if (!strncmp(vpninfo->redirect_url, "https://", 8)) {
431                         /* New host. Tear down the existing connection and make a new one */
432                         char *host = vpninfo->redirect_url + 8;
433                         char *path = strchr(host, '/');
434
435                         free(vpninfo->urlpath);
436                         if (path) {
437                                 *(path++) = 0;
438                                 vpninfo->urlpath = strdup(path);
439                         } else
440                                 vpninfo->urlpath = NULL;
441
442                         if (strcmp(vpninfo->hostname, host)) {
443                                 free(vpninfo->hostname);
444                                 vpninfo->hostname = strdup(host);
445
446                                 /* Kill the existing connection, and a new one will happen */
447                                 SSL_free(vpninfo->https_ssl);
448                                 vpninfo->https_ssl = NULL;
449                                 close(vpninfo->ssl_fd);
450                                 vpninfo->ssl_fd = -1;
451
452                                 for (opt = vpninfo->cookies; opt; opt = next) {
453                                         next = opt->next;
454
455                                         free(opt->option);
456                                         free(opt->value);
457                                         free(opt);
458                                 }
459                                 vpninfo->cookies = NULL;
460                         }
461                         free(vpninfo->redirect_url);
462                         vpninfo->redirect_url = NULL;
463
464                         goto retry;
465                 } else if (vpninfo->redirect_url[0] == '/') {
466                         /* Absolute redirect within same host */
467                         free(vpninfo->urlpath);
468                         vpninfo->urlpath = strdup(vpninfo->redirect_url + 1);
469                         free(vpninfo->redirect_url);
470                         vpninfo->redirect_url = NULL;
471                         goto retry;
472                 } else {
473                         vpninfo->progress(vpninfo, PRG_ERR, "Relative redirect (to '%s') not supported\n",
474                                 vpninfo->redirect_url);
475                         return -EINVAL;
476                 }
477         }
478
479         if (vpninfo->csd_stuburl) {
480                 /* This is the CSD stub script, which we now need to run */
481                 result = run_csd_script(vpninfo, buf, buflen);
482                 if (result)
483                         return result;
484
485                 /* Now we'll be redirected to the waiturl */
486                 goto retry;
487         }
488         if (strncmp(buf, "<?xml", 5)) {
489                 /* Not XML? Perhaps it's HTML with a refresh... */
490                 if (strcasestr(buf, "http-equiv=\"refresh\"")) {
491                         vpninfo->progress(vpninfo, PRG_INFO, "Refreshing %s after 1 second...\n",
492                                           vpninfo->urlpath);
493                         sleep(1);
494                         goto retry;
495                 }
496                 vpninfo->progress(vpninfo, PRG_ERR, "Unknown response from server\n");
497                 return -EINVAL;
498         }
499         request_body[0] = 0;
500         result = parse_xml_response(vpninfo, buf, request_body, sizeof(request_body),
501                                     &method, &request_body_type);
502         if (!result)
503                 goto redirect;
504
505         if (result != 2)
506                 return result;
507         /* A return value of 2 means the XML form indicated
508            success. We _should_ have a cookie... */
509
510         for (opt = vpninfo->cookies; opt; opt = opt->next) {
511
512                 if (!strcmp(opt->option, "webvpn"))
513                         vpninfo->cookie = opt->value;
514                 else if (vpninfo->write_new_config && !strcmp(opt->option, "webvpnc")) {
515                         char *tok = opt->value;
516                         char *bu = NULL, *fu = NULL, *sha = NULL;
517
518                         do {
519                                 if (tok != opt->value)
520                                         *(tok++) = 0;
521
522                                 if (!strncmp(tok, "bu:", 3))
523                                         bu = tok + 3;
524                                 else if (!strncmp(tok, "fu:", 3))
525                                         fu = tok + 3;
526                                 else if (!strncmp(tok, "fh:", 3)) {
527                                         if (!strncasecmp(tok+3, vpninfo->xmlsha1,
528                                                          SHA_DIGEST_LENGTH * 2))
529                                                 break;
530                                         sha = tok + 3;
531                                 }
532                         } while ((tok = strchr(tok, '&')));
533
534                         if (bu && fu && sha)
535                                 fetch_config(vpninfo, bu, fu, sha);
536                 }
537         }
538         if (vpninfo->csd_scriptname) {
539                 unlink(vpninfo->csd_scriptname);
540                 free(vpninfo->csd_scriptname);
541                 vpninfo->csd_scriptname = NULL;
542         }
543         return 0;
544 }
545
546 char *openconnect_create_useragent(char *base)
547 {
548         char *uagent = malloc(strlen(base) + 1 + strlen(openconnect_version));
549         sprintf(uagent, "%s%s", base, openconnect_version);
550         return uagent;
551 }