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