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