]> git.sur5r.net Git - openldap/blob - clients/tools/ldappasswd.c
Add support for -P protocol_version.
[openldap] / clients / tools / ldappasswd.c
1 /*
2  *      Copyright 1998, David E. Storey, All rights reserved.
3  *      This software is not subject to any license of The Murphy Group, Inc.
4  *      or George Mason University.
5  *
6  *      Redistribution and use in source and binary forms are permitted only
7  *      as authorized by the OpenLDAP Public License.  A copy of this
8  *      license is available at http://www.OpenLDAP.org/license.html or
9  *      in file LICENSE in the top-level directory of the distribution.
10  *
11  *      ldappasswd.c - program to modify passwords in an LDAP tree
12  *
13  *      Author: David E. Storey <dave@tamos.net>
14  */
15
16 #include "portable.h"
17
18 #include <ctype.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <sys/time.h>
22
23 #include <ac/string.h>
24 #include <ac/unistd.h>
25
26 #include <lber.h>
27 #include <ldap.h>
28 #include <lutil.h>
29 #include <lutil_md5.h>
30 #include <lutil_sha1.h>
31
32 #include "ldapconfig.h"
33
34 /* local macros */
35 #define CEILING(x)      ((double)x > (int)x ? (int)x + 1 : (int)x)
36 #define STRDUP(x)       (x ? strcpy(malloc(strlen(x) + 1), x) : NULL)
37
38 #define LDAP_PASSWD_ATTRIB "userPassword"
39 #define LDAP_PASSWD_CONF   DEFAULT_SYSCONFDIR"/passwd.conf"
40
41 #define HS_NONE  0
42 #define HS_PLAIN 1
43 #define HS_CONV  2
44
45 typedef enum
46 {
47         HASHTYPE_NONE,
48         HASHTYPE_CRYPT,
49         HASHTYPE_MD5,
50         HASHTYPE_SMD5,
51         HASHTYPE_SHA1,
52         HASHTYPE_SSHA1
53 }
54 HashTypes;
55
56 typedef struct salt_t
57 {
58         unsigned char  *salt;
59         unsigned int    len;
60 }
61 Salt;
62
63 typedef struct hash_t
64 {
65         char           *name;
66         unsigned int    namesz;
67         char           *(*func) (const char *, Salt *);
68         unsigned char   takes_salt;
69         HashTypes       type;
70         HashTypes       type_salted;
71         unsigned int    default_salt_len;
72 }
73 Hash;
74
75 static int      noupdates = 0;
76 static int      verbose = 0;
77 static int      want_entryhash = 0;
78 static int      auto_gen_pw = 0;
79
80 /*** functions ***/
81
82 /*
83  * pw_encode() essentially base64 encodes a password and it's salt
84  */
85
86 char *
87 pw_encode (unsigned char *passwd, Salt * salt, unsigned int len)
88 {
89         int             salted = salt && salt->salt && salt->len;
90         int             b64_len = 0;
91         char           *base64digest = NULL;
92         unsigned char  *npasswd = passwd;
93
94         if (salted)
95         {
96                 npasswd = (unsigned char *)malloc (len + salt->len);
97                 memcpy (npasswd, passwd, len);
98                 memcpy (&npasswd[len], salt->salt, salt->len);
99                 len += salt->len;
100         }
101
102         b64_len = CEILING (len / 3) * 4 + 1;
103         base64digest = (char *)malloc (b64_len);
104         if (lutil_b64_ntop (npasswd, len, base64digest, b64_len) < 0)
105         {
106                 free (base64digest);
107                 base64digest = NULL;
108         }
109
110         if (salted)
111                 free (npasswd);
112
113         return (base64digest);
114 }
115
116 /*
117  * if you'd like to write a better salt generator, please, be my guest.
118  */
119
120 void
121 make_salt (Salt * salt, unsigned int len)
122 {
123         struct timeval  tv;
124
125         if (!salt)
126                 return;
127
128         /* seed random number generator */
129         gettimeofday (&tv, NULL);
130         srand (tv.tv_usec);
131
132         salt->len = len;
133         salt->salt = (unsigned char *)malloc (len);
134
135         for (len = 0; len < salt->len; len++)
136                 salt->salt[len] = (tv.tv_usec ^ rand ()) & 0xff;
137 }
138
139 /*
140  * password generator
141  */
142
143 char *
144 gen_pass (unsigned int len)
145 {
146         const unsigned char autogen[] =
147                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.,";
148         int             i;
149         Salt            salt = {NULL, 0};
150
151         make_salt (&salt, len);
152         for (i = 0; i < len; i++)
153                 salt.salt[i] = autogen[salt.salt[i] % (sizeof (autogen) - 1)];
154
155         return ((char *)salt.salt);
156 }
157
158 char *
159 hash_none (const char *pw_in, Salt * salt)
160 {
161         return (STRDUP (pw_in));
162 }
163
164 char *
165 hash_crypt (const char *pw_in, Salt * salt)
166 {
167         const unsigned char crypt64[] =
168                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890./";
169         char   *crypted_pw = NULL;
170         Salt    lsalt;
171
172         if (salt && salt->salt && strlen ((char *)salt->salt) >= 2)
173         {
174                 /* sanity check */
175                 if (!(isalnum(salt->salt[0]) || salt->salt[0] == '.' || salt->salt[0] == '/'))
176                         salt->salt[0] = crypt64[salt->salt[0] % (sizeof (crypt64) - 1)];
177                 if (!(isalnum(salt->salt[1]) || salt->salt[1] == '.' || salt->salt[1] == '/'))
178                         salt->salt[1] = crypt64[salt->salt[1] % (sizeof (crypt64) - 1)];
179
180                 crypted_pw = crypt (pw_in, (char *)salt->salt);
181         }
182         else
183         {
184                 make_salt (&lsalt, 2);
185                 lsalt.salt[0] = crypt64[lsalt.salt[0] % (sizeof (crypt64) - 1)];
186                 lsalt.salt[1] = crypt64[lsalt.salt[1] % (sizeof (crypt64) - 1)];
187                 crypted_pw = crypt (pw_in, (char *)lsalt.salt);
188                 free (lsalt.salt);
189         }
190         return (STRDUP (crypted_pw));
191 }
192
193 char *
194 hash_md5 (const char *pw_in, Salt * salt)
195 {
196         lutil_MD5_CTX   MD5context;
197         unsigned char   MD5digest[16];
198
199         lutil_MD5Init (&MD5context);
200         lutil_MD5Update (&MD5context, pw_in, strlen(pw_in));
201         if (salt && salt->salt && salt->len)
202                 lutil_MD5Update (&MD5context, salt->salt, salt->len);
203         lutil_MD5Final (MD5digest, &MD5context);
204
205         return (pw_encode (MD5digest, salt, sizeof (MD5digest)));
206 }
207
208 char *
209 hash_sha1 (const char *pw_in, Salt * salt)
210 {
211         lutil_SHA1_CTX  SHA1context;
212         unsigned char   SHA1digest[20];
213
214         lutil_SHA1Init (&SHA1context);
215         lutil_SHA1Update (&SHA1context, pw_in, strlen(pw_in));
216         if (salt && salt->salt && salt->len)
217                 lutil_SHA1Update (&SHA1context, salt->salt, salt->len);
218         lutil_SHA1Final (SHA1digest, &SHA1context);
219
220         return (pw_encode (SHA1digest, salt, sizeof (SHA1digest)));
221 }
222
223 static Hash hashes[] =
224 {
225         {"none",  4, hash_none,  0, HASHTYPE_NONE,  HASHTYPE_NONE,  0},
226         {"crypt", 5, hash_crypt, 1, HASHTYPE_CRYPT, HASHTYPE_CRYPT, 2},
227         {"md5",   3, hash_md5,   0, HASHTYPE_MD5,   HASHTYPE_SMD5,  0},
228         {"smd5",  4, hash_md5,   1, HASHTYPE_SMD5,  HASHTYPE_SMD5,  4},
229         {"sha",   3, hash_sha1,  0, HASHTYPE_SHA1,  HASHTYPE_SSHA1, 0},
230         {"ssha",  4, hash_sha1,  1, HASHTYPE_SSHA1, HASHTYPE_SSHA1, 4},
231         {NULL,    0, NULL,       0, HASHTYPE_NONE,  HASHTYPE_NONE,  0}
232 };
233
234 int
235 modify_dn (LDAP * ld, char *targetdn, char *pwattr, char *oldpw,
236            char *newpw, HashTypes htype, Salt * salt)
237 {
238         int             ret = 0;
239         int             salted = salt->salt ? 1 : 0;
240         int             want_salt = salt->len && !salted;
241         char           *buf = NULL;
242         char           *hashed_pw = NULL;
243         char           *strvals[2];
244         LDAPMod         mod, *mods[2];
245
246         if (!ld || !targetdn || !newpw)
247                 return (1);
248
249         /* auto-generate password */
250         if (auto_gen_pw)
251                 newpw = gen_pass (auto_gen_pw);
252
253         /* handle salt */
254         if (want_salt)
255         {
256                 make_salt (salt, salt->len);
257                 htype = hashes[htype].type_salted;
258         }
259         else if (hashes[htype].default_salt_len)
260         {
261                 /* user chose a salted hash and needs a salt */
262                 if (!salted)
263                 {
264                         want_salt++;
265                         salt->len = hashes[htype].default_salt_len;
266                         make_salt (salt, salt->len);
267                 }
268         }
269
270         /* hash password */
271         hashed_pw = hashes[htype].func (newpw, salt->len ? salt : NULL);
272
273         /* return salt back to it's original state */
274         if (want_salt)
275         {
276                 free (salt->salt);
277                 salt->salt = NULL;
278         }
279
280         buf = (char *)malloc (hashes[htype].namesz + 3 + strlen (hashed_pw));
281         if (htype)
282                 sprintf (buf, "{%s}%s", hashes[htype].name, hashed_pw);
283         else
284                 sprintf (buf, "%s", hashed_pw);
285
286         if (verbose > 0)
287         {
288                 printf ("%s", targetdn);
289                 if (verbose > 1)
290                 {
291                         printf (":%s", buf);
292                         if (verbose > 2)
293                                 printf (":%s", newpw);
294                 }
295                 printf ("\n");
296         }
297
298         strvals[0] = buf;
299         strvals[1] = NULL;
300         mod.mod_vals.modv_strvals = strvals;
301         mod.mod_type = pwattr;
302         mod.mod_op = LDAP_MOD_REPLACE;
303         mods[0] = &mod;
304         mods[1] =NULL;
305
306         if (!noupdates && (ret = ldap_modify_s (ld, targetdn, mods)) != LDAP_SUCCESS)
307                 ldap_perror (ld, "ldap_modify_s");
308
309         free (hashed_pw);
310         free (buf);
311         return (ret);
312 }
313
314 void
315 usage (char *s)
316 {
317         fprintf (stderr, "Usage: %s [options] [filter]\n", s);
318         fprintf (stderr, "  -a attrib\tpassword attribute (default: %s)\n", LDAP_PASSWD_ATTRIB);
319         fprintf (stderr, "  -b basedn\tbasedn to perform searches\n");
320 /*      fprintf (stderr, "  -C\t\tuse entry's current hash mechanism\n"); */
321         fprintf (stderr, "  -D binddn\tbind dn\n");
322         fprintf (stderr, "  -d level\tdebugging level\n");
323         fprintf (stderr, "  -E\t\tprompt for new password\n");
324         fprintf (stderr, "  -e passwd\tnew password\n");
325         fprintf (stderr, "  -g passlen\tauto-generate passwords with length pwlen\n");
326         fprintf (stderr, "  -H hash\thash type (default: crypt)\n");
327         fprintf (stderr, "  -h host\tldap server (default: localhost)\n");
328 #ifdef HAVE_KERBEROS
329         fprintf (stderr, "  -K\t\tuse Kerberos step 1\n");
330         fprintf (stderr, "  -k\t\tuse Kerberos\n");
331 #endif
332         fprintf (stderr, "  -l time\ttime limit\n");
333         fprintf (stderr, "  -n\t\tmake no modifications\n");
334         fprintf (stderr, "  -P version\tprotocol version (2 or 3)\n");
335         fprintf (stderr, "  -p port\tldap port\n");
336         fprintf (stderr, "  -s scope\tsearch scope: base, one, sub (default: sub)\n");
337         fprintf (stderr, "  -t targetdn\tdn to change password\n");
338         fprintf (stderr, "  -v\t\tverbose (more v's, more verbose)\n");
339         fprintf (stderr, "  -W\t\tprompt for bind password\n");
340         fprintf (stderr, "  -w passwd\tbind password (for simple authentication)\n");
341         fprintf (stderr, "  -Y saltlen\tsalt length to use\n");
342 /*      fprintf (stderr, "  -y salt\tsalt to use\n"); */
343         fprintf (stderr, "  -z size\tsize limit\n");
344         exit (1);
345 }
346
347 int
348 main (int argc, char *argv[])
349 {
350         char           *base = NULL;
351         char           *binddn = NULL;
352         char           *bindpw = NULL;
353         char           *filtpattern = NULL;
354         char           *ldaphost = NULL;
355         char           *targetdn = NULL;
356         char           *pwattr = LDAP_PASSWD_ATTRIB;
357         char           *newpw = NULL;
358         int             authmethod = LDAP_AUTH_SIMPLE;
359         int             hashtype = HASHTYPE_CRYPT;
360         int             i, j;
361         int             ldapport = 0;
362         int             debug = 0;
363         int             scope = LDAP_SCOPE_SUBTREE;
364         int             sizelimit = LDAP_NO_LIMIT;
365         int             timelimit = LDAP_NO_LIMIT;
366         int             version = LDAP_VERSION2;
367         int             want_bindpw = 0;
368         int             want_newpw = 0;
369         LDAP           *ld;
370         Salt            salt;
371
372         salt.salt = NULL;
373         salt.len = 0;
374
375         if (argc == 1)
376                 usage (argv[0]);
377
378         while ((i = getopt (argc, argv, "a:b:C:D:d:Ee:g:H:h:Kkl:nP:p:s:t:vWw:Y:y:z:")) != EOF)
379         {
380                 switch (i)
381                 {
382                 case 'a':       /* password attribute */
383                         pwattr = STRDUP (optarg);
384                         break;
385
386                 case 'b':       /* base search dn */
387                         base = STRDUP (optarg);
388                         break;
389
390                 case 'C':
391                         want_entryhash++;
392                         break;
393
394                 case 'D':       /* bind distinguished name */
395                         binddn = STRDUP (optarg);
396                         break;
397
398                 case 'd':       /* debugging option */
399                         debug |= atoi (optarg);
400                         break;
401
402                 case 'E':       /* prompt for new password */
403                         want_newpw++;
404                         break;
405
406                 case 'e':       /* new password */
407                         newpw = STRDUP (optarg);
408                         break;
409
410                 case 'g':
411                         auto_gen_pw = strtol (optarg, NULL, 10);
412                         break;
413
414                 case 'H':       /* hashes */
415                         for (j = 0; hashes[j].name; j++)
416                         {
417                                 if (!strncasecmp (optarg, hashes[j].name, hashes[j].namesz))
418                                 {
419                                         hashtype = hashes[j].type;
420                                         break;
421                                 }
422                         }
423
424                         if (!hashes[j].name)
425                         {
426                                 fprintf (stderr, "hash type: %s is unknown\n", optarg);
427                                 usage (argv[0]);
428                         }
429                         break;
430
431                 case 'h':       /* ldap host */
432                         ldaphost = STRDUP (optarg);
433                         break;
434
435                 case 'K':       /* use kerberos bind, 1st part only */
436 #ifdef HAVE_KERBEROS
437                         authmethod = LDAP_AUTH_KRBV41;
438 #else
439                         fprintf (stderr, "%s was not compiled with Kerberos support\n", argv[0]);
440 #endif
441                         break;
442
443                 case 'k':       /* use kerberos bind */
444 #ifdef HAVE_KERBEROS
445                         authmethod = LDAP_AUTH_KRBV4;
446 #else
447                         fprintf (stderr, "%s was not compiled with Kerberos support\n", argv[0]);
448 #endif
449                         break;
450
451                 case 'l':       /* time limit */
452                         timelimit = strtol (optarg, NULL, 10);
453                         break;
454
455                 case 'n':       /* don't update entry(s) */
456                         noupdates++;
457                         break;
458
459                 case 'P':
460                         switch(optarg[0])
461                         {
462                         case '2':
463                                 version = LDAP_VERSION2;
464                                 break;
465                         case '3':
466                                 version = LDAP_VERSION3;
467                                 break;
468                         }
469                         break;
470
471                 case 'p':       /* ldap port */
472                         ldapport = strtol (optarg, NULL, 10);
473                         break;
474
475                 case 's':       /* scope */
476                         if (strncasecmp (optarg, "base", 4) == 0)
477                                 scope = LDAP_SCOPE_BASE;
478                         else if (strncasecmp (optarg, "one", 3) == 0)
479                                 scope = LDAP_SCOPE_ONELEVEL;
480                         else if (strncasecmp (optarg, "sub", 3) == 0)
481                                 scope = LDAP_SCOPE_SUBTREE;
482                         else
483                         {
484                                 fprintf (stderr, "scope should be base, one, or sub\n");
485                                 usage (argv[0]);
486                         }
487                         break;
488
489                 case 't':       /* target dn */
490                         targetdn = STRDUP (optarg);
491                         break;
492
493                 case 'v':       /* verbose */
494                         verbose++;
495                         break;
496
497                 case 'W':       /* promt for bind password */
498                         want_bindpw++;
499                         break;
500
501                 case 'w':       /* bind password */
502                         bindpw = STRDUP (optarg);
503                         break;
504
505                 case 'Y':       /* salt length */
506                         salt.len = strtol (optarg, NULL, 10);
507                         break;
508
509                 case 'y':       /* user specified salt */
510                         salt.len = strlen (optarg);
511                         salt.salt = (unsigned char *)STRDUP (optarg);
512                         break;
513
514                 case 'z':       /* time limit */
515                         sizelimit = strtol (optarg, NULL, 10);
516                         break;
517
518                 default:
519                         usage (argv[0]);
520                 }
521         }
522
523         /* grab filter */
524         if (!(argc - optind < 1))
525                 filtpattern = STRDUP (argv[optind]);
526
527         /* check for target(s) */
528         if (!filtpattern && !targetdn)
529                 targetdn = binddn;
530
531         /* handle bind password */
532         if (want_bindpw)
533                 bindpw = strdup (getpass ("Enter LDAP password: "));
534
535         /* handle new password */
536         if (!newpw)
537         {
538                 char *cknewpw;
539                 newpw = strdup (getpass ("New password: "));
540                 cknewpw = getpass ("Re-enter new password: ");
541
542                 if (strncmp (newpw, cknewpw, strlen (newpw)))
543                 {
544                         fprintf (stderr, "passwords do not match\n");
545                         exit (1);
546                 }
547         }
548
549         if ( debug ) {
550                 lber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug );
551                 ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug );
552         }
553
554         /* connect to server */
555         if ((ld = ldap_open (ldaphost, ldapport)) == NULL)
556         {
557                 perror (ldaphost);
558                 exit (1);
559         }
560
561         /* set options */
562         ldap_set_option (ld, LDAP_OPT_TIMELIMIT, (void *)&timelimit);
563         ldap_set_option (ld, LDAP_OPT_SIZELIMIT, (void *)&sizelimit);
564
565         /* this seems prudent */
566         {
567                 int deref = LDAP_DEREF_NEVER;
568                 ldap_set_option( ld, LDAP_OPT_DEREF, &deref);
569         }
570
571         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version );
572
573         /* authenticate to server */
574         if (ldap_bind_s (ld, binddn, bindpw, authmethod) != LDAP_SUCCESS)
575         {
576                 ldap_perror (ld, "ldap_bind");
577                 exit (1);
578         }
579
580         if (targetdn)
581         {
582                 if (want_entryhash)
583                 {
584                         /* insert code here =) */
585                 }
586                 else
587                         modify_dn (ld, targetdn, pwattr, NULL, newpw, hashtype, &salt);
588         }
589
590         if (filtpattern)
591         {
592                 char            filter[BUFSIZ];
593                 LDAPMessage    *result = NULL, *e = NULL;
594                 char           *attrs[3] = {"dn", NULL, NULL};
595                 attrs[1] = pwattr;
596
597                 /* search */
598                 sprintf (filter, "%s", filtpattern);
599                 i = ldap_search_s (ld, base, scope, filter, attrs, 0, &result);
600                 if (i != LDAP_SUCCESS &&
601                     i != LDAP_TIMELIMIT_EXCEEDED &&
602                     i != LDAP_SIZELIMIT_EXCEEDED)
603                 {
604                         ldap_perror (ld, "ldap_search_s");
605                         exit (1);
606                 }
607
608                 for (e = ldap_first_entry (ld, result); e; e = ldap_next_entry (ld, e))
609                 {
610                         char *dn = ldap_get_dn (ld, e);
611                         if (dn)
612                         {
613                                 struct berval **pw_vals = ldap_get_values_len (ld, e, pwattr);
614                                 modify_dn (ld, dn, pwattr, pw_vals ? pw_vals[0]->bv_val : NULL, newpw, hashtype, &salt);
615                                 if (pw_vals)
616                                         ldap_value_free_len (pw_vals);
617                                 free (dn);
618                         }
619                 }
620         }
621
622         /* disconnect from server */
623         ldap_unbind (ld);
624         exit(0);
625
626         /* unreached */
627         return (0);
628 }