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