2007-09-14 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / keyserver / gpgkeys_ldap.c
blobdf107ff9ccf7fc751fcc6ebe3c11c50940ae7f9e
1 /* gpgkeys_ldap.c - talk to a LDAP keyserver
2 * Copyright (C) 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 * In addition, as a special exception, the Free Software Foundation
20 * gives permission to link the code of the keyserver helper tools:
21 * gpgkeys_ldap, gpgkeys_curl and gpgkeys_hkp with the OpenSSL
22 * project's "OpenSSL" library (or with modified versions of it that
23 * use the same license as the "OpenSSL" library), and distribute the
24 * linked executables. You must obey the GNU General Public License
25 * in all respects for all of the code used other than "OpenSSL". If
26 * you modify this file, you may extend this exception to your version
27 * of the file, but you are not obligated to do so. If you do not
28 * wish to do so, delete this exception statement from your version.
31 #include <config.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <time.h>
35 #include <unistd.h>
36 #ifdef HAVE_GETOPT_H
37 #include <getopt.h>
38 #endif
39 #include <stdlib.h>
40 #include <errno.h>
41 #include <assert.h>
43 #ifdef _WIN32
44 #include <winsock2.h>
45 #include <winldap.h>
46 #else
47 #ifdef NEED_LBER_H
48 #include <lber.h>
49 #endif
50 /* For OpenLDAP, to enable the API that we're using. */
51 #define LDAP_DEPRECATED 1
52 #include <ldap.h>
53 #endif
55 #include "util.h"
56 #include "keyserver.h"
57 #include "ksutil.h"
59 #ifdef __riscos__
60 #include "util.h"
61 #endif
63 extern char *optarg;
64 extern int optind;
66 static int real_ldap=0;
67 static char *basekeyspacedn=NULL;
68 static char *pgpkeystr="pgpKey";
69 static FILE *input=NULL,*output=NULL,*console=NULL;
70 static LDAP *ldap=NULL;
71 static struct ks_options *opt;
73 #ifndef HAVE_TIMEGM
74 time_t timegm(struct tm *tm);
75 #endif
77 static int
78 ldap_err_to_gpg_err(int err)
80 int ret;
82 switch(err)
84 case LDAP_ALREADY_EXISTS:
85 ret=KEYSERVER_KEY_EXISTS;
86 break;
88 case LDAP_SERVER_DOWN:
89 ret=KEYSERVER_UNREACHABLE;
90 break;
92 default:
93 ret=KEYSERVER_GENERAL_ERROR;
94 break;
97 return ret;
100 static int
101 ldap_to_gpg_err(LDAP *ld)
103 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
105 int err;
107 if(ldap_get_option(ld,LDAP_OPT_ERROR_NUMBER,&err)==0)
108 return ldap_err_to_gpg_err(err);
109 else
110 return KEYSERVER_GENERAL_ERROR;
112 #elif defined(HAVE_LDAP_LD_ERRNO)
114 return ldap_err_to_gpg_err(ld->ld_errno);
116 #else
118 /* We should never get here since the LDAP library should always
119 have either ldap_get_option or ld_errno, but just in case... */
120 return KEYSERVER_GENERAL_ERROR;
122 #endif
125 static int
126 key_in_keylist(const char *key,struct keylist *list)
128 struct keylist *keyptr=list;
130 while(keyptr!=NULL)
132 if(strcasecmp(key,keyptr->str)==0)
133 return 1;
135 keyptr=keyptr->next;
138 return 0;
141 static int
142 add_key_to_keylist(const char *key,struct keylist **list)
144 struct keylist *keyptr=malloc(sizeof(struct keylist));
146 if(keyptr==NULL)
148 fprintf(console,"gpgkeys: out of memory when deduping "
149 "key list\n");
150 return KEYSERVER_NO_MEMORY;
153 strncpy(keyptr->str,key,MAX_LINE);
154 keyptr->str[MAX_LINE-1]='\0';
155 keyptr->next=*list;
156 *list=keyptr;
158 return 0;
161 static void
162 free_keylist(struct keylist *list)
164 while(list!=NULL)
166 struct keylist *keyptr=list;
168 list=keyptr->next;
169 free(keyptr);
173 static time_t
174 ldap2epochtime(const char *timestr)
176 struct tm pgptime;
177 time_t answer;
179 memset(&pgptime,0,sizeof(pgptime));
181 /* YYYYMMDDHHmmssZ */
183 sscanf(timestr,"%4d%2d%2d%2d%2d%2d",
184 &pgptime.tm_year,
185 &pgptime.tm_mon,
186 &pgptime.tm_mday,
187 &pgptime.tm_hour,
188 &pgptime.tm_min,
189 &pgptime.tm_sec);
191 pgptime.tm_year-=1900;
192 pgptime.tm_isdst=-1;
193 pgptime.tm_mon--;
195 /* mktime() takes the timezone into account, so we use timegm() */
197 answer=timegm(&pgptime);
199 return answer;
202 /* Caller must free */
203 static char *
204 epoch2ldaptime(time_t stamp)
206 struct tm *ldaptime;
207 char buf[16];
209 ldaptime=gmtime(&stamp);
211 ldaptime->tm_year+=1900;
212 ldaptime->tm_mon++;
214 /* YYYYMMDDHHmmssZ */
216 sprintf(buf,"%04d%02d%02d%02d%02d%02dZ",
217 ldaptime->tm_year,
218 ldaptime->tm_mon,
219 ldaptime->tm_mday,
220 ldaptime->tm_hour,
221 ldaptime->tm_min,
222 ldaptime->tm_sec);
224 return strdup(buf);
227 /* Append two onto the end of one. Two is not freed, but its pointers
228 are now part of one. Make sure you don't free them both! */
229 static int
230 join_two_modlists(LDAPMod ***one,LDAPMod **two)
232 int i,one_count=0,two_count=0;
233 LDAPMod **grow;
235 for(grow=*one;*grow;grow++)
236 one_count++;
238 for(grow=two;*grow;grow++)
239 two_count++;
241 grow=realloc(*one,sizeof(LDAPMod *)*(one_count+two_count+1));
242 if(!grow)
243 return 0;
245 for(i=0;i<two_count;i++)
246 grow[one_count+i]=two[i];
248 grow[one_count+i]=NULL;
250 *one=grow;
252 return 1;
255 /* Passing a NULL for value effectively deletes that attribute. This
256 doesn't mean "delete" in the sense of removing something from the
257 modlist, but "delete" in the LDAP sense of adding a modlist item
258 that specifies LDAP_MOD_REPLACE and a null attribute for the given
259 attribute. LDAP_MOD_DELETE doesn't work here as we don't know if
260 the attribute in question exists or not. */
262 static int
263 make_one_attr(LDAPMod ***modlist,char *attr,const char *value)
265 LDAPMod **m;
266 int nummods=0;
268 /* Search modlist for the attribute we're playing with. */
269 for(m=*modlist;*m;m++)
271 if(strcasecmp((*m)->mod_type,attr)==0)
273 char **ptr=(*m)->mod_values;
274 int numvalues=0;
276 /* We have this attribute already, so when the REPLACE
277 happens, the server attributes will be replaced
278 anyway. */
279 if(!value)
280 return 1;
282 if(ptr)
283 for(ptr=(*m)->mod_values;*ptr;ptr++)
285 /* Duplicate value */
286 if(strcmp(*ptr,value)==0)
287 return 1;
288 numvalues++;
291 ptr=realloc((*m)->mod_values,sizeof(char *)*(numvalues+2));
292 if(!ptr)
293 return 0;
295 (*m)->mod_values=ptr;
296 ptr[numvalues]=strdup(value);
297 if(!ptr[numvalues])
298 return 0;
300 ptr[numvalues+1]=NULL;
301 break;
304 nummods++;
307 /* We didn't find the attr, so make one and add it to the end */
308 if(!*m)
310 LDAPMod **grow;
312 grow=realloc(*modlist,sizeof(LDAPMod *)*(nummods+2));
313 if(!grow)
314 return 0;
316 *modlist=grow;
317 grow[nummods]=malloc(sizeof(LDAPMod));
318 if(!grow[nummods])
319 return 0;
320 grow[nummods]->mod_op=LDAP_MOD_REPLACE;
321 grow[nummods]->mod_type=attr;
322 if(value)
324 grow[nummods]->mod_values=malloc(sizeof(char *)*2);
325 if(!grow[nummods]->mod_values)
327 grow[nummods]=NULL;
328 return 0;
331 /* Is this the right thing? Can a UTF8-encoded user ID have
332 embedded nulls? */
333 grow[nummods]->mod_values[0]=strdup(value);
334 if(!grow[nummods]->mod_values[0])
336 free(grow[nummods]->mod_values);
337 grow[nummods]=NULL;
338 return 0;
341 grow[nummods]->mod_values[1]=NULL;
343 else
344 grow[nummods]->mod_values=NULL;
346 grow[nummods+1]=NULL;
349 return 1;
352 static void
353 build_attrs(LDAPMod ***modlist,char *line)
355 char *record;
356 int i;
358 /* Remove trailing whitespace */
359 for(i=strlen(line);i>0;i--)
360 if(ascii_isspace(line[i-1]))
361 line[i-1]='\0';
362 else
363 break;
365 if((record=strsep(&line,":"))==NULL)
366 return;
368 if(ks_strcasecmp("pub",record)==0)
370 char *tok;
371 int disabled=0,revoked=0;
373 /* The long keyid */
374 if((tok=strsep(&line,":"))==NULL)
375 return;
377 if(strlen(tok)==16)
379 make_one_attr(modlist,"pgpCertID",tok);
380 make_one_attr(modlist,"pgpKeyID",&tok[8]);
382 else
383 return;
385 /* The primary pubkey algo */
386 if((tok=strsep(&line,":"))==NULL)
387 return;
389 switch(atoi(tok))
391 case 1:
392 make_one_attr(modlist,"pgpKeyType","RSA");
393 break;
395 case 17:
396 make_one_attr(modlist,"pgpKeyType","DSS/DH");
397 break;
400 /* Size of primary key */
401 if((tok=strsep(&line,":"))==NULL)
402 return;
404 if(atoi(tok)>0)
406 char padded[6];
407 int val=atoi(tok);
409 /* We zero pad this on the left to make PGP happy. */
411 if(val<99999 && val>0)
413 sprintf(padded,"%05u",atoi(tok));
414 make_one_attr(modlist,"pgpKeySize",padded);
418 /* pk timestamp */
419 if((tok=strsep(&line,":"))==NULL)
420 return;
422 if(atoi(tok)>0)
424 char *stamp=epoch2ldaptime(atoi(tok));
425 if(stamp)
427 make_one_attr(modlist,"pgpKeyCreateTime",stamp);
428 free(stamp);
432 /* pk expire */
433 if((tok=strsep(&line,":"))==NULL)
434 return;
436 if(atoi(tok)>0)
438 char *stamp=epoch2ldaptime(atoi(tok));
439 if(stamp)
441 make_one_attr(modlist,"pgpKeyExpireTime",stamp);
442 free(stamp);
446 /* flags */
447 if((tok=strsep(&line,":"))==NULL)
448 return;
450 while(*tok)
451 switch(*tok++)
453 case 'r':
454 case 'R':
455 revoked=1;
456 break;
458 case 'd':
459 case 'D':
460 disabled=1;
461 break;
465 Note that we always create the pgpDisabled and pgpRevoked
466 attributes, regardless of whether the key is disabled/revoked
467 or not. This is because a very common search is like
468 "(&(pgpUserID=*isabella*)(pgpDisabled=0))"
471 make_one_attr(modlist,"pgpDisabled",disabled?"1":"0");
472 make_one_attr(modlist,"pgpRevoked",revoked?"1":"0");
474 else if(ks_strcasecmp("sub",record)==0)
476 char *tok;
478 /* The long keyid */
479 if((tok=strsep(&line,":"))==NULL)
480 return;
482 if(strlen(tok)==16)
483 make_one_attr(modlist,"pgpSubKeyID",tok);
484 else
485 return;
487 /* The subkey algo */
488 if((tok=strsep(&line,":"))==NULL)
489 return;
491 /* Size of subkey */
492 if((tok=strsep(&line,":"))==NULL)
493 return;
495 if(atoi(tok)>0)
497 char padded[6];
498 int val=atoi(tok);
500 /* We zero pad this on the left to make PGP happy. */
502 if(val<99999 && val>0)
504 sprintf(padded,"%05u",atoi(tok));
505 make_one_attr(modlist,"pgpKeySize",padded);
509 /* Ignore the rest of the items for subkeys since the LDAP
510 schema doesn't store them. */
512 else if(ks_strcasecmp("uid",record)==0)
514 char *userid,*tok;
516 /* The user ID string */
517 if((tok=strsep(&line,":"))==NULL)
518 return;
520 if(strlen(tok)==0)
521 return;
523 userid=tok;
525 /* By definition, de-%-encoding is always smaller than the
526 original string so we can decode in place. */
528 i=0;
530 while(*tok)
531 if(tok[0]=='%' && tok[1] && tok[2])
533 if((userid[i]=ks_hextobyte(&tok[1]))==-1)
534 userid[i]='?';
536 i++;
537 tok+=3;
539 else
540 userid[i++]=*tok++;
542 userid[i]='\0';
544 /* We don't care about the other info provided in the uid: line
545 since the LDAP schema doesn't need it. */
547 make_one_attr(modlist,"pgpUserID",userid);
549 else if(ks_strcasecmp("sig",record)==0)
551 char *tok;
553 if((tok=strsep(&line,":"))==NULL)
554 return;
556 if(strlen(tok)==16)
557 make_one_attr(modlist,"pgpSignerID",tok);
561 static void
562 free_mod_values(LDAPMod *mod)
564 char **ptr;
566 if(!mod->mod_values)
567 return;
569 for(ptr=mod->mod_values;*ptr;ptr++)
570 free(*ptr);
572 free(mod->mod_values);
575 static int
576 send_key(int *r_eof)
578 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
579 char *dn=NULL,line[MAX_LINE],*key=NULL;
580 char keyid[17],state[6];
581 LDAPMod **modlist,**addlist,**ml;
583 modlist=malloc(sizeof(LDAPMod *));
584 if(!modlist)
586 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
587 ret=KEYSERVER_NO_MEMORY;
588 goto fail;
591 *modlist=NULL;
593 addlist=malloc(sizeof(LDAPMod *));
594 if(!addlist)
596 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
597 ret=KEYSERVER_NO_MEMORY;
598 goto fail;
601 *addlist=NULL;
603 /* Start by nulling out all attributes. We try and do a modify
604 operation first, so this ensures that we don't leave old
605 attributes lying around. */
606 make_one_attr(&modlist,"pgpDisabled",NULL);
607 make_one_attr(&modlist,"pgpKeyID",NULL);
608 make_one_attr(&modlist,"pgpKeyType",NULL);
609 make_one_attr(&modlist,"pgpUserID",NULL);
610 make_one_attr(&modlist,"pgpKeyCreateTime",NULL);
611 make_one_attr(&modlist,"pgpSignerID",NULL);
612 make_one_attr(&modlist,"pgpRevoked",NULL);
613 make_one_attr(&modlist,"pgpSubKeyID",NULL);
614 make_one_attr(&modlist,"pgpKeySize",NULL);
615 make_one_attr(&modlist,"pgpKeyExpireTime",NULL);
616 make_one_attr(&modlist,"pgpCertID",NULL);
618 /* Assemble the INFO stuff into LDAP attributes */
620 while(fgets(line,MAX_LINE,input)!=NULL)
621 if(sscanf(line,"INFO%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
622 && strcmp(state,"BEGIN")==0)
624 begin=1;
625 break;
628 if(!begin)
630 /* i.e. eof before the INFO BEGIN was found. This isn't an
631 error. */
632 *r_eof=1;
633 ret=KEYSERVER_OK;
634 goto fail;
637 if(strlen(keyid)!=16)
639 *r_eof=1;
640 ret=KEYSERVER_KEY_INCOMPLETE;
641 goto fail;
644 dn=malloc(strlen("pgpCertID=")+16+1+strlen(basekeyspacedn)+1);
645 if(dn==NULL)
647 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
648 ret=KEYSERVER_NO_MEMORY;
649 goto fail;
652 sprintf(dn,"pgpCertID=%s,%s",keyid,basekeyspacedn);
654 key=malloc(1);
655 if(!key)
657 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
658 ret=KEYSERVER_NO_MEMORY;
659 goto fail;
662 key[0]='\0';
664 /* Now parse each line until we see the END */
666 while(fgets(line,MAX_LINE,input)!=NULL)
667 if(sscanf(line,"INFO%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
668 && strcmp(state,"END")==0)
670 end=1;
671 break;
673 else
674 build_attrs(&addlist,line);
676 if(!end)
678 fprintf(console,"gpgkeys: no INFO %s END found\n",keyid);
679 *r_eof=1;
680 ret=KEYSERVER_KEY_INCOMPLETE;
681 goto fail;
684 begin=end=0;
686 /* Read and throw away stdin until we see the BEGIN */
688 while(fgets(line,MAX_LINE,input)!=NULL)
689 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
690 && strcmp(state,"BEGIN")==0)
692 begin=1;
693 break;
696 if(!begin)
698 /* i.e. eof before the KEY BEGIN was found. This isn't an
699 error. */
700 *r_eof=1;
701 ret=KEYSERVER_OK;
702 goto fail;
705 /* Now slurp up everything until we see the END */
707 while(fgets(line,MAX_LINE,input)!=NULL)
708 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
709 && strcmp(state,"END")==0)
711 end=1;
712 break;
714 else
716 char *tempkey;
717 keysize+=strlen(line);
718 tempkey=realloc(key,keysize);
719 if(tempkey==NULL)
721 fprintf(console,"gpgkeys: unable to reallocate for key\n");
722 ret=KEYSERVER_NO_MEMORY;
723 goto fail;
725 else
726 key=tempkey;
728 strcat(key,line);
731 if(!end)
733 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
734 *r_eof=1;
735 ret=KEYSERVER_KEY_INCOMPLETE;
736 goto fail;
739 make_one_attr(&addlist,"objectClass","pgpKeyInfo");
740 make_one_attr(&addlist,"pgpKey",key);
742 /* Now append addlist onto modlist */
743 if(!join_two_modlists(&modlist,addlist))
745 fprintf(console,"gpgkeys: unable to merge LDAP modification lists\n");
746 ret=KEYSERVER_NO_MEMORY;
747 goto fail;
750 /* Going on the assumption that modify operations are more frequent
751 than adds, we try a modify first. If it's not there, we just
752 turn around and send an add command for the same key. Otherwise,
753 the modify brings the server copy into compliance with our copy.
754 Note that unlike the LDAP keyserver (and really, any other
755 keyserver) this does NOT merge signatures, but replaces the whole
756 key. This should make some people very happy. */
758 err=ldap_modify_s(ldap,dn,modlist);
759 if(err==LDAP_NO_SUCH_OBJECT)
760 err=ldap_add_s(ldap,dn,addlist);
762 if(err!=LDAP_SUCCESS)
764 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
765 keyid,ldap_err2string(err));
766 ret=ldap_err_to_gpg_err(err);
767 goto fail;
770 ret=KEYSERVER_OK;
772 fail:
773 /* Unwind and free the whole modlist structure */
774 for(ml=modlist;*ml;ml++)
776 free_mod_values(*ml);
777 free(*ml);
780 free(modlist);
781 free(addlist);
782 free(dn);
783 free(key);
785 if(ret!=0 && begin)
786 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
788 return ret;
791 static int
792 send_key_keyserver(int *r_eof)
794 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
795 char *dn=NULL,line[MAX_LINE],*key[2]={NULL,NULL};
796 char keyid[17],state[6];
797 LDAPMod mod, *attrs[2];
799 memset(&mod,0,sizeof(mod));
800 mod.mod_op=LDAP_MOD_ADD;
801 mod.mod_type=pgpkeystr;
802 mod.mod_values=key;
803 attrs[0]=&mod;
804 attrs[1]=NULL;
806 dn=malloc(strlen("pgpCertid=virtual,")+strlen(basekeyspacedn)+1);
807 if(dn==NULL)
809 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
810 ret=KEYSERVER_NO_MEMORY;
811 goto fail;
814 strcpy(dn,"pgpCertid=virtual,");
815 strcat(dn,basekeyspacedn);
817 key[0]=malloc(1);
818 if(key[0]==NULL)
820 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
821 ret=KEYSERVER_NO_MEMORY;
822 goto fail;
825 key[0][0]='\0';
827 /* Read and throw away stdin until we see the BEGIN */
829 while(fgets(line,MAX_LINE,input)!=NULL)
830 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
831 && strcmp(state,"BEGIN")==0)
833 begin=1;
834 break;
837 if(!begin)
839 /* i.e. eof before the KEY BEGIN was found. This isn't an
840 error. */
841 *r_eof=1;
842 ret=KEYSERVER_OK;
843 goto fail;
846 /* Now slurp up everything until we see the END */
848 while(fgets(line,MAX_LINE,input)!=NULL)
849 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
850 && strcmp(state,"END")==0)
852 end=1;
853 break;
855 else
857 keysize+=strlen(line);
858 key[0]=realloc(key[0],keysize);
859 if(key[0]==NULL)
861 fprintf(console,"gpgkeys: unable to reallocate for key\n");
862 ret=KEYSERVER_NO_MEMORY;
863 goto fail;
866 strcat(key[0],line);
869 if(!end)
871 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
872 *r_eof=1;
873 ret=KEYSERVER_KEY_INCOMPLETE;
874 goto fail;
877 err=ldap_add_s(ldap,dn,attrs);
878 if(err!=LDAP_SUCCESS)
880 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
881 keyid,ldap_err2string(err));
882 ret=ldap_err_to_gpg_err(err);
883 goto fail;
886 ret=KEYSERVER_OK;
888 fail:
890 free(key[0]);
891 free(dn);
893 if(ret!=0 && begin)
894 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
896 /* Not a fatal error */
897 if(ret==KEYSERVER_KEY_EXISTS)
898 ret=KEYSERVER_OK;
900 return ret;
903 static void
904 build_info(const char *certid,LDAPMessage *each)
906 char **vals;
908 fprintf(output,"INFO %s BEGIN\n",certid);
910 fprintf(output,"pub:%s:",certid);
912 vals=ldap_get_values(ldap,each,"pgpkeytype");
913 if(vals!=NULL)
915 if(strcmp(vals[0],"RSA")==0)
916 fprintf(output,"1");
917 else if(strcmp(vals[0],"DSS/DH")==0)
918 fprintf(output,"17");
919 ldap_value_free(vals);
922 fprintf(output,":");
924 vals=ldap_get_values(ldap,each,"pgpkeysize");
925 if(vals!=NULL)
927 if(atoi(vals[0])>0)
928 fprintf(output,"%d",atoi(vals[0]));
929 ldap_value_free(vals);
932 fprintf(output,":");
934 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
935 if(vals!=NULL)
937 if(strlen(vals[0])==15)
938 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
939 ldap_value_free(vals);
942 fprintf(output,":");
944 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
945 if(vals!=NULL)
947 if(strlen(vals[0])==15)
948 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
949 ldap_value_free(vals);
952 fprintf(output,":");
954 vals=ldap_get_values(ldap,each,"pgprevoked");
955 if(vals!=NULL)
957 if(atoi(vals[0])==1)
958 fprintf(output,"r");
959 ldap_value_free(vals);
962 fprintf(output,"\n");
964 vals=ldap_get_values(ldap,each,"pgpuserid");
965 if(vals!=NULL)
967 int i;
969 for(i=0;vals[i];i++)
970 fprintf(output,"uid:%s\n",vals[i]);
971 ldap_value_free(vals);
974 fprintf(output,"INFO %s END\n",certid);
977 /* Note that key-not-found is not a fatal error */
978 static int
979 get_key(char *getkey)
981 LDAPMessage *res,*each;
982 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
983 struct keylist *dupelist=NULL;
984 char search[62];
985 /* This ordering is significant - specifically, "pgpcertid" needs to
986 be the second item in the list, since everything after it may be
987 discarded if the user isn't in verbose mode. */
988 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
989 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
990 "pgpkeysize","pgpkeytype",NULL};
991 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
992 array initializers. */
994 /* Build the search string */
996 /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
997 or v4 short key id */
999 if(strncmp(getkey,"0x",2)==0)
1000 getkey+=2;
1002 if(strlen(getkey)==32)
1004 fprintf(console,
1005 "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
1006 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1007 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
1008 return KEYSERVER_NOT_SUPPORTED;
1011 if(strlen(getkey)>16)
1013 char *offset=&getkey[strlen(getkey)-16];
1015 /* fingerprint. Take the last 16 characters and treat it like a
1016 long key id */
1018 if(opt->flags.include_subkeys)
1019 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1020 offset,offset);
1021 else
1022 sprintf(search,"(pgpcertid=%.16s)",offset);
1024 else if(strlen(getkey)>8)
1026 /* long key id */
1028 if(opt->flags.include_subkeys)
1029 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1030 getkey,getkey);
1031 else
1032 sprintf(search,"(pgpcertid=%.16s)",getkey);
1034 else
1036 /* short key id */
1038 sprintf(search,"(pgpkeyid=%.8s)",getkey);
1041 if(opt->verbose>2)
1042 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1044 if(!opt->verbose)
1045 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1047 err=ldap_search_s(ldap,basekeyspacedn,
1048 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1049 if(err!=0)
1051 int errtag=ldap_err_to_gpg_err(err);
1053 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1054 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1055 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1056 return errtag;
1059 count=ldap_count_entries(ldap,res);
1060 if(count<1)
1062 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1063 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1064 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1066 else
1068 /* There may be more than one unique result for a given keyID,
1069 so we should fetch them all (test this by fetching short key
1070 id 0xDEADBEEF). */
1072 each=ldap_first_entry(ldap,res);
1073 while(each!=NULL)
1075 char **vals,**certid;
1077 /* Use the long keyid to remove duplicates. The LDAP server
1078 returns the same keyid more than once if there are
1079 multiple user IDs on the key. Note that this does NOT
1080 mean that a keyid that exists multiple times on the
1081 keyserver will not be fetched. It means that each KEY,
1082 no matter how many user IDs share its keyid, will be
1083 fetched only once. If a keyid that belongs to more than
1084 one key is fetched, the server quite properly responds
1085 with all matching keys. -ds */
1087 certid=ldap_get_values(ldap,each,"pgpcertid");
1088 if(certid!=NULL)
1090 if(!key_in_keylist(certid[0],dupelist))
1092 /* it's not a duplicate, so add it */
1094 int rc=add_key_to_keylist(certid[0],&dupelist);
1095 if(rc)
1097 ret=rc;
1098 goto fail;
1101 build_info(certid[0],each);
1103 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1105 vals=ldap_get_values(ldap,each,pgpkeystr);
1106 if(vals==NULL)
1108 int errtag=ldap_to_gpg_err(ldap);
1110 fprintf(console,"gpgkeys: unable to retrieve key %s "
1111 "from keyserver\n",getkey);
1112 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1114 else
1116 print_nocr(output,vals[0]);
1117 fprintf(output,"\nKEY 0x%s END\n",getkey);
1119 ldap_value_free(vals);
1123 ldap_value_free(certid);
1126 each=ldap_next_entry(ldap,each);
1130 ret=KEYSERVER_OK;
1132 fail:
1133 ldap_msgfree(res);
1134 free_keylist(dupelist);
1136 return ret;
1139 #define LDAP_ESCAPE_CHARS "*()\\"
1141 /* Append string to buffer in a LDAP-quoted way */
1142 static void
1143 ldap_quote(char *buffer,const char *string)
1145 /* Find the end of buffer */
1146 buffer+=strlen(buffer);
1148 for(;*string;string++)
1150 if(strchr(LDAP_ESCAPE_CHARS,*string))
1152 sprintf(buffer,"\\%02X",*string);
1153 buffer+=3;
1155 else
1156 *buffer++=*string;
1159 *buffer='\0';
1162 /* Note that key-not-found is not a fatal error */
1163 static int
1164 get_name(char *getkey)
1166 LDAPMessage *res,*each;
1167 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1168 /* The maximum size of the search, including the optional stuff and
1169 the trailing \0 */
1170 char search[2+12+(MAX_LINE*3)+2+15+14+1+1+20];
1171 /* This ordering is significant - specifically, "pgpcertid" needs to
1172 be the second item in the list, since everything after it may be
1173 discarded if the user isn't in verbose mode. */
1174 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1175 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1176 "pgpkeysize","pgpkeytype",NULL};
1177 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1178 array initializers. */
1180 /* Build the search string */
1182 search[0]='\0';
1184 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1185 strcat(search,"(&");
1187 strcat(search,"(pgpUserID=*");
1188 ldap_quote(search,getkey);
1189 strcat(search,"*)");
1191 if(!opt->flags.include_disabled)
1192 strcat(search,"(pgpDisabled=0)");
1194 if(!opt->flags.include_revoked)
1195 strcat(search,"(pgpRevoked=0)");
1197 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1198 strcat(search,")");
1200 if(opt->verbose>2)
1201 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1203 if(!opt->verbose)
1204 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1206 err=ldap_search_s(ldap,basekeyspacedn,
1207 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1208 if(err!=0)
1210 int errtag=ldap_err_to_gpg_err(err);
1212 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1213 fprintf(output,"NAME %s BEGIN\n",getkey);
1214 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1215 return errtag;
1218 count=ldap_count_entries(ldap,res);
1219 if(count<1)
1221 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1222 fprintf(output,"NAME %s BEGIN\n",getkey);
1223 fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1225 else
1227 /* There may be more than one result, but we return them all. */
1229 each=ldap_first_entry(ldap,res);
1230 while(each!=NULL)
1232 char **vals,**certid;
1234 certid=ldap_get_values(ldap,each,"pgpcertid");
1235 if(certid!=NULL)
1237 build_info(certid[0],each);
1239 fprintf(output,"NAME %s BEGIN\n",getkey);
1241 vals=ldap_get_values(ldap,each,pgpkeystr);
1242 if(vals==NULL)
1244 int errtag=ldap_to_gpg_err(ldap);
1246 fprintf(console,"gpgkeys: unable to retrieve key %s "
1247 "from keyserver\n",getkey);
1248 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1250 else
1252 print_nocr(output,vals[0]);
1253 fprintf(output,"\nNAME %s END\n",getkey);
1255 ldap_value_free(vals);
1258 ldap_value_free(certid);
1261 each=ldap_next_entry(ldap,each);
1265 ret=KEYSERVER_OK;
1267 ldap_msgfree(res);
1269 return ret;
1272 static void
1273 printquoted(FILE *stream,char *string,char delim)
1275 while(*string)
1277 if(*string==delim || *string=='%')
1278 fprintf(stream,"%%%02x",*string);
1279 else
1280 fputc(*string,stream);
1282 string++;
1286 /* Returns 0 on success and -1 on error. Note that key-not-found is
1287 not an error! */
1288 static int
1289 search_key(const char *searchkey)
1291 char **vals;
1292 LDAPMessage *res,*each;
1293 int err,count=0;
1294 struct keylist *dupelist=NULL;
1295 /* The maximum size of the search, including the optional stuff and
1296 the trailing \0 */
1297 char search[2+1+9+1+3+(MAX_LINE*3)+3+1+15+14+1+1+20];
1298 char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1299 "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1300 "pgpkeysize","pgpkeytype",NULL};
1301 enum ks_search_type search_type;
1303 fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1305 search_type=classify_ks_search(&searchkey);
1307 if(opt->debug)
1308 fprintf(console,"search type is %d, and key is \"%s\"\n",
1309 search_type,searchkey);
1311 /* Build the search string */
1313 search[0]='\0';
1315 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1316 strcat(search,"(&");
1318 strcat(search,"(");
1320 switch(search_type)
1322 case KS_SEARCH_KEYID_SHORT:
1323 strcat(search,"pgpKeyID");
1324 break;
1326 case KS_SEARCH_KEYID_LONG:
1327 strcat(search,"pgpCertID");
1328 break;
1330 default:
1331 strcat(search,"pgpUserID");
1332 break;
1335 strcat(search,"=");
1337 switch(search_type)
1339 case KS_SEARCH_SUBSTR:
1340 strcat(search,"*");
1341 break;
1343 case KS_SEARCH_MAIL:
1344 strcat(search,"*<");
1345 break;
1347 case KS_SEARCH_MAILSUB:
1348 strcat(search,"*<*");
1349 break;
1351 case KS_SEARCH_EXACT:
1352 case KS_SEARCH_KEYID_LONG:
1353 case KS_SEARCH_KEYID_SHORT:
1354 break;
1357 ldap_quote(search,searchkey);
1359 switch(search_type)
1361 case KS_SEARCH_SUBSTR:
1362 strcat(search,"*");
1363 break;
1365 case KS_SEARCH_MAIL:
1366 strcat(search,">*");
1367 break;
1369 case KS_SEARCH_MAILSUB:
1370 strcat(search,"*>*");
1371 break;
1373 case KS_SEARCH_EXACT:
1374 case KS_SEARCH_KEYID_LONG:
1375 case KS_SEARCH_KEYID_SHORT:
1376 break;
1379 strcat(search,")");
1381 if(!opt->flags.include_disabled)
1382 strcat(search,"(pgpDisabled=0)");
1384 if(!opt->flags.include_revoked)
1385 strcat(search,"(pgpRevoked=0)");
1387 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1388 strcat(search,")");
1390 if(opt->verbose>2)
1391 fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1393 err=ldap_search_s(ldap,basekeyspacedn,
1394 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1395 if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1397 int errtag=ldap_err_to_gpg_err(err);
1399 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1400 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1401 return errtag;
1404 /* The LDAP server doesn't return a real count of unique keys, so we
1405 can't use ldap_count_entries here. */
1406 each=ldap_first_entry(ldap,res);
1407 while(each!=NULL)
1409 char **certid=ldap_get_values(ldap,each,"pgpcertid");
1411 if(certid!=NULL)
1413 if(!key_in_keylist(certid[0],dupelist))
1415 int rc=add_key_to_keylist(certid[0],&dupelist);
1416 if(rc!=0)
1418 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1419 free_keylist(dupelist);
1420 return rc;
1423 count++;
1427 each=ldap_next_entry(ldap,each);
1430 if(err==LDAP_SIZELIMIT_EXCEEDED)
1432 if(count==1)
1433 fprintf(console,"gpgkeys: search results exceeded server limit."
1434 " First %d result shown.\n",count);
1435 else
1436 fprintf(console,"gpgkeys: search results exceeded server limit."
1437 " First %d results shown.\n",count);
1440 free_keylist(dupelist);
1441 dupelist=NULL;
1443 if(count<1)
1444 fprintf(output,"info:1:0\n");
1445 else
1447 fprintf(output,"info:1:%d\n",count);
1449 each=ldap_first_entry(ldap,res);
1450 while(each!=NULL)
1452 char **certid;
1454 certid=ldap_get_values(ldap,each,"pgpcertid");
1455 if(certid!=NULL)
1457 LDAPMessage *uids;
1459 /* Have we seen this certid before? */
1460 if(!key_in_keylist(certid[0],dupelist))
1462 int rc=add_key_to_keylist(certid[0],&dupelist);
1463 if(rc)
1465 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1466 free_keylist(dupelist);
1467 ldap_value_free(certid);
1468 ldap_msgfree(res);
1469 return rc;
1472 fprintf(output,"pub:%s:",certid[0]);
1474 vals=ldap_get_values(ldap,each,"pgpkeytype");
1475 if(vals!=NULL)
1477 /* The LDAP server doesn't exactly handle this
1478 well. */
1479 if(strcasecmp(vals[0],"RSA")==0)
1480 fprintf(output,"1");
1481 else if(strcasecmp(vals[0],"DSS/DH")==0)
1482 fprintf(output,"17");
1483 ldap_value_free(vals);
1486 fputc(':',output);
1488 vals=ldap_get_values(ldap,each,"pgpkeysize");
1489 if(vals!=NULL)
1491 /* Not sure why, but some keys are listed with a
1492 key size of 0. Treat that like an
1493 unknown. */
1494 if(atoi(vals[0])>0)
1495 fprintf(output,"%d",atoi(vals[0]));
1496 ldap_value_free(vals);
1499 fputc(':',output);
1501 /* YYYYMMDDHHmmssZ */
1503 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1504 if(vals!=NULL && strlen(vals[0])==15)
1506 fprintf(output,"%u",
1507 (unsigned int)ldap2epochtime(vals[0]));
1508 ldap_value_free(vals);
1511 fputc(':',output);
1513 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1514 if(vals!=NULL && strlen(vals[0])==15)
1516 fprintf(output,"%u",
1517 (unsigned int)ldap2epochtime(vals[0]));
1518 ldap_value_free(vals);
1521 fputc(':',output);
1523 vals=ldap_get_values(ldap,each,"pgprevoked");
1524 if(vals!=NULL)
1526 if(atoi(vals[0])==1)
1527 fprintf(output,"r");
1528 ldap_value_free(vals);
1531 vals=ldap_get_values(ldap,each,"pgpdisabled");
1532 if(vals!=NULL)
1534 if(atoi(vals[0])==1)
1535 fprintf(output,"d");
1536 ldap_value_free(vals);
1539 #if 0
1540 /* This is not yet specified in the keyserver
1541 protocol, but may be someday. */
1542 fputc(':',output);
1544 vals=ldap_get_values(ldap,each,"modifytimestamp");
1545 if(vals!=NULL && strlen(vals[0])==15)
1547 fprintf(output,"%u",
1548 (unsigned int)ldap2epochtime(vals[0]));
1549 ldap_value_free(vals);
1551 #endif
1553 fprintf(output,"\n");
1555 /* Now print all the uids that have this certid */
1556 uids=ldap_first_entry(ldap,res);
1557 while(uids!=NULL)
1559 vals=ldap_get_values(ldap,uids,"pgpcertid");
1560 if(vals!=NULL)
1562 if(strcasecmp(certid[0],vals[0])==0)
1564 char **uidvals;
1566 fprintf(output,"uid:");
1568 uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1569 if(uidvals!=NULL)
1571 /* Need to escape any colons */
1572 printquoted(output,uidvals[0],':');
1573 ldap_value_free(uidvals);
1576 fprintf(output,"\n");
1579 ldap_value_free(vals);
1582 uids=ldap_next_entry(ldap,uids);
1586 ldap_value_free(certid);
1589 each=ldap_next_entry(ldap,each);
1593 ldap_msgfree(res);
1594 free_keylist(dupelist);
1596 fprintf(output,"SEARCH %s END\n",searchkey);
1598 return KEYSERVER_OK;
1601 static void
1602 fail_all(struct keylist *keylist,int err)
1604 if(!keylist)
1605 return;
1607 if(opt->action==KS_SEARCH)
1609 fprintf(output,"SEARCH ");
1610 while(keylist)
1612 fprintf(output,"%s ",keylist->str);
1613 keylist=keylist->next;
1615 fprintf(output,"FAILED %d\n",err);
1617 else
1618 while(keylist)
1620 fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1621 keylist=keylist->next;
1625 static int
1626 find_basekeyspacedn(void)
1628 int err,i;
1629 char *attr[]={"namingContexts",NULL,NULL,NULL};
1630 LDAPMessage *res;
1631 char **context;
1633 /* Look for namingContexts */
1634 err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1635 if(err==LDAP_SUCCESS)
1637 context=ldap_get_values(ldap,res,"namingContexts");
1638 if(context)
1640 attr[0]="pgpBaseKeySpaceDN";
1641 attr[1]="pgpVersion";
1642 attr[2]="pgpSoftware";
1644 real_ldap=1;
1646 /* We found some, so try each namingContext as the search base
1647 and look for pgpBaseKeySpaceDN. Because we found this, we
1648 know we're talking to a regular-ish LDAP server and not a
1649 LDAP keyserver. */
1651 for(i=0;context[i] && !basekeyspacedn;i++)
1653 char **vals;
1654 LDAPMessage *si_res;
1655 char *object;
1657 object=malloc(17+strlen(context[i])+1);
1658 if(!object)
1659 return -1;
1661 strcpy(object,"cn=pgpServerInfo,");
1662 strcat(object,context[i]);
1664 err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1665 "(objectClass=*)",attr,0,&si_res);
1666 free(object);
1668 if(err==LDAP_NO_SUCH_OBJECT)
1669 continue;
1670 else if(err!=LDAP_SUCCESS)
1671 return err;
1673 vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1674 if(vals)
1676 basekeyspacedn=strdup(vals[0]);
1677 ldap_value_free(vals);
1680 if(opt->verbose>1)
1682 vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1683 if(vals)
1685 fprintf(console,"Server: \t%s\n",vals[0]);
1686 ldap_value_free(vals);
1689 vals=ldap_get_values(ldap,si_res,"pgpVersion");
1690 if(vals)
1692 fprintf(console,"Version:\t%s\n",vals[0]);
1693 ldap_value_free(vals);
1697 ldap_msgfree(si_res);
1700 ldap_value_free(context);
1703 ldap_msgfree(res);
1705 else
1707 /* We don't have an answer yet, which means the server might be
1708 a LDAP keyserver. */
1709 char **vals;
1710 LDAPMessage *si_res;
1712 attr[0]="pgpBaseKeySpaceDN";
1713 attr[1]="version";
1714 attr[2]="software";
1716 err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1717 "(objectClass=*)",attr,0,&si_res);
1718 if(err!=LDAP_SUCCESS)
1719 return err;
1721 /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1722 KEYSPACE,C=US", but it might not be in the future. */
1724 vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1725 if(vals)
1727 basekeyspacedn=strdup(vals[0]);
1728 ldap_value_free(vals);
1731 if(opt->verbose>1)
1733 vals=ldap_get_values(ldap,si_res,"software");
1734 if(vals)
1736 fprintf(console,"Server: \t%s\n",vals[0]);
1737 ldap_value_free(vals);
1741 vals=ldap_get_values(ldap,si_res,"version");
1742 if(vals)
1744 if(opt->verbose>1)
1745 fprintf(console,"Version:\t%s\n",vals[0]);
1747 /* If the version is high enough, use the new pgpKeyV2
1748 attribute. This design if iffy at best, but it matches how
1749 PGP does it. I figure the NAI folks assumed that there would
1750 never be a LDAP keyserver vendor with a different numbering
1751 scheme. */
1752 if(atoi(vals[0])>1)
1753 pgpkeystr="pgpKeyV2";
1755 ldap_value_free(vals);
1758 ldap_msgfree(si_res);
1761 return LDAP_SUCCESS;
1764 static void
1765 show_help (FILE *fp)
1767 fprintf (fp,"-h\thelp\n");
1768 fprintf (fp,"-V\tversion\n");
1769 fprintf (fp,"-o\toutput to this file\n");
1773 main(int argc,char *argv[])
1775 int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1776 char line[MAX_LINE],*binddn=NULL,*bindpw=NULL;
1777 int failed=0,use_ssl=0,use_tls=0,bound=0;
1778 struct keylist *keylist=NULL,*keyptr=NULL;
1780 console=stderr;
1782 /* Kludge to implement standard GNU options. */
1783 if (argc > 1 && !strcmp (argv[1], "--version"))
1785 fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1786 return 0;
1788 else if (argc > 1 && !strcmp (argv[1], "--help"))
1790 show_help (stdout);
1791 return 0;
1794 while((arg=getopt(argc,argv,"hVo:"))!=-1)
1795 switch(arg)
1797 default:
1798 case 'h':
1799 show_help (console);
1800 return KEYSERVER_OK;
1802 case 'V':
1803 fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1804 return KEYSERVER_OK;
1806 case 'o':
1807 output=fopen(optarg,"w");
1808 if(output==NULL)
1810 fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1811 optarg,strerror(errno));
1812 return KEYSERVER_INTERNAL_ERROR;
1815 break;
1818 if(argc>optind)
1820 input=fopen(argv[optind],"r");
1821 if(input==NULL)
1823 fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1824 argv[optind],strerror(errno));
1825 return KEYSERVER_INTERNAL_ERROR;
1829 if(input==NULL)
1830 input=stdin;
1832 if(output==NULL)
1833 output=stdout;
1835 opt=init_ks_options();
1836 if(!opt)
1837 return KEYSERVER_NO_MEMORY;
1839 /* Get the command and info block */
1841 while(fgets(line,MAX_LINE,input)!=NULL)
1843 char optionstr[MAX_OPTION+1];
1845 if(line[0]=='\n')
1846 break;
1848 err=parse_ks_options(line,opt);
1849 if(err>0)
1851 ret=err;
1852 goto fail;
1854 else if(err==0)
1855 continue;
1857 if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1859 int no=0;
1860 char *start=&optionstr[0];
1862 optionstr[MAX_OPTION]='\0';
1864 if(strncasecmp(optionstr,"no-",3)==0)
1866 no=1;
1867 start=&optionstr[3];
1870 if(strncasecmp(start,"tls",3)==0)
1872 if(no)
1873 use_tls=0;
1874 else if(start[3]=='=')
1876 if(strcasecmp(&start[4],"no")==0)
1877 use_tls=0;
1878 else if(strcasecmp(&start[4],"try")==0)
1879 use_tls=1;
1880 else if(strcasecmp(&start[4],"warn")==0)
1881 use_tls=2;
1882 else if(strcasecmp(&start[4],"require")==0)
1883 use_tls=3;
1884 else
1885 use_tls=1;
1887 else if(start[3]=='\0')
1888 use_tls=1;
1890 else if(strncasecmp(start,"basedn",6)==0)
1892 if(no)
1894 free(basekeyspacedn);
1895 basekeyspacedn=NULL;
1897 else if(start[6]=='=')
1899 free(basekeyspacedn);
1900 basekeyspacedn=strdup(&start[7]);
1901 if(!basekeyspacedn)
1903 fprintf(console,"gpgkeys: out of memory while creating "
1904 "base DN\n");
1905 ret=KEYSERVER_NO_MEMORY;
1906 goto fail;
1909 real_ldap=1;
1912 else if(strncasecmp(start,"binddn",6)==0)
1914 if(no)
1916 free(binddn);
1917 binddn=NULL;
1919 else if(start[6]=='=')
1921 free(binddn);
1922 binddn=strdup(&start[7]);
1923 if(!binddn)
1925 fprintf(console,"gpgkeys: out of memory while creating "
1926 "bind DN\n");
1927 ret=KEYSERVER_NO_MEMORY;
1928 goto fail;
1931 real_ldap=1;
1934 else if(strncasecmp(start,"bindpw",6)==0)
1936 if(no)
1938 free(bindpw);
1939 bindpw=NULL;
1941 else if(start[6]=='=')
1943 free(bindpw);
1944 bindpw=strdup(&start[7]);
1945 if(!bindpw)
1947 fprintf(console,"gpgkeys: out of memory while creating "
1948 "bind password\n");
1949 ret=KEYSERVER_NO_MEMORY;
1950 goto fail;
1953 real_ldap=1;
1957 continue;
1961 if(!opt->scheme)
1963 fprintf(console,"gpgkeys: no scheme supplied!\n");
1964 ret=KEYSERVER_SCHEME_NOT_FOUND;
1965 goto fail;
1968 if(strcasecmp(opt->scheme,"ldaps")==0)
1970 port=636;
1971 use_ssl=1;
1974 if(opt->port)
1975 port=atoi(opt->port);
1977 if(!opt->host)
1979 fprintf(console,"gpgkeys: no keyserver host provided\n");
1980 goto fail;
1983 if(opt->timeout && register_timeout()==-1)
1985 fprintf(console,"gpgkeys: unable to register timeout handler\n");
1986 return KEYSERVER_INTERNAL_ERROR;
1989 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
1991 if(opt->ca_cert_file)
1993 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
1994 if(err!=LDAP_SUCCESS)
1996 fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
1997 ldap_err2string(err));
1998 ret=KEYSERVER_INTERNAL_ERROR;
1999 goto fail;
2002 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
2004 /* SSL trumps TLS */
2005 if(use_ssl)
2006 use_tls=0;
2008 /* If it's a GET or a SEARCH, the next thing to come in is the
2009 keyids. If it's a SEND, then there are no keyids. */
2011 if(opt->action==KS_SEND)
2012 while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
2013 else if(opt->action==KS_GET
2014 || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
2016 for(;;)
2018 struct keylist *work;
2020 if(fgets(line,MAX_LINE,input)==NULL)
2021 break;
2022 else
2024 if(line[0]=='\n' || line[0]=='\0')
2025 break;
2027 work=malloc(sizeof(struct keylist));
2028 if(work==NULL)
2030 fprintf(console,"gpgkeys: out of memory while "
2031 "building key list\n");
2032 ret=KEYSERVER_NO_MEMORY;
2033 goto fail;
2036 strcpy(work->str,line);
2038 /* Trim the trailing \n */
2039 work->str[strlen(line)-1]='\0';
2041 work->next=NULL;
2043 /* Always attach at the end to keep the list in proper
2044 order for searching */
2045 if(keylist==NULL)
2046 keylist=work;
2047 else
2048 keyptr->next=work;
2050 keyptr=work;
2054 else
2056 fprintf(console,"gpgkeys: no keyserver command specified\n");
2057 goto fail;
2060 /* Send the response */
2062 fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
2063 fprintf(output,"PROGRAM %s\n\n",VERSION);
2065 if(opt->verbose>1)
2067 fprintf(console,"Host:\t\t%s\n",opt->host);
2068 if(port)
2069 fprintf(console,"Port:\t\t%d\n",port);
2070 fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
2073 if(opt->debug)
2075 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
2076 err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
2077 if(err!=LDAP_SUCCESS)
2078 fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
2079 ldap_err2string(err));
2080 else
2081 fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
2082 #else
2083 fprintf(console,"gpgkeys: not built with debugging support\n");
2084 #endif
2087 /* We have a timeout set for the setup stuff since it could time out
2088 as well. */
2089 set_timeout(opt->timeout);
2091 /* Note that this tries all A records on a given host (or at least,
2092 OpenLDAP does). */
2093 ldap=ldap_init(opt->host,port);
2094 if(ldap==NULL)
2096 fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
2097 strerror(errno));
2098 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2099 goto fail;
2102 if(use_ssl)
2104 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2105 int ssl=LDAP_OPT_X_TLS_HARD;
2107 err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2108 if(err!=LDAP_SUCCESS)
2110 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2111 ldap_err2string(err));
2112 fail_all(keylist,ldap_err_to_gpg_err(err));
2113 goto fail;
2116 if(!opt->flags.check_cert)
2117 ssl=LDAP_OPT_X_TLS_NEVER;
2119 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2120 if(err!=LDAP_SUCCESS)
2122 fprintf(console,
2123 "gpgkeys: unable to set certificate validation: %s\n",
2124 ldap_err2string(err));
2125 fail_all(keylist,ldap_err_to_gpg_err(err));
2126 goto fail;
2128 #else
2129 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2130 "not built with LDAPS support");
2131 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2132 goto fail;
2133 #endif
2136 if(!basekeyspacedn)
2137 if((err=find_basekeyspacedn()) || !basekeyspacedn)
2139 fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2140 err?ldap_err2string(err):"not found");
2141 fail_all(keylist,ldap_err_to_gpg_err(err));
2142 goto fail;
2145 /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2146 3=force use. */
2147 if(use_tls)
2149 if(!real_ldap)
2151 if(use_tls>=2)
2152 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2153 "not supported by the NAI LDAP keyserver");
2154 if(use_tls==3)
2156 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2157 goto fail;
2160 else
2162 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2163 int ver=LDAP_VERSION3;
2165 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2167 #ifdef LDAP_OPT_X_TLS
2168 if(err==LDAP_SUCCESS)
2170 if(opt->flags.check_cert)
2171 ver=LDAP_OPT_X_TLS_HARD;
2172 else
2173 ver=LDAP_OPT_X_TLS_NEVER;
2175 err=ldap_set_option(ldap,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2177 #endif
2179 if(err==LDAP_SUCCESS)
2180 err=ldap_start_tls_s(ldap,NULL,NULL);
2182 if(err!=LDAP_SUCCESS)
2184 if(use_tls>=2 || opt->verbose>2)
2185 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2186 ldap_err2string(err));
2187 /* Are we forcing it? */
2188 if(use_tls==3)
2190 fail_all(keylist,ldap_err_to_gpg_err(err));
2191 goto fail;
2194 else if(opt->verbose>1)
2195 fprintf(console,"gpgkeys: TLS started successfully.\n");
2196 #else
2197 if(use_tls>=2)
2198 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2199 "not built with TLS support");
2200 if(use_tls==3)
2202 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2203 goto fail;
2205 #endif
2209 /* By default we don't bind as there is usually no need to. For
2210 cases where the server needs some authentication, the user can
2211 use binddn and bindpw for auth. */
2213 if(binddn)
2215 #ifdef HAVE_LDAP_SET_OPTION
2216 int ver=LDAP_VERSION3;
2218 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2219 if(err!=LDAP_SUCCESS)
2221 fprintf(console,"gpgkeys: unable to go to LDAP 3: %s\n",
2222 ldap_err2string(err));
2223 fail_all(keylist,ldap_err_to_gpg_err(err));
2224 goto fail;
2226 #endif
2228 if(opt->verbose>2)
2229 fprintf(console,"gpgkeys: LDAP bind to %s, pw %s\n",binddn,
2230 bindpw?">not shown<":">none<");
2231 err=ldap_simple_bind_s(ldap,binddn,bindpw);
2232 if(err!=LDAP_SUCCESS)
2234 fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2235 ldap_err2string(err));
2236 fail_all(keylist,ldap_err_to_gpg_err(err));
2237 goto fail;
2239 else
2240 bound=1;
2243 if(opt->action==KS_GET)
2245 keyptr=keylist;
2247 while(keyptr!=NULL)
2249 set_timeout(opt->timeout);
2251 if(get_key(keyptr->str)!=KEYSERVER_OK)
2252 failed++;
2254 keyptr=keyptr->next;
2257 else if(opt->action==KS_GETNAME)
2259 keyptr=keylist;
2261 while(keyptr!=NULL)
2263 set_timeout(opt->timeout);
2265 if(get_name(keyptr->str)!=KEYSERVER_OK)
2266 failed++;
2268 keyptr=keyptr->next;
2271 else if(opt->action==KS_SEND)
2273 int eof_seen = 0;
2277 set_timeout(opt->timeout);
2279 if(real_ldap)
2281 if (send_key(&eof_seen) != KEYSERVER_OK)
2282 failed++;
2284 else
2286 if (send_key_keyserver(&eof_seen) != KEYSERVER_OK)
2287 failed++;
2290 while (!eof_seen);
2292 else if(opt->action==KS_SEARCH)
2294 char *searchkey=NULL;
2295 int len=0;
2297 set_timeout(opt->timeout);
2299 /* To search, we stick a * in between each key to search for.
2300 This means that if the user enters words, they'll get
2301 "enters*words". If the user "enters words", they'll get
2302 "enters words" */
2304 keyptr=keylist;
2305 while(keyptr!=NULL)
2307 len+=strlen(keyptr->str)+1;
2308 keyptr=keyptr->next;
2311 searchkey=malloc(len+1);
2312 if(searchkey==NULL)
2314 ret=KEYSERVER_NO_MEMORY;
2315 fail_all(keylist,KEYSERVER_NO_MEMORY);
2316 goto fail;
2319 searchkey[0]='\0';
2321 keyptr=keylist;
2322 while(keyptr!=NULL)
2324 strcat(searchkey,keyptr->str);
2325 strcat(searchkey,"*");
2326 keyptr=keyptr->next;
2329 /* Nail that last "*" */
2330 if(*searchkey)
2331 searchkey[strlen(searchkey)-1]='\0';
2333 if(search_key(searchkey)!=KEYSERVER_OK)
2334 failed++;
2336 free(searchkey);
2338 else
2339 assert (!"bad action");
2341 if(!failed)
2342 ret=KEYSERVER_OK;
2344 fail:
2346 while(keylist!=NULL)
2348 struct keylist *current=keylist;
2349 keylist=keylist->next;
2350 free(current);
2353 if(input!=stdin)
2354 fclose(input);
2356 if(output!=stdout)
2357 fclose(output);
2359 free_ks_options(opt);
2361 if(ldap!=NULL && bound)
2362 ldap_unbind_s(ldap);
2364 free(basekeyspacedn);
2366 return ret;