/[winpt]/trunk/Src/wptKeyserver.cpp
ViewVC logotype

Contents of /trunk/Src/wptKeyserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 175 - (show annotations)
Tue Feb 7 08:58:04 2006 UTC (19 years ago) by twoaday
File size: 33712 byte(s)
2006-02-04  Timo Schulz  <ts@g10code.de>
                                                                                                                            
        * wptKeyManagerDlg.cpp (keymanager_dlg_proc): Check for
        at least one ultimately trusted key.
        * wptKeyManager.cpp (km_refresh_key_from_keyserver):
        Only check inet connection if we refresh all keys.
        * wptGPGUtil.cpp (gpg_extract_keys): New.
        * wptClipEncryptDlg.cpp (clip_encrypt_dlg_proc): Use textmode.
        * wptClipSignEncDlg.cpp (clip_signenc_dlg_proc): Likewise.
        * wptClipSignDlg.cpp (get_selected_key): New.
        (one_key_proc): Use it here.
        (count_useable_seckeys): New.
        * wptSigTreeDlg.cpp (sigtree_dlg_proc): New.
        * wptKeyEditDlgs.cpp (diff_time): Removed.
        (w32_mktime): New.
        (keyedit_addsubkey_dlg_proc): Use it here.
                                                                                                                            
2006-02-02  Timo Schulz  <ts@g10code.de>
                                                                                                                            
        * wptW32API.cpp (get_temp_name): New.
        * wptKeyserver.cpp (ldap_recvkey): Use it here.
        * wptKeyPropsDlg.cpp (get_photo_tmpname): Likewise.
        * wptGPGUtil.cpp (create_tempfile): Likewise.
        * wptImportList.cpp (implist_load): Likewise.
        * wptKeyCache.cpp (parse_attr_data): Likewise.
        (w32_tempfile): Removed.
        * wptGPGME.cpp (check_ultimate_trusted_key): New.
                                                                                                                            

