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