]> git.sur5r.net Git - openldap/blob - clients/tools/ldappasswd.c
b45d13361579d54434a168d9cbe8f27d0ef1f068
[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;
150
151         salt.salt = NULL;
152         salt.len = 0;
153
154         make_salt (&salt, len);
155         for (i = 0; i < len; i++)
156                 salt.salt[i] = autogen[salt.salt[i] % (sizeof (autogen) - 1)];
157
158         return ((char *)salt.salt);
159 }
160
161 #ifdef SLAPD_CLEARTEXT
162 char *
163 hash_none (const char *pw_in, Salt * salt)
164 {
165         return (STRDUP (pw_in));
166 }
167 #endif
168
169 #ifdef SLAPD_CRYPT
170 char *
171 hash_crypt (const char *pw_in, Salt * salt)
172 {
173         const unsigned char crypt64[] =
174                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890./";
175         char   *crypted_pw = NULL;
176         Salt    lsalt;
177
178         if (salt && salt->salt && strlen ((char *)salt->salt) >= 2)
179         {
180                 /* sanity check */
181                 if (!(isalnum(salt->salt[0]) || salt->salt[0] == '.' || salt->salt[0] == '/'))
182                         salt->salt[0] = crypt64[salt->salt[0] % (sizeof (crypt64) - 1)];
183                 if (!(isalnum(salt->salt[1]) || salt->salt[1] == '.' || salt->salt[1] == '/'))
184                         salt->salt[1] = crypt64[salt->salt[1] % (sizeof (crypt64) - 1)];
185
186                 crypted_pw = crypt (pw_in, (char *)salt->salt);
187         }
188         else
189         {
190                 make_salt (&lsalt, 2);
191                 lsalt.salt[0] = crypt64[lsalt.salt[0] % (sizeof (crypt64) - 1)];
192                 lsalt.salt[1] = crypt64[lsalt.salt[1] % (sizeof (crypt64) - 1)];
193                 crypted_pw = crypt (pw_in, (char *)lsalt.salt);
194                 free (lsalt.salt);
195         }
196         return (STRDUP (crypted_pw));
197 }
198 #endif
199
200 char *
201 hash_md5 (const char *pw_in, Salt * salt)
202 {
203         lutil_MD5_CTX   MD5context;
204         unsigned char   MD5digest[16];
205
206         lutil_MD5Init (&MD5context);
207         lutil_MD5Update (&MD5context, pw_in, strlen(pw_in));
208         if (salt && salt->salt && salt->len)
209                 lutil_MD5Update (&MD5context, salt->salt, salt->len);
210         lutil_MD5Final (MD5digest, &MD5context);
211
212         return (pw_encode (MD5digest, salt, sizeof (MD5digest)));
213 }
214
215 char *
216 hash_sha1 (const char *pw_in, Salt * salt)
217 {
218         lutil_SHA1_CTX  SHA1context;
219         unsigned char   SHA1digest[20];
220
221         lutil_SHA1Init (&SHA1context);
222         lutil_SHA1Update (&SHA1context, pw_in, strlen(pw_in));
223         if (salt && salt->salt && salt->len)
224                 lutil_SHA1Update (&SHA1context, salt->salt, salt->len);
225         lutil_SHA1Final (SHA1digest, &SHA1context);
226
227         return (pw_encode (SHA1digest, salt, sizeof (SHA1digest)));
228 }
229
230 static Hash hashes[] =
231 {
232 #ifdef SLAPD_CLEARTEXT
233         {"none",  4, hash_none,  0, HASHTYPE_NONE,  HASHTYPE_NONE,  0},
234 #endif
235 #ifdef SLAPD_CRYPT
236         {"crypt", 5, hash_crypt, 1, HASHTYPE_CRYPT, HASHTYPE_CRYPT, 2},
237 #endif
238         {"md5",   3, hash_md5,   0, HASHTYPE_MD5,   HASHTYPE_SMD5,  0},
239         {"smd5",  4, hash_md5,   1, HASHTYPE_SMD5,  HASHTYPE_SMD5,  4},
240         {"sha",   3, hash_sha1,  0, HASHTYPE_SHA1,  HASHTYPE_SSHA1, 0},
241         {"ssha",  4, hash_sha1,  1, HASHTYPE_SSHA1, HASHTYPE_SSHA1, 4},
242         {NULL,    0, NULL,       0, HASHTYPE_NONE,  HASHTYPE_NONE,  0}
243 };
244
245 int
246 modify_dn (LDAP * ld, char *targetdn, char *pwattr, char *oldpw,
247            char *newpw, HashTypes htype, Salt * salt)
248 {
249         int             ret = 0;
250         int             salted = salt->salt ? 1 : 0;
251         int             want_salt = salt->len && !salted;
252         char           *buf = NULL;
253         char           *hashed_pw = NULL;
254         char           *strvals[2];
255         LDAPMod         mod, *mods[2];
256
257         if (!ld || !targetdn || !newpw)
258                 return (1);
259
260         /* auto-generate password */
261         if (auto_gen_pw)
262                 newpw = gen_pass (auto_gen_pw);
263
264         /* handle salt */
265         if (want_salt)
266         {
267                 make_salt (salt, salt->len);
268                 htype = hashes[htype].type_salted;
269         }
270         else if (hashes[htype].default_salt_len)
271         {
272                 /* user chose a salted hash and needs a salt */
273                 if (!salted)
274                 {
275                         want_salt++;
276                         salt->len = hashes[htype].default_salt_len;
277                         make_salt (salt, salt->len);
278                 }
279         }
280
281         /* hash password */
282         hashed_pw = hashes[htype].func (newpw, salt->len ? salt : NULL);
283
284         /* return salt back to it's original state */
285         if (want_salt)
286         {
287                 free (salt->salt);
288                 salt->salt = NULL;
289         }
290
291         buf = (char *)malloc (hashes[htype].namesz + 3 + strlen (hashed_pw));
292         if (htype)
293                 sprintf (buf, "{%s}%s", hashes[htype].name, hashed_pw);
294         else
295                 sprintf (buf, "%s", hashed_pw);
296
297         if (verbose > 0)
298         {
299                 printf ("%s", targetdn);
300                 if (verbose > 1)
301                 {
302                         printf (":%s", buf);
303                         if (verbose > 2)
304                                 printf (":%s", newpw);
305                 }
306                 printf ("\n");
307         }
308
309         strvals[0] = buf;
310         strvals[1] = NULL;
311         mod.mod_vals.modv_strvals = strvals;
312         mod.mod_type = pwattr;
313         mod.mod_op = LDAP_MOD_REPLACE;
314         mods[0] = &mod;
315         mods[1] =NULL;
316
317         if (!noupdates && (ret = ldap_modify_s (ld, targetdn, mods)) != LDAP_SUCCESS)
318                 ldap_perror (ld, "ldap_modify_s");
319
320         free (hashed_pw);
321         free (buf);
322         return (ret);
323 }
324
325 void
326 usage (char *s)
327 {
328         fprintf (stderr, "Usage: %s [options] [filter]\n", s);
329         fprintf (stderr, "  -a attrib\tpassword attribute (default: %s)\n", LDAP_PASSWD_ATTRIB);
330         fprintf (stderr, "  -b basedn\tbasedn to perform searches\n");
331 /*      fprintf (stderr, "  -C\t\tuse entry's current hash mechanism\n"); */
332         fprintf (stderr, "  -D binddn\tbind dn\n");
333         fprintf (stderr, "  -d level\tdebugging level\n");
334         fprintf (stderr, "  -E\t\tprompt for new password\n");
335         fprintf (stderr, "  -e passwd\tnew password\n");
336         fprintf (stderr, "  -g passlen\tauto-generate passwords with length pwlen\n");
337         fprintf (stderr, "  -H hash\thash type (default: crypt)\n");
338         fprintf (stderr, "  -h host\tldap server (default: localhost)\n");
339 #ifdef HAVE_KERBEROS
340         fprintf (stderr, "  -K\t\tuse Kerberos step 1\n");
341         fprintf (stderr, "  -k\t\tuse Kerberos\n");
342 #endif
343         fprintf (stderr, "  -l time\ttime limit\n");
344         fprintf (stderr, "  -n\t\tmake no modifications\n");
345         fprintf (stderr, "  -P version\tprotocol version (2 or 3)\n");
346         fprintf (stderr, "  -p port\tldap port\n");
347         fprintf (stderr, "  -s scope\tsearch scope: base, one, sub (default: sub)\n");
348         fprintf (stderr, "  -t targetdn\tdn to change password\n");
349         fprintf (stderr, "  -v\t\tverbose (more v's, more verbose)\n");
350         fprintf (stderr, "  -W\t\tprompt for bind password\n");
351         fprintf (stderr, "  -w passwd\tbind password (for simple authentication)\n");
352         fprintf (stderr, "  -Y saltlen\tsalt length to use\n");
353 /*      fprintf (stderr, "  -y salt\tsalt to use\n"); */
354         fprintf (stderr, "  -z size\tsize limit\n");
355         exit (1);
356 }
357
358 int
359 main (int argc, char *argv[])
360 {
361         char           *base = NULL;
362         char           *binddn = NULL;
363         char           *bindpw = NULL;
364         char           *filtpattern = NULL;
365         char           *ldaphost = NULL;
366         char           *targetdn = NULL;
367         char           *pwattr = LDAP_PASSWD_ATTRIB;
368         char           *newpw = NULL;
369         int             authmethod = LDAP_AUTH_SIMPLE;
370         int             hashtype = HASHTYPE_CRYPT;
371         int             i, j;
372         int             ldapport = 0;
373         int             debug = 0;
374         int             scope = LDAP_SCOPE_SUBTREE;
375         int             sizelimit = -1;
376         int             timelimit = -1;
377         int             version = -1;
378         int             want_bindpw = 0;
379         int             want_newpw = 0;
380         LDAP           *ld;
381         Salt            salt;
382
383         salt.salt = NULL;
384         salt.len = 0;
385
386         if (argc == 1)
387                 usage (argv[0]);
388
389         while ((i = getopt (argc, argv, "a:b:C:D:d:Ee:g:H:h:Kkl:nP:p:s:t:vWw:Y:y:z:")) != EOF)
390         {
391                 switch (i)
392                 {
393                 case 'a':       /* password attribute */
394                         pwattr = STRDUP (optarg);
395                         break;
396
397                 case 'b':       /* base search dn */
398                         base = STRDUP (optarg);
399                         break;
400
401                 case 'C':
402                         want_entryhash++;
403                         break;
404
405                 case 'D':       /* bind distinguished name */
406                         binddn = STRDUP (optarg);
407                         break;
408
409                 case 'd':       /* debugging option */
410                         debug |= atoi (optarg);
411                         break;
412
413                 case 'E':       /* prompt for new password */
414                         want_newpw++;
415                         break;
416
417                 case 'e':       /* new password */
418                         newpw = STRDUP (optarg);
419                         break;
420
421                 case 'g':
422                         auto_gen_pw = strtol (optarg, NULL, 10);
423                         break;
424
425                 case 'H':       /* hashes */
426                         for (j = 0; hashes[j].name; j++)
427                         {
428                                 if (!strncasecmp (optarg, hashes[j].name, hashes[j].namesz))
429                                 {
430                                         hashtype = hashes[j].type;
431                                         break;
432                                 }
433                         }
434
435                         if (!hashes[j].name)
436                         {
437                                 fprintf (stderr, "hash type: %s is unknown\n", optarg);
438                                 usage (argv[0]);
439                         }
440                         break;
441
442                 case 'h':       /* ldap host */
443                         ldaphost = STRDUP (optarg);
444                         break;
445
446                 case 'K':       /* use kerberos bind, 1st part only */
447 #ifdef HAVE_KERBEROS
448                         authmethod = LDAP_AUTH_KRBV41;
449 #else
450                         fprintf (stderr, "%s was not compiled with Kerberos support\n", argv[0]);
451 #endif
452                         break;
453
454                 case 'k':       /* use kerberos bind */
455 #ifdef HAVE_KERBEROS
456                         authmethod = LDAP_AUTH_KRBV4;
457 #else
458                         fprintf (stderr, "%s was not compiled with Kerberos support\n", argv[0]);
459 #endif
460                         break;
461
462                 case 'l':       /* time limit */
463                         timelimit = strtol (optarg, NULL, 10);
464                         break;
465
466                 case 'n':       /* don't update entry(s) */
467                         noupdates++;
468                         break;
469
470                 case 'P':
471                         switch(optarg[0])
472                         {
473                         case '2':
474                                 version = LDAP_VERSION2;
475                                 break;
476                         case '3':
477                                 version = LDAP_VERSION3;
478                                 break;
479                         }
480                         break;
481
482                 case 'p':       /* ldap port */
483                         ldapport = strtol (optarg, NULL, 10);
484                         break;
485
486                 case 's':       /* scope */
487                         if (strncasecmp (optarg, "base", 4) == 0)
488                                 scope = LDAP_SCOPE_BASE;
489                         else if (strncasecmp (optarg, "one", 3) == 0)
490                                 scope = LDAP_SCOPE_ONELEVEL;
491                         else if (strncasecmp (optarg, "sub", 3) == 0)
492                                 scope = LDAP_SCOPE_SUBTREE;
493                         else
494                         {
495                                 fprintf (stderr, "scope should be base, one, or sub\n");
496                                 usage (argv[0]);
497                         }
498                         break;
499
500                 case 't':       /* target dn */
501                         targetdn = STRDUP (optarg);
502                         break;
503
504                 case 'v':       /* verbose */
505                         verbose++;
506                         break;
507
508                 case 'W':       /* promt for bind password */
509                         want_bindpw++;
510                         break;
511
512                 case 'w':       /* bind password */
513                         bindpw = STRDUP (optarg);
514                         break;
515
516                 case 'Y':       /* salt length */
517                         salt.len = strtol (optarg, NULL, 10);
518                         break;
519
520                 case 'y':       /* user specified salt */
521                         salt.len = strlen (optarg);
522                         salt.salt = (unsigned char *)STRDUP (optarg);
523                         break;
524
525                 case 'z':       /* time limit */
526                         sizelimit = strtol (optarg, NULL, 10);
527                         break;
528
529                 default:
530                         usage (argv[0]);
531                 }
532         }
533
534         /* grab filter */
535         if (!(argc - optind < 1))
536                 filtpattern = STRDUP (argv[optind]);
537
538         /* check for target(s) */
539         if (!filtpattern && !targetdn)
540                 targetdn = binddn;
541
542         /* handle bind password */
543         if (want_bindpw)
544                 bindpw = strdup (getpass ("Enter LDAP password: "));
545
546         /* handle new password */
547         if (!newpw)
548         {
549                 char *cknewpw;
550                 newpw = strdup (getpass ("New password: "));
551                 cknewpw = getpass ("Re-enter new password: ");
552
553                 if (strncmp (newpw, cknewpw, strlen (newpw)))
554                 {
555                         fprintf (stderr, "passwords do not match\n");
556                         exit (1);
557                 }
558         }
559
560         if ( debug ) {
561                 lber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug );
562                 ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug );
563         }
564
565         /* connect to server */
566         if ((ld = ldap_open (ldaphost, ldapport)) == NULL)
567         {
568                 perror (ldaphost);
569                 exit (1);
570         }
571
572         /* set options */
573         if( timelimit != -1 ) {
574                 ldap_set_option (ld, LDAP_OPT_TIMELIMIT, (void *)&timelimit);
575         }
576         if( sizelimit != -1 ) {
577                 ldap_set_option (ld, LDAP_OPT_SIZELIMIT, (void *)&sizelimit);
578         }
579
580         /* this seems prudent */
581         {
582                 int deref = LDAP_DEREF_NEVER;
583                 ldap_set_option( ld, LDAP_OPT_DEREF, &deref);
584         }
585
586         if( version != -1 ) {
587                 ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version );
588         }
589
590         /* authenticate to server */
591         if (ldap_bind_s (ld, binddn, bindpw, authmethod) != LDAP_SUCCESS)
592         {
593                 ldap_perror (ld, "ldap_bind");
594                 exit (1);
595         }
596
597         if (targetdn)
598         {
599                 if (want_entryhash)
600                 {
601                         /* insert code here =) */
602                 }
603                 else
604                         modify_dn (ld, targetdn, pwattr, NULL, newpw, hashtype, &salt);
605         }
606
607         if (filtpattern)
608         {
609                 char            filter[BUFSIZ];
610                 LDAPMessage    *result = NULL, *e = NULL;
611                 char           *attrs[3] = {"dn", NULL, NULL};
612                 attrs[1] = pwattr;
613
614                 /* search */
615                 sprintf (filter, "%s", filtpattern);
616                 i = ldap_search_s (ld, base, scope, filter, attrs, 0, &result);
617                 if (i != LDAP_SUCCESS &&
618                     i != LDAP_TIMELIMIT_EXCEEDED &&
619                     i != LDAP_SIZELIMIT_EXCEEDED)
620                 {
621                         ldap_perror (ld, "ldap_search_s");
622                         exit (1);
623                 }
624
625                 for (e = ldap_first_entry (ld, result); e; e = ldap_next_entry (ld, e))
626                 {
627                         char *dn = ldap_get_dn (ld, e);
628                         if (dn)
629                         {
630                                 struct berval **pw_vals = ldap_get_values_len (ld, e, pwattr);
631                                 modify_dn (ld, dn, pwattr, pw_vals ? pw_vals[0]->bv_val : NULL, newpw, hashtype, &salt);
632                                 if (pw_vals)
633                                         ldap_value_free_len (pw_vals);
634                                 free (dn);
635                         }
636                 }
637         }
638
639         /* disconnect from server */
640         ldap_unbind (ld);
641         exit(0);
642
643         /* unreached */
644         return (0);
645 }