1 /* wptKeyserver.cpp - W32 Keyserver Access
2 * Copyright (C) 2000-2005 Timo Schulz
3 * Copyright (C) 2001 Marco Cunha
4 *
5 * This file is part of WinPT.
6 *
7 * WinPT is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * WinPT is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with WinPT; if not, write to the Free Software Foundation,
19 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <windows.h>
27 #include <shlobj.h>
28 #include <stdio.h>
29 #include <sys/stat.h>
30 #include <ctype.h>
31
32 #include "wptKeyserver.h"
33 #include "wptErrors.h"
34 #include "wptTypes.h"
35 #include "wptNLS.h"
36 #include "wptW32API.h"
37 #include "wptGPG.h"
38 #include "wptRegistry.h"
39
40 #define net_errno ((int)WSAGetLastError ())
41
42 static char base64code[] =
43 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
44
45 keyserver server[MAX_KEYSERVERS] = {0};
46 static keyserver_proxy_ctx proxy = {0};
47 static const char *server_list[] = {
48 "hkp://wwwkeys.nl.pgp.net",
49 "hkp://wwwkeys.pl.pgp.net",
50 "hkp://wwwkeys.at.pgp.net",
51 "hkp://wwwkeys.ch.pgp.net",
52 "hkp://wwwkeys.de.pgp.net",
53 "hkp://wwwkeys.dk.pgp.net",
54 "hkp://wwwkeys.cz.pgp.net",
55 "hkp://wwwkeys.es.pgp.net",
56 "hkp://wwwkeys.eu.pgp.net",
57 "hkp://wwwkeys.uk.pgp.net",
58 "hkp://wwwkeys.us.pgp.net",
59 "hkp://subkeys.pgp.net",
60 "ldap://keyserver.pgp.com",
61 NULL
62 };
63
64
65 static char hkp_errmsg[1024]; /* Holds the error message from the server */
66 static int hkp_err = 0; /* != 0 indicates an error occurred. */
67 static DWORD conf_timestamp = 0;/* timestamp of the configuration fiele. */
68
69 /* Default keyserver and port. */
70 char *default_keyserver = NULL;
71 WORD default_keyserver_port = 0;
72
73
74 /* Basic64 encode the input @inputstr to @outputstr. */
75 static void
76 base64_encode (const char *inputstr, char *outputstr, int maxlen)
77 {
78 int index = 0, temp = 0, res = 0, i = 0, inputlen = 0, len = 0;
79
80 /* XXX: check len < maxlen. */
81 inputlen = strlen (inputstr);
82 for (i = 0; i <inputlen; i++) {
83 res = temp;
84 res = (res << 8) | (inputstr[i] & 0xFF);
85 switch (index++) {
86 case 0: outputstr[len++] = base64code[res >> 2 & 0x3F]; res &= 0x3; break;
87 case 1: outputstr[len++] = base64code[res >> 4 & 0x3F]; res &= 0xF; break;
88 case 2: outputstr[len++] = base64code[res >> 6 & 0x3F];
89 outputstr[len++] = base64code[res & 0x3F]; res = index = 0; break;
90 }
91 temp = res;
92 }
93
94 switch (index) {
95 case 0: break;
96 case 2: outputstr[len++] = base64code[temp << 2 & 0x3F];
97 outputstr[len++] = '='; break;
98 case 1: outputstr[len++] = base64code[temp << 4 & 0x3F];
99 outputstr[len++] = '=';
100 outputstr[len++] = '=';
101 }
102
103 outputstr[len] = '\0';
104 }
105
106
107 /* Skip the URL schema and return only the host part of it. */
108 static const char*
109 skip_type_prefix (const char *hostname)
110 {
111 if (hostname && !strncmp (hostname, "http://", 7))
112 hostname += 7;
113 else if (hostname && !strncmp (hostname, "hkp://", 6))
114 hostname += 6;
115 else if (hostname && !strncmp (hostname, "finger://", 9))
116 hostname += 9;
117 else if (hostname && !strncmp (hostname, "ldap://", 7))
118 hostname += 7;
119 return hostname;
120 }
121
122
123 /* Check that the keyserver response indicates an OK.
124 Return 0 on success. */
125 static int
126 check_hkp_response (const char *resp, int recv)
127 {
128 char *p, *end;
129 int ec, len;
130
131 ec = recv ? WPTERR_WINSOCK_RECVKEY : WPTERR_WINSOCK_SENDKEY;
132 if (!strstr (resp, "HTTP/1.0 200 OK") &&
133 !strstr (resp, "HTTP/1.1 200 OK")) /* http error */
134 return ec;
135 if (strstr (resp, "Public Key Server -- Error")
136 || strstr (resp, "Public Key Server -- Error")
137 || strstr (resp, "No matching keys in database")) {
138 p = strstr (resp, "<p>");
139 if (p && strlen (p) < sizeof (hkp_errmsg)) {
140 end = strstr (p, "</p>");
141 len = end? (end - p + 1) : strlen (p);
142 memset (hkp_errmsg, 0, sizeof (hkp_errmsg));
143 strncpy (hkp_errmsg, p, len);
144 hkp_err = 1;
145 }
146 return ec;
147 }
148 return 0;
149 }
150
151
152 /* Read a single line (\r\n) from a socket.
153 Return 0 on success. */
154 static int
155 sock_getline (int fd, char *buf, int buflen, int *nbytes)
156 {
157 char ch;
158 int count = 0;
159
160 if (nbytes)
161 *nbytes = 0;
162 *buf = 0;
163 while (recv (fd, &ch, 1, 0) > 0) {
164 *buf++ = ch;
165 count++;
166 /* XXX: remove the '\r' */
167 if (ch == '\n' || count == (buflen - 1)) {
168 *buf = 0;
169 if (nbytes)
170 *nbytes = count;
171 return 0;
172 }
173 }
174
175 return -1;
176 }
177
178
179 /* Perform a select() on the given fd to find out
180 is there is data for reading. Wait at least @nsecs seconds. */
181 static int
182 sock_select (int fd, int nsecs)
183 {
184 FD_SET rfd;
185 timeval tv = {nsecs, 0};
186
187 FD_ZERO (&rfd);
188 FD_SET (fd, &rfd);
189 if (select (fd + 1, &rfd, NULL, NULL, &tv) == SOCKET_ERROR) {
190 log_debug ("sock_select: select() failed ec=%d.\r\n", net_errno);
191 return SOCKET_ERROR;
192 }
193 if (FD_ISSET (fd, &rfd))
194 return 1;
195 return 0;
196 }
197
198
199 /* Read from a socket @fd to buffer @buf with a fixed timeout
200 of 10 seconds. The amount of bytes which were read are
201 returned in @nbytes.
202 Return value: 0 on success. */
203 static int
204 sock_read (int fd, char *buf, int buflen, int *nbytes)
205 {
206 DWORD nread;
207 int nleft = buflen;
208 int rc, n = 0;
209
210 while (nleft > 0) {
211 if (n >= 10)
212 return WPTERR_WINSOCK_TIMEOUT;
213 rc = sock_select (fd, 1);
214 if (rc == SOCKET_ERROR)
215 return rc;
216 else if (!rc)
217 n++;
218 else {
219 nread = recv (fd, buf, nleft, 0);
220 if (nread == SOCKET_ERROR) {
221 log_debug ("sock_read: recv() failed ec=%d.\r\n", net_errno);
222 return SOCKET_ERROR;
223 }
224 else if (!nread)
225 break;
226 nleft -= nread;
227 buf += nread;
228 }
229 }
230 if (nbytes)
231 *nbytes = buflen - nleft;
232
233 return 0;
234 }
235
236 /* Read much data as possible from the socket @fd and
237 return the data in @buffer. Caller must free data.
238 Return value: 0 on success. */
239 int
240 sock_read_ext (int fd, char **buffer, int *r_bufferlen)
241 {
242 gpgme_data_t dh;
243 char buf[1024], *p;
244 size_t n=0;
245 int nread, rc;
246
247 gpgme_data_new (&dh);
248 while (n < 10) {
249 rc = sock_select (fd, 1);
250 if (rc == SOCKET_ERROR) {
251 gpgme_data_release (dh);
252 return rc;
253 }
254 else if (!rc)
255 n++;
256 else {
257 nread = recv (fd, buf, sizeof (buf), 0);
258 if (nread == SOCKET_ERROR)
259 return SOCKET_ERROR;
260 else if (!nread)
261 break;
262 gpgme_data_write (dh, buf, nread);
263 }
264 }
265 gpg_data_putc (dh, '\0');
266 p = gpgme_data_release_and_get_mem (dh, &n);
267 *buffer = m_strdup (p);
268 if (r_bufferlen)
269 *r_bufferlen = n;
270 gpgme_free (p);
271 return 0;
272 }
273
274
275 /* Write the buffer @buf with the length @buflen to a socket @fd. */
276 static int
277 sock_write (int fd, const char *buf, int buflen)
278 {
279 DWORD nwritten;
280 int nleft = buflen;
281
282 while (nleft > 0) {
283 nwritten = send (fd, buf, nleft, 0);
284 if (nwritten == SOCKET_ERROR) {
285 log_debug ("sock_write: send() failed ec=%d\r\n", net_errno);
286 return SOCKET_ERROR;
287 }
288 nleft -= nwritten;
289 buf += nwritten;
290 }
291
292 return 0;
293 }
294
295
296 /* Set the default keyserver. */
297 void
298 set_default_kserver (void)
299 {
300 char *p = get_reg_entry_keyserver ("Default");
301 free_if_alloc (default_keyserver);
302 default_keyserver = p && *p != ' ' ? p : m_strdup (DEF_HKP_KEYSERVER);
303 p = get_reg_entry_keyserver ("Default_Port");
304 if (p && *p) {
305 default_keyserver_port = (WORD)strtoul (p, NULL, 10);
306 free_if_alloc (p);
307 }
308 else
309 default_keyserver_port = HKP_PORT;
310 }
311
312
313 /* Initialize the Winsock2 interface.*/
314 int
315 wsock_init (void)
316 {
317 WSADATA wsa;
318
319 if (WSAStartup (0x202, &wsa)) {
320 log_debug ("wsock_init: WSAStartup failed ec=%d\r\n", net_errno);
321 return WPTERR_WINSOCK_INIT;
322 }
323 set_default_kserver ();
324 return 0;
325 }
326
327
328 /* Cleanup the Winsock2 interface. */
329 void
330 wsock_end (void)
331 {
332 char *p;
333 int i;
334
335 p = make_special_filename (CSIDL_APPDATA, "winpt\\keyserver.conf", NULL);
336 kserver_save_conf (p);
337 free_if_alloc (p);
338 free_if_alloc (default_keyserver);
339 for (i=0; i < MAX_KEYSERVERS; i++) {
340 if (server[i].used)
341 free_if_alloc (server[i].name);
342 }
343 WSACleanup ();
344 }
345
346
347 /* Return a string representation of a winsock error. */
348 const char*
349 wsock_strerror (void)
350 {
351 static char buf[384];
352 int ec = WSAGetLastError ();
353
354 switch (ec) {
355 case WSAENETDOWN:
356 return _("The network subsystem has failed");
357 case WSAHOST_NOT_FOUND:
358 return _("Authoritative Answer Host not found");
359 case WSAETIMEDOUT:
360 return _("The connection has been dropped because of a network failure");
361 default:
362 _snprintf (buf, sizeof (buf) -1, _("Unknown Winsock error ec=%d"),ec);
363 return buf;
364 }
365 return NULL;
366 }
367
368
369 /* Return the last keyserver error as a string. */
370 const char*
371 kserver_strerror (void)
372 {
373 if (hkp_err)
374 return hkp_errmsg;
375 return NULL;
376 }
377
378
379 /* Read a keyserver from the list at index @idx.
380 Return value: keyserver name at the given position. */
381 const char*
382 kserver_get_hostname (int idx, int type, WORD *port)
383 {
384 if (type == -1) {
385 *port = default_keyserver_port;
386 return default_keyserver;
387 }
388 else if (!type && idx < DIM (server_list)) {
389 *port = HKP_PORT;
390 return server_list[idx];
391 }
392 return NULL;
393 }
394
395
396 /* Check if the computer is connected to the internet.
397 Return 0 on success -1 otherwise. */
398 int
399 kserver_check_inet_connection (void)
400 {
401 int fd;
402
403 if (!kserver_connect (default_keyserver, default_keyserver_port, &fd)) {
404 closesocket (fd);
405 return 0;
406 }
407 return -1;
408 }
409
410
411 /* If the request contains the keyid, it have to be
412 always postfix with '0x'+keyid. This code checks
413 if the keyid is a decimal value and if so if it contains
414 the '0x'. If not it is inserted. */
415 const char*
416 kserver_check_keyid (const char *keyid)
417 {
418 static char id[21];
419
420 if (strstr (keyid, "@"))
421 return keyid; /* email address */
422 if (strncmp (keyid, "0x", 2)) {
423 memset (&id, 0, sizeof (id));
424 _snprintf (id, sizeof (id)-1, "0x%s", keyid);
425 return id;
426 }
427 return keyid;
428 }
429
430
431 /* Update the keyserver proxy user. */
432 static void
433 kserver_update_proxyuser (const char *proxy_user, const char *proxy_pass)
434 {
435 char t[257]; /* user:pass = 127+1+127+1 = 257 */
436 int n = 0;
437
438 n = 4*strlen (proxy_user) / 3 + 32 + strlen (proxy_pass) + 2;
439 free_if_alloc (proxy.base64_user);
440 proxy.base64_user = new char[n];
441 if (!proxy.base64_user)
442 BUG (0);
443 _snprintf (t, sizeof (t)-1, "%s:%s", proxy_user, proxy_pass);
444 base64_encode (t, proxy.base64_user, 257);
445 free_if_alloc (proxy.user);
446 free_if_alloc (proxy.pass);
447 proxy.user = m_strdup (proxy_user);
448 proxy.pass = m_strdup (proxy_pass);
449 }
450
451
452 /* Check that the given buffer contains a valid keyserver URL. */
453 static int
454 check_URL (const char * buf)
455 {
456 if (strlen (buf) < 7)
457 return -1;
458 if (!strstr (buf, "ldap://")
459 && !strstr (buf, "http://")
460 && !strstr (buf, "finger://")
461 && !strstr (buf, "hkp://"))
462 return -1;
463 return 0;
464 }
465
466
467 /* Get the port number from the given protocol. */
468 static int
469 port_from_proto (int proto)
470 {
471 switch (proto) {
472 case KSPROTO_LDAP: return 0;
473 case KSPROTO_FINGER: return FINGER_PORT;
474 case KSPROTO_HTTP: return HKP_PORT;
475 }
476 return 0;
477 }
478
479
480 /* Get the port number from the given URL. */
481 static int
482 proto_from_URL (const char * buf)
483 {
484 if (strstr( buf, "ldap"))
485 return KSPROTO_LDAP;
486 else if (strstr( buf, "finger"))
487 return KSPROTO_FINGER;
488 return KSPROTO_HKP;
489 }
490
491
492 void
493 keyserver_set_default (const char *hostname, WORD port)
494 {
495 if (hostname) {
496 free_if_alloc (default_keyserver);
497 default_keyserver = m_strdup (hostname);
498 if (!default_keyserver)
499 BUG (0);
500 default_keyserver_port = port;
501 }
502 server[0].name = m_strdup (default_keyserver);
503 server[0].used = 1;
504 server[0].port = port;
505 server[0].proto = proto_from_URL (default_keyserver);
506 }
507
508
509 /* Skip all kind of whitespace chars in @str. */
510 static const char*
511 skip_whitespace (const char *str)
512 {
513 while (str && *str) {
514 if (*str == ' ' ||
515 *str == '\t' ||
516 *str == '\n' ||
517 *str == '\r') {
518 str++;
519 continue;
520 }
521 break;
522 }
523 return str;
524 }
525
526
527 /* Save the keyserver config file in @conf. */
528 int
529 kserver_save_conf (const char *conf)
530 {
531 FILE *fp;
532 int pos;
533
534 fp = fopen (conf, "wb");
535 if (!fp) {
536 msg_box (NULL, _("Could not save keyserver.conf file"),
537 _("Keyserver"), MB_ERR);
538 return -1;
539 }
540
541 fprintf (fp, "# do NOT manually modify this file, it will be generated automatically!!\r\n");
542 for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
543 if (!server[pos].used)
544 continue;
545 fprintf (fp, "%s:%d\r\n", server[pos].name, server[pos].port);
546 }
547 fclose (fp);
548 return 0;
549 }
550
551
552 /* Load the keyserver config file @conf. */
553 int
554 kserver_load_conf (const char *conf)
555 {
556 struct stat statbuf;
557 FILE *fp;
558 char buf[1024], * s, * p;
559 char *user = NULL, *pass = NULL;
560 int no_config=0, chk_pos=0;
561 int pos;
562
563 for (pos = 0; pos < MAX_KEYSERVERS; pos++) {
564 server[pos].used = 0;
565 server[pos].port = HKP_PORT;
566 }
567
568 fp = fopen (conf, "rb");
569 if (!fp) {
570 for (pos = 0; server_list[pos]; pos++) {
571 server[pos].used = 1;
572 server[pos].name = m_strdup (server_list[pos]);
573 server[pos].proto = proto_from_URL (server_list[pos]);
574 }
575 no_config=1;
576 }
577 get_reg_proxy_prefs (&proxy.host, &proxy.port, &user, &pass);
578 if (user && pass)
579 kserver_update_proxyuser (user, pass);
580 else if (user && !pass || !user && pass) {
581 msg_box (NULL, _("Invalid proxy configuration."
582 "You need to set a user and a password"
583 "to use proxy authentication!"),
584 _("Proxy Error"), MB_ERR);
585 }
586 /* check if the host has a http:// prefix and skip it */
587 if (proxy.host && !strncmp (proxy.host, "http://", 7)) {
588 char *host = m_strdup (proxy.host+7);
589 if (!host)
590 BUG (0);
591 free_if_alloc (proxy.host);
592 proxy.host = host;
593 }
594 free_if_alloc (user);
595 free_if_alloc (pass);
596
597 pos = 0;
598 while (fp && !feof (fp)) {
599 s = fgets (buf, sizeof (buf)-1, fp);
600 if (!s)
601 break;
602 if (strstr (buf, "\r\n"))
603 buf[strlen (buf)-2] = '\0';
604 if (strstr (buf, "\n"))
605 buf[strlen (buf)-1] = '\0';
606 s = (char *)skip_whitespace (buf);
607 if (*s == '#' || strlen (s) < 7)
608 continue;
609 if (check_URL (s)) {
610 msg_box (NULL, _("All entries of this file must have a valid prefix.\n"
611 "Currently HKP/HTTP, LDAP and FINGER are supported.\n"),
612 _("Keyserver Error"), MB_ERR);
613 continue;
614 }
615 chk_pos=6;
616 if (strstr (s, "finger"))
617 chk_pos = 10;
618 p = strchr (s+chk_pos, ':');
619 server[pos].used = 1;
620 server[pos].proto = proto_from_URL (s);
621 server[pos].port = port_from_proto (server[pos].proto);
622 if (!p)
623 server[pos].name = m_strdup (s);
624 else {
625 server[pos].port = atol (p+1);
626 if (server[pos].port < 0 || server[pos].port > 65536)
627 server[pos].port = HKP_PORT;
628 server[pos].name = new char [(p-s)+2];
629 if (!server[pos].name)
630 BUG (0);
631 memset (server[pos].name, 0, (p-s)+2);
632 memcpy (server[pos].name, s, (p-s));
633 }
634 pos++;
635 if (pos > MAX_KEYSERVERS) {
636 msg_box (NULL, _("The keyserver limit is exceeded"),
637 _("Keyserver Warning"), MB_INFO);
638 break;
639 }
640 }
641 if (fp)
642 fclose (fp);
643 if (!pos) {
644 /* only issue an error if the config file exist but it has no valid entries. */
645 keyserver_set_default (NULL, HKP_PORT);
646 if (!no_config)
647 return WPTERR_CONFIG_FILE;
648 }
649
650 if (!stat (conf, &statbuf))
651 conf_timestamp = statbuf.st_mtime;
652 return 0;
653 }
654
655
656 /* Return the proxy host and port if available. Null otherwise. */
657 const char*
658 kserver_get_proxy (int *r_port)
659 {
660 if (proxy.host) {
661 if (r_port)
662 *r_port = proxy.port;
663 return proxy.host;
664 }
665 return NULL;
666 }
667
668
669 /* Return a requested item from the proxy environment. */
670 const char*
671 kserver_get_proxy_info (int id)
672 {
673 switch (id) {
674 case PROXY_USER: return proxy.user;
675 case PROXY_PASS: return proxy.pass;
676 }
677 return NULL;
678 }
679
680
681 /* Connect to the keyserver @hostname (port @port).
682 Return value: 0 on success */
683 int
684 kserver_connect (const char *hostname, WORD port, int *conn_fd)
685 {
686 int rc, fd;
687 DWORD iaddr;
688 char host[128] = {0};
689 struct hostent *hp;
690 struct sockaddr_in sock;
691
692 log_debug ("kserver_connect: %s:%d\r\n", hostname, port);
693
694 if (!port)
695 port = HKP_PORT;
696 if (conn_fd)
697 *conn_fd = 0;
698 hostname = skip_type_prefix (hostname);
699
700 memset (&sock, 0, sizeof (sock));
701 sock.sin_family = AF_INET;
702 sock.sin_port = proxy.host? htons (proxy.port) : htons (port);
703 if (proxy.host)
704 strncpy (host, proxy.host, 127);
705 else
706 strncpy (host, hostname, 127);
707
708 if ((iaddr = inet_addr (host)) != INADDR_NONE)
709 memcpy (&sock.sin_addr, &iaddr, sizeof (iaddr));
710 else if ((hp = gethostbyname (host))) {
711 if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
712 log_debug ("gethostbyname: unknown address type.\r\n");
713 return WPTERR_WINSOCK_RESOLVE;
714 }
715 memcpy (&sock.sin_addr, hp->h_addr, hp->h_length);
716 }
717 else {
718 log_debug ("gethostbyname: failed ec=%d.\r\n", net_errno);
719 return WPTERR_WINSOCK_RESOLVE;
720 }
721 fd = socket (AF_INET, SOCK_STREAM, 0);
722 if (fd == INVALID_SOCKET)
723 return WPTERR_WINSOCK_SOCKET;
724 rc = connect (fd, (struct sockaddr *) &sock, sizeof (sock));
725 if (rc == SOCKET_ERROR) {
726 log_debug ("connect: failed ec=%d.\r\n", net_errno);
727 closesocket (fd);
728 return WPTERR_WINSOCK_CONNECT;
729 }
730
731 if (conn_fd)
732 *conn_fd = fd;
733 WSASetLastError (0);
734 return 0;
735 }
736
737
738 static bool
739 URL_must_encoded (const char *url)
740 {
741 if (strchr (url, '.') || strchr (url, '@') || strchr (url, ' '))
742 return true;
743 return false;
744 }
745
746
747 /* Perform URL encoding of the given data. */
748 static char*
749 URL_encode (const char *url, size_t ulen, size_t *ret_nlen)
750 {
751 gpgme_data_t hd;
752 char numbuf[5], *pp, *p;
753 size_t i, n;
754
755 gpgme_data_new (&hd);
756 for (i=0; i < ulen; i++) {
757 if (isalnum (url[i]) || url[i] == '-')
758 gpg_data_putc (hd, url[i]);
759 else if (url[i] == ' ')
760 gpg_data_putc (hd, '+');
761 else {
762 sprintf (numbuf, "%%%02X", url[i]);
763 gpgme_data_write (hd, numbuf, strlen (numbuf));
764 }
765 }
766 gpg_data_putc (hd, '\0');
767
768 /* Copy memory to avoid that we need to use gpgme_free later. */
769 pp = gpgme_data_release_and_get_mem (hd, &n);
770 p = m_strdup (pp);
771 gpgme_free (pp);
772 if (ret_nlen)
773 *ret_nlen = n;
774 return p;
775 }
776
777
778 /* Format a request for the given keyid (send). */
779 static char*
780 kserver_send_request (const char *hostname, WORD port,
781 const char *pubkey, int octets)
782 {
783 char *request = NULL;
784 char *enc_pubkey = NULL;
785 size_t enc_octets;
786 int reqlen;
787
788 log_debug ("kserver_send_request: %s:%d\r\n", hostname, port);
789
790 if (!port)
791 port = HKP_PORT;
792 reqlen = 512 + strlen (hostname) + 2*strlen (pubkey);
793 request = new char[reqlen];
794 if (!request)
795 BUG (0);
796 enc_pubkey = URL_encode (pubkey, octets, &enc_octets);
797 if (!enc_pubkey || !enc_octets) {
798 free_if_alloc (request);
799 return NULL;
800 }
801
802 if (proxy.user) {
803 _snprintf (request, reqlen-1,
804 "POST http://%s:%d/pks/add HTTP/1.0\r\n"
805 "Referer: \r\n"
806 "User-Agent: WinPT/W32\r\n"
807 "Host: %s:%d\r\n"
808 "Proxy-Authorization: Basic %s\r\n"
809 "Content-type: application/x-www-form-urlencoded\r\n"
810 "Content-length: %d\r\n"
811 "\r\n"
812 "keytext=%s"
813 "\n",
814 skip_type_prefix (hostname), port, hostname, port,
815 proxy.base64_user, enc_octets+9, enc_pubkey);
816 }
817 else {
818 _snprintf (request, reqlen-1,
819 "POST /pks/add HTTP/1.0\r\n"
820 "Referer: \r\n"
821 "User-Agent: WinPT/W32\r\n"
822 "Host: %s:%d\r\n"
823 "Content-type: application/x-www-form-urlencoded\r\n"
824 "Content-length: %d\r\n"
825 "\r\n"
826 "keytext=%s"
827 "\n",
828 skip_type_prefix (hostname), port,
829 enc_octets+9, enc_pubkey);
830 }
831 free_if_alloc (enc_pubkey);
832
833 log_debug ("%s\r\n", request);
834 return request;
835 }
836
837
838 int
839 kserver_recvkey_ext (const char *hostname, WORD port, const char *keyid,
840 char **r_key, int *r_keylen)
841 {
842 char *request = NULL;
843 int conn_fd;
844 int rc, n;
845
846 if (!port)
847 port = HKP_PORT;
848 hkp_err = 0; /* reset */
849 rc = kserver_connect (hostname, port, &conn_fd);
850 if (rc)
851 goto leave;
852
853 request = new char[300+1];
854 if (!request)
855 BUG (0);
856
857 if (proxy.host && proxy.user) {
858 _snprintf (request, 300,
859 "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n"
860 "Proxy-Authorization: Basic %s\r\n\r\n",
861 skip_type_prefix (hostname), port, keyid, proxy.base64_user);
862 }
863 else if (proxy.host) {
864 _snprintf (request, 300,
865 "GET http://%s:%d/pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n",
866 skip_type_prefix (hostname), port, keyid);
867 }
868 else {
869 _snprintf (request, 300,
870 "GET /pks/lookup?op=get&search=%s HTTP/1.0\r\n\r\n", keyid);
871 }
872
873 log_debug ("%s\r\n", request);
874
875 rc = sock_write (conn_fd, request, strlen (request));
876 if (rc == SOCKET_ERROR) {
877 rc = WPTERR_WINSOCK_RECVKEY;
878 goto leave;
879 }
880
881 rc = sock_read_ext (conn_fd, r_key, &n);
882 if (rc == SOCKET_ERROR) {
883 rc = WPTERR_WINSOCK_RECVKEY;
884 goto leave;
885 }
886
887 if (r_keylen)
888 *r_keylen = n;
889 log_debug("%s\r\n", *r_key);
890 rc = check_hkp_response (*r_key, 1);
891 if (rc)
892 goto leave;
893
894 WSASetLastError (0);
895
896 leave:
897 closesocket (conn_fd);
898 free_if_alloc (request);
899 return rc;
900 }
901
902 /* Interface for receiving a public key. */
903 int
904 kserver_recvkey (const char *hostname, WORD port, const char *keyid,
905 char *key, int maxkeylen)
906 {
907 char *tmpkey;
908 int rc, nread=0;
909
910 /* XXX: just a wrapper around the new method, replace it
911 soon as possible. */
912 rc = kserver_recvkey_ext (hostname, port, keyid, &tmpkey, &nread);
913 if (rc)
914 return rc;
915
916 if (nread > maxkeylen) {
917 free_if_alloc (tmpkey);
918 return WPTERR_GENERAL;
919 }
920 strcpy (key, tmpkey);
921 free_if_alloc (tmpkey);
922 return 0;
923 }
924
925
926 /* Interface to send a public key. */
927 int
928 kserver_sendkey (const char *hostname, WORD port, const char *pubkey, int len )
929 {
930 char *request = NULL;
931 char log[2048];
932 int conn_fd, n;
933 int rc;
934
935 hkp_err = 0; /* reset */
936 rc = kserver_connect (hostname, port, &conn_fd);
937 if (rc)
938 goto leave;
939
940 request = kserver_send_request (hostname, port, pubkey, len);
941 if (request == NULL) {
942 rc = WPTERR_GENERAL;
943 goto leave;
944 }
945
946 rc = sock_write (conn_fd, request, strlen (request));
947 if (rc == SOCKET_ERROR) {
948 rc = WPTERR_WINSOCK_SENDKEY;
949 goto leave;
950 }
951
952 rc = sock_read (conn_fd, log, sizeof (log)-1, &n);
953 if (rc == SOCKET_ERROR) {
954 rc = WPTERR_WINSOCK_SENDKEY;
955 goto leave;
956 }
957
958 log_debug ("kserver_sendkey:\r\n%s\r\n", log);
959 rc = check_hkp_response (log, 0);
960 if (rc)
961 goto leave;
962
963 WSASetLastError (0);
964
965 leave:
966 closesocket (conn_fd);
967 free_if_alloc (request);
968 return rc;
969 }
970
971
972 int
973 kserver_search_init (const char *hostname, WORD port,
974 const char *keyid, int *conn_fd)
975 {
976 char *request = NULL;
977 char *enc_keyid = NULL;
978 int n = 0;
979 int rc, sock_fd;
980
981 rc = kserver_connect (hostname, port, &sock_fd);
982 if (rc) {
983 *conn_fd = 0;
984 goto leave;
985 }
986
987 enc_keyid = URL_encode (keyid, strlen (keyid), NULL);
988 n=300;
989 request = new char[n+1];
990 if (!request)
991 BUG (0);
992
993 if (proxy.host && proxy.user) {
994 _snprintf (request, n,
995 "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n"
996 "Proxy-Authorization: Basic %s\r\n\r\n",
997 skip_type_prefix (hostname), port, enc_keyid, proxy.base64_user);
998 }
999 else if (proxy.host) {
1000 _snprintf (request, n,
1001 "GET http://%s:%d/pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",
1002 skip_type_prefix (hostname), port, enc_keyid);
1003 }
1004 else {
1005 _snprintf (request, n,
1006 "GET /pks/lookup?op=index&search=%s HTTP/1.0\r\n\r\n",
1007 enc_keyid);
1008 }
1009
1010 log_debug ("kserver_search_init:\r\n%s\r\n", request);
1011
1012 if (sock_write (sock_fd, request, strlen (request)) == SOCKET_ERROR) {
1013 rc = WPTERR_GENERAL;
1014 goto leave;
1015 }
1016
1017 *conn_fd = sock_fd;
1018
1019 leave:
1020 free_if_alloc (request);
1021 free_if_alloc (enc_keyid);
1022 return rc;
1023 }
1024
1025
1026 /* Check keyserver response. */
1027 int
1028 kserver_search_chkresp (int fd)
1029 {
1030 char buf[128];
1031 int n=0;
1032
1033 /* parse response 'HTTP/1.0 500 OK' */
1034 if (sock_getline (fd, buf, 127, &n))
1035 return WPTERR_KEYSERVER_NOTFOUND;
1036
1037 log_debug ("kserver_search_chkpresp: %s\r\n", buf);
1038 if (strncmp (buf, "HTTP/1.", 7))
1039 return WPTERR_KEYSERVER_NOTFOUND;
1040 if (strncmp (buf+(8+1), "200", 3))
1041 return WPTERR_KEYSERVER_NOTFOUND;
1042 return 0;
1043 }
1044
1045
1046 /* Convert an iso date @iso_date (YYYY-MM-DD) into the locale
1047 representation and store it into @loc_date.
1048 Return value: 0 on success. */
1049 static int
1050 parse_iso_date (const char *iso_date, char *loc_date, size_t loclen)
1051 {
1052 SYSTEMTIME st;
1053 char buf[16] = {0}, *p;
1054 int pos=0;
1055
1056 strncpy (buf, iso_date, sizeof (buf)-1);
1057 p = strtok (buf, "-");
1058 while (p != NULL) {
1059 switch (pos) {
1060 case 0: st.wYear = (WORD)atoi (p); pos++; break;
1061 case 1: st.wMonth = (WORD)atoi (p); pos++; break;
1062 case 2: st.wDay = (WORD)atoi (p); pos++; break;
1063 default: break;
1064 }
1065 p = strtok (NULL, "-");
1066 }
1067 if (pos != 3)
1068 return -1;
1069
1070 if (!GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
1071 NULL, loc_date, loclen))
1072 return -1;
1073 return 0;
1074 }
1075
1076
1077 int
1078 kserver_search (int fd, keyserver_key *key)
1079 {
1080 char buf[1024], *p;
1081 int uidlen, nbytes, pos = 0;
1082
1083 log_debug ("keyserver_search:\r\n");
1084
1085 if (sock_getline (fd, buf, sizeof (buf) - 1, &nbytes))
1086 return WPTERR_GENERAL;
1087
1088 log_debug ("%s\r\n", buf);
1089
1090 if (!strncmp (buf, "pub", 3)) {
1091 int revoked = strstr (buf, "KEY REVOKED") != NULL? 1 : 0;
1092 key->bits = atol (buf+3);
1093 p = strchr (buf, '>');
1094 if (!p)
1095 goto fail;
1096 pos = p - buf + 1;
1097 memcpy (key->keyid, buf + pos, 8);
1098 key->keyid[8] = '\0';
1099 p = strstr (buf, "</a>");
1100 if (!p)
1101 goto fail;
1102 pos = p - buf + 5;
1103 memcpy (key->date, buf + pos, 10);
1104 key->date[10] = '\0';
1105 parse_iso_date (key->date, key->date, sizeof (key->date)-1);
1106 if (revoked) {
1107 strcpy (key->uid, "KEY REVOKED: not checked");
1108 return 0;
1109 }
1110 pos += 10;
1111 p = buf + pos + 1;
1112 while (p && *p != '>')
1113 p++;
1114 p++;
1115 uidlen = strlen (p) - 10;
1116 if (!strstr (p, "&lt;") && !strstr (p, "&gt;")) {
1117 pos=0;
1118 while (p && *p && pos < sizeof (key->uid)-1) {
1119 if (*p == '<')
1120 break;
1121 key->uid[pos++] = *p++;
1122 }
1123 key->uid[pos] ='\0';
1124 return 0;
1125 }
1126
1127 if (uidlen > sizeof (key->uid)-1)
1128 uidlen = sizeof (key->uid)-1;
1129 memcpy (key->uid, p, uidlen);
1130 key->uid[uidlen] = '\0';
1131 strcat (key->uid, ">");
1132 p = strchr (key->uid, '&');
1133 if (p) {
1134 key->uid[(p-key->uid)] = '<';
1135 memmove (key->uid+(p-key->uid)+1, key->uid+(p-key->uid)+4,
1136 strlen (key->uid)-3);
1137 }
1138 return 0;
1139 }
1140
1141 fail:
1142 key->bits = 0;
1143 memset (key, 0, sizeof *key);
1144 return 0;
1145 }
1146
1147
1148 /* Replace all current proxy items with the items
1149 from the context @ctx. */
1150 void
1151 kserver_change_proxy (keyserver_proxy_ctx *ctx)
1152 {
1153 proxy.port = ctx->port;
1154 free_if_alloc (proxy.host);
1155 proxy.host = ctx->host? m_strdup (ctx->host) : NULL;
1156 free_if_alloc (proxy.pass);
1157 proxy.pass = ctx->pass? m_strdup (ctx->pass) : NULL;
1158 free_if_alloc (proxy.user);
1159 proxy.user = ctx->user? m_strdup (ctx->user) : NULL;
1160 set_reg_proxy_prefs (proxy.host, proxy.port, proxy.user, proxy.pass);
1161 }
1162
1163
1164 /* Release mbmers in the proxy context @ctx. */
1165 void
1166 proxy_release (keyserver_proxy_ctx *ctx)
1167 {
1168 free_if_alloc (ctx->host);
1169 free_if_alloc (ctx->pass);
1170 free_if_alloc (ctx->user);
1171 }
1172
1173
1174 /* Spawn a process given by @cmdl. */
1175 static int
1176 spawn_application (char *cmdl)
1177 {
1178 STARTUPINFO si;
1179 PROCESS_INFORMATION pi;
1180 int rc = 0;
1181
1182 memset (&si, 0, sizeof (si));
1183 si.cb = sizeof (si);
1184 si.dwFlags = STARTF_USESHOWWINDOW;
1185 si.wShowWindow = SW_HIDE;
1186 memset (&pi, 0, sizeof (pi));
1187
1188 if (!CreateProcess (NULL, cmdl, NULL, NULL, FALSE, 0,
1189 NULL, NULL, &si, &pi)) {
1190 log_box ("Keyserver Plugin", MB_ERR, "Could not spawn helper process");
1191 rc = -1;
1192 }
1193
1194 CloseHandle (pi.hThread);
1195 WaitForSingleObject (pi.hProcess, INFINITE);
1196 CloseHandle (pi.hProcess);
1197 return rc;
1198 }
1199
1200
1201 /* Receive an key via LDAP from host @host with the keyid @keyid.
1202 @key contains the key on success. */
1203 int
1204 ldap_recvkey (const char *host, const char *keyid, char *key, int maxkeylen)
1205 {
1206 FILE *fp;
1207 const char *s;
1208 char *ksprg = NULL, *p = NULL, *sep;
1209 char inf[256], outf[256], buf[512];
1210 DWORD n;
1211 int start_key = 0, failed = 0;
1212 int rc = 0;
1213
1214 p = get_gnupg_prog ();
1215 n = strlen (p) + 1 + 128;
1216 ksprg = new char[n+1];
1217 if (!ksprg)
1218 BUG (0);
1219 sep = strrchr (p, '\\');
1220 if (sep != NULL)
1221 p[(sep-p)] = 0;
1222
1223 _snprintf (ksprg, n, "%s\\gpgkeys_ldap.exe", p);
1224 free_if_alloc (p);
1225 if (file_exist_check (ksprg)) {
1226 log_box ("LDAP Keyserver Plugin", MB_ERR,
1227 "%s: could not find LDAP keyserver module!", ksprg);
1228 rc = -1;
1229 goto leave;
1230 }
1231 get_temp_name (outf, sizeof (outf)-1, keyid);
1232 get_temp_name (inf, sizeof (inf)-1, NULL);
1233 fp = fopen (inf, "w+b");
1234 if (!fp) {
1235 log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", inf,
1236 winpt_strerror (WPTERR_FILE_OPEN));
1237 rc = -1;
1238 goto leave;
1239 }
1240 fprintf (fp,
1241 "VERSION 1\n"
1242 "PROGRAM 1.4.3-cvs\n"
1243 "SCHEME ldap\n"
1244 "HOST %s\n"
1245 "COMMAND GET\n"
1246 "\n"
1247 "%s\n",
1248 host? skip_type_prefix (host): "64.94.85.200", keyid);
1249 fclose (fp);
1250
1251 p = new char[strlen (ksprg) + strlen (inf) + strlen (outf) + 32];
1252 if (!p)
1253 BUG (NULL);
1254 sprintf (p, "%s -o %s %s", ksprg, outf, inf);
1255 if (spawn_application (p)) {
1256 rc = -1;
1257 goto leave;
1258 }
1259
1260 fp = fopen (outf, "rb");
1261 if (!fp) {
1262 log_box ("LDAP Keyserver Plugin", MB_ERR, "%s: %s", outf,
1263 winpt_strerror (WPTERR_FILE_OPEN));
1264 rc = -1;
1265 goto leave;
1266 }
1267 memset (key, 0, maxkeylen);
1268 while (!feof (fp)) {
1269 s = fgets (buf, sizeof (buf)-1, fp);
1270 if (!s)
1271 break;
1272 if (strstr (s, "KEY") && strstr (s, "FAILED")) {
1273 failed = 1;
1274 break;
1275 }
1276 if (!start_key && strstr (s, "KEY") && strstr (s, "BEGIN")) {
1277 start_key = 1;
1278 continue;
1279 }
1280 if (!start_key)
1281 continue;
1282 strcat (key, buf);
1283 maxkeylen -= strlen (buf);
1284 if (maxkeylen < 0 || (strstr (s, "KEY") && strstr (s, "END")))
1285 break;
1286 }
1287 fclose (fp);
1288
1289 leave:
1290 if (failed || !strlen (key))
1291 rc = WPTERR_WINSOCK_RECVKEY;
1292 DeleteFile (inf);
1293 DeleteFile (outf);
1294 free_if_alloc (p);
1295 free_if_alloc (ksprg);
1296 return rc;
1297 }
1298
1299
1300 static int
1301 finger_readline (int fd, char *buf, int nbytes)
1302 {
1303 char c = 0;
1304 int n, pos = 0;
1305
1306 while (nbytes > 0) {
1307 n = recv (fd, &c, 1, 0);
1308 if (n <= 0)
1309 break;
1310 if (c == '\n')
1311 break;
1312 buf[pos++] = c;
1313 nbytes--;
1314 }
1315 if (nbytes > 0)
1316 buf[pos++] = '\0';
1317 if (n <= 0)
1318 pos = n;
1319 return pos;
1320 }
1321
1322
1323 /* Receive an key via FINGER from host @host with the user @user.
1324 On success @key contains the key. */
1325 int
1326 finger_recvkey (const char *host, const char *user, char *key, int maxkeylen)
1327 {
1328 struct hostent * hp;
1329 struct sockaddr_in saddr;
1330 char buf[128];
1331 int fd, nread;
1332 int start_key = 0;
1333 int rc=0;
1334
1335 fd = socket (PF_INET, SOCK_STREAM, 0);
1336 if (fd == -1)
1337 return WPTERR_WINSOCK_SOCKET;
1338 hp = gethostbyname (skip_type_prefix (host));
1339 if (!hp) {
1340 closesocket (fd);
1341 return WPTERR_WINSOCK_RESOLVE;
1342 }
1343
1344 memset (&saddr, 0, sizeof (saddr));
1345 saddr.sin_family = AF_INET;
1346 saddr.sin_port = htons (FINGER_PORT);
1347 saddr.sin_addr = *(struct in_addr *)hp->h_addr;
1348 if (connect (fd, (struct sockaddr *)&saddr, sizeof (saddr))) {
1349 closesocket (fd);
1350 return WPTERR_WINSOCK_CONNECT;
1351 }
1352 send (fd, user, strlen (user), 0);
1353 send (fd, "\r\n", 2, 0);
1354
1355 memset (key, 0, maxkeylen);
1356 while (maxkeylen > 0) {
1357 nread = finger_readline (fd, buf, sizeof (buf)-1);
1358 if (nread <= 0)
1359 break;
1360 strcat (buf, "\n");
1361 if (strstr (buf, "BEGIN PGP PUBLIC KEY BLOCK")) {
1362 strcat (key, buf);
1363 start_key = 1;
1364 maxkeylen -= nread;
1365 }
1366 else if (strstr (buf, "END PGP PUBLIC KEY BLOCK" ) && start_key) {
1367 strcat (key, buf);
1368 start_key--;
1369 maxkeylen -= nread;
1370 break;
1371 }
1372 else if (start_key) {
1373 strcat (key, buf);
1374 maxkeylen -= nread;
1375 }
1376 }
1377 closesocket (fd);
1378 if (start_key != 0)
1379 rc = WPTERR_WINSOCK_RECVKEY;
1380 return rc;
1381 }
1382
1383
1384 /* Check if the given name @name is a valid hostname. */
1385 int
1386 check_IP_or_hostname (const char *name)
1387 {
1388 const char *not_allowed = "=!ยง$%&@#*~\\/}][{<>|,;:'";
1389 size_t i, j;
1390
1391 for (i=0; i < strlen (name); i++) {
1392 for (j =0; j < strlen (not_allowed); j++) {
1393 if (name[i] == not_allowed[j])
1394 return -1;
1395 }
1396 }
1397 return 0;
1398 }

Properties

Name Value
svn:eol-style native

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26