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