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