s3-kerberos: only use krb5 headers where required.
[ira/wip.git] / source3 / libads / krb5_setpw.c
1 /* 
2    Unix SMB/CIFS implementation.
3    krb5 set password implementation
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Remus Koos 2001 (remuskoos@yahoo.com)
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "smb_krb5.h"
23
24 #ifdef HAVE_KRB5
25
26 #define DEFAULT_KPASSWD_PORT    464
27
28 #define KRB5_KPASSWD_VERS_CHANGEPW              1
29
30 #define KRB5_KPASSWD_VERS_SETPW                 0xff80
31 #define KRB5_KPASSWD_VERS_SETPW_ALT             2
32
33 #define KRB5_KPASSWD_SUCCESS                    0
34 #define KRB5_KPASSWD_MALFORMED                  1
35 #define KRB5_KPASSWD_HARDERROR                  2
36 #define KRB5_KPASSWD_AUTHERROR                  3
37 #define KRB5_KPASSWD_SOFTERROR                  4
38 #define KRB5_KPASSWD_ACCESSDENIED               5
39 #define KRB5_KPASSWD_BAD_VERSION                6
40 #define KRB5_KPASSWD_INITIAL_FLAG_NEEDED        7
41
42 /* Those are defined by kerberos-set-passwd-02.txt and are probably 
43  * not supported by M$ implementation */
44 #define KRB5_KPASSWD_POLICY_REJECT              8
45 #define KRB5_KPASSWD_BAD_PRINCIPAL              9
46 #define KRB5_KPASSWD_ETYPE_NOSUPP               10
47
48 /*
49  * we've got to be able to distinguish KRB_ERRORs from other
50  * requests - valid response for CHPW v2 replies.
51  */
52
53 #define krb5_is_krb_error(packet) \
54         ( packet && packet->length && (((char *)packet->data)[0] == 0x7e || ((char *)packet->data)[0] == 0x5e))
55
56 /* This implements kerberos password change protocol as specified in 
57  * kerb-chg-password-02.txt and kerberos-set-passwd-02.txt
58  * as well as microsoft version of the protocol 
59  * as specified in kerberos-set-passwd-00.txt
60  */
61 static DATA_BLOB encode_krb5_setpw(const char *principal, const char *password)
62 {
63         char* princ_part1 = NULL;
64         char* princ_part2 = NULL;
65         char* realm = NULL;
66         char* c;
67         char* princ;
68
69         ASN1_DATA *req;
70         DATA_BLOB ret;
71
72
73         princ = SMB_STRDUP(principal);
74
75         if ((c = strchr_m(princ, '/')) == NULL) {
76                 c = princ; 
77         } else {
78                 *c = '\0';
79                 c++;
80                 princ_part1 = princ;
81         }
82
83         princ_part2 = c;
84
85         if ((c = strchr_m(c, '@')) != NULL) {
86                 *c = '\0';
87                 c++;
88                 realm = c;
89         } else {
90                 /* We must have a realm component. */
91                 return data_blob_null;
92         }
93
94         req = asn1_init(talloc_tos());
95         if (req == NULL) {
96                 return data_blob_null;
97         }
98
99         asn1_push_tag(req, ASN1_SEQUENCE(0));
100         asn1_push_tag(req, ASN1_CONTEXT(0));
101         asn1_write_OctetString(req, password, strlen(password));
102         asn1_pop_tag(req);
103
104         asn1_push_tag(req, ASN1_CONTEXT(1));
105         asn1_push_tag(req, ASN1_SEQUENCE(0));
106
107         asn1_push_tag(req, ASN1_CONTEXT(0));
108         asn1_write_Integer(req, 1);
109         asn1_pop_tag(req);
110
111         asn1_push_tag(req, ASN1_CONTEXT(1));
112         asn1_push_tag(req, ASN1_SEQUENCE(0));
113
114         if (princ_part1) {
115                 asn1_write_GeneralString(req, princ_part1);
116         }
117         
118         asn1_write_GeneralString(req, princ_part2);
119         asn1_pop_tag(req);
120         asn1_pop_tag(req);
121         asn1_pop_tag(req);
122         asn1_pop_tag(req);
123
124         asn1_push_tag(req, ASN1_CONTEXT(2));
125         asn1_write_GeneralString(req, realm);
126         asn1_pop_tag(req);
127         asn1_pop_tag(req);
128
129         ret = data_blob(req->data, req->length);
130         asn1_free(req);
131
132         free(princ);
133
134         return ret;
135 }       
136
137 static krb5_error_code build_kpasswd_request(uint16 pversion,
138                                            krb5_context context,
139                                            krb5_auth_context auth_context,
140                                            krb5_data *ap_req,
141                                            const char *princ,
142                                            const char *passwd,
143                                            bool use_tcp,
144                                            krb5_data *packet)
145 {
146         krb5_error_code ret;
147         krb5_data cipherpw;
148         krb5_data encoded_setpw;
149         krb5_replay_data replay;
150         char *p, *msg_start;
151         DATA_BLOB setpw;
152         unsigned int msg_length;
153
154         ret = krb5_auth_con_setflags(context,
155                                      auth_context,KRB5_AUTH_CONTEXT_DO_SEQUENCE);
156         if (ret) {
157                 DEBUG(1,("krb5_auth_con_setflags failed (%s)\n",
158                          error_message(ret)));
159                 return ret;
160         }
161
162         /* handle protocol differences in chpw and setpw */
163         if (pversion  == KRB5_KPASSWD_VERS_CHANGEPW)
164                 setpw = data_blob(passwd, strlen(passwd));
165         else if (pversion == KRB5_KPASSWD_VERS_SETPW ||
166                  pversion == KRB5_KPASSWD_VERS_SETPW_ALT)
167                 setpw = encode_krb5_setpw(princ, passwd);
168         else
169                 return EINVAL;
170
171         if (setpw.data == NULL || setpw.length == 0) {
172                 return EINVAL;
173         }
174
175         encoded_setpw.data = (char *)setpw.data;
176         encoded_setpw.length = setpw.length;
177
178         ret = krb5_mk_priv(context, auth_context,
179                            &encoded_setpw, &cipherpw, &replay);
180         
181         data_blob_free(&setpw);         /*from 'encode_krb5_setpw(...)' */
182         
183         if (ret) {
184                 DEBUG(1,("krb5_mk_priv failed (%s)\n", error_message(ret)));
185                 return ret;
186         }
187
188         packet->data = (char *)SMB_MALLOC(ap_req->length + cipherpw.length + (use_tcp ? 10 : 6 ));
189         if (!packet->data)
190                 return -1;
191
192
193
194         /* see the RFC for details */
195
196         msg_start = p = ((char *)packet->data) + (use_tcp ? 4 : 0);
197         p += 2;
198         RSSVAL(p, 0, pversion);
199         p += 2;
200         RSSVAL(p, 0, ap_req->length);
201         p += 2;
202         memcpy(p, ap_req->data, ap_req->length);
203         p += ap_req->length;
204         memcpy(p, cipherpw.data, cipherpw.length);
205         p += cipherpw.length;
206         packet->length = PTR_DIFF(p,packet->data);
207         msg_length = PTR_DIFF(p,msg_start);
208
209         if (use_tcp) {
210                 RSIVAL(packet->data, 0, msg_length);
211         }
212         RSSVAL(msg_start, 0, msg_length);
213         
214         free(cipherpw.data);    /* from 'krb5_mk_priv(...)' */
215
216         return 0;
217 }
218
219 static const struct kpasswd_errors {
220         int result_code;
221         const char *error_string;
222 } kpasswd_errors[] = {
223         {KRB5_KPASSWD_MALFORMED, "Malformed request error"},
224         {KRB5_KPASSWD_HARDERROR, "Server error"},
225         {KRB5_KPASSWD_AUTHERROR, "Authentication error"},
226         {KRB5_KPASSWD_SOFTERROR, "Password change rejected"},
227         {KRB5_KPASSWD_ACCESSDENIED, "Client does not have proper authorization"},
228         {KRB5_KPASSWD_BAD_VERSION, "Protocol version not supported"},
229         {KRB5_KPASSWD_INITIAL_FLAG_NEEDED, "Authorization ticket must have initial flag set"},
230         {KRB5_KPASSWD_POLICY_REJECT, "Password rejected due to policy requirements"},
231         {KRB5_KPASSWD_BAD_PRINCIPAL, "Target principal does not exist"},
232         {KRB5_KPASSWD_ETYPE_NOSUPP, "Unsupported encryption type"},
233         {0, NULL}
234 };
235
236 static krb5_error_code setpw_result_code_string(krb5_context context,
237                                                 int result_code,
238                                                 const char **code_string)
239 {
240         unsigned int idx = 0;
241
242         while (kpasswd_errors[idx].error_string != NULL) {
243                 if (kpasswd_errors[idx].result_code == 
244                     result_code) {
245                         *code_string = kpasswd_errors[idx].error_string;
246                         return 0;
247                 }
248                 idx++;
249         }
250         *code_string = "Password change failed";
251         return (0);
252 }
253
254  krb5_error_code kpasswd_err_to_krb5_err(krb5_error_code res_code) 
255 {
256         switch(res_code) {
257                 case KRB5_KPASSWD_ACCESSDENIED:
258                         return KRB5KDC_ERR_BADOPTION;
259                 case KRB5_KPASSWD_INITIAL_FLAG_NEEDED:
260                         return KRB5KDC_ERR_BADOPTION;
261                         /* return KV5M_ALT_METHOD; MIT-only define */
262                 case KRB5_KPASSWD_ETYPE_NOSUPP:
263                         return KRB5KDC_ERR_ETYPE_NOSUPP;
264                 case KRB5_KPASSWD_BAD_PRINCIPAL:
265                         return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
266                 case KRB5_KPASSWD_POLICY_REJECT:
267                 case KRB5_KPASSWD_SOFTERROR:
268                         return KRB5KDC_ERR_POLICY;
269                 default:
270                         return KRB5KRB_ERR_GENERIC;
271         }
272 }
273 static krb5_error_code parse_setpw_reply(krb5_context context,
274                                          bool use_tcp,
275                                          krb5_auth_context auth_context,
276                                          krb5_data *packet)
277 {
278         krb5_data ap_rep;
279         char *p;
280         int vnum, ret, res_code;
281         krb5_data cipherresult;
282         krb5_data clearresult;
283         krb5_ap_rep_enc_part *ap_rep_enc;
284         krb5_replay_data replay;
285         unsigned int msg_length = packet->length;
286
287
288         if (packet->length < (use_tcp ? 8 : 4)) {
289                 return KRB5KRB_AP_ERR_MODIFIED;
290         }
291         
292         p = (char *)packet->data;
293         /*
294         ** see if it is an error
295         */
296         if (krb5_is_krb_error(packet)) {
297
298                 ret = handle_krberror_packet(context, packet);
299                 if (ret) {
300                         return ret;
301                 }
302         }
303
304         
305         /* tcp... */
306         if (use_tcp) {
307                 msg_length -= 4;
308                 if (RIVAL(p, 0) != msg_length) {
309                         DEBUG(1,("Bad TCP packet length (%d/%d) from kpasswd server\n",
310                         RIVAL(p, 0), msg_length));
311                         return KRB5KRB_AP_ERR_MODIFIED;
312                 }
313
314                 p += 4;
315         }
316         
317         if (RSVAL(p, 0) != msg_length) {
318                 DEBUG(1,("Bad packet length (%d/%d) from kpasswd server\n",
319                          RSVAL(p, 0), msg_length));
320                 return KRB5KRB_AP_ERR_MODIFIED;
321         }
322
323         p += 2;
324
325         vnum = RSVAL(p, 0); p += 2;
326
327         /* FIXME: According to standard there is only one type of reply */      
328         if (vnum != KRB5_KPASSWD_VERS_SETPW && 
329             vnum != KRB5_KPASSWD_VERS_SETPW_ALT && 
330             vnum != KRB5_KPASSWD_VERS_CHANGEPW) {
331                 DEBUG(1,("Bad vnum (%d) from kpasswd server\n", vnum));
332                 return KRB5KDC_ERR_BAD_PVNO;
333         }
334         
335         ap_rep.length = RSVAL(p, 0); p += 2;
336         
337         if (p + ap_rep.length >= (char *)packet->data + packet->length) {
338                 DEBUG(1,("ptr beyond end of packet from kpasswd server\n"));
339                 return KRB5KRB_AP_ERR_MODIFIED;
340         }
341         
342         if (ap_rep.length == 0) {
343                 DEBUG(1,("got unencrypted setpw result?!\n"));
344                 return KRB5KRB_AP_ERR_MODIFIED;
345         }
346
347         /* verify ap_rep */
348         ap_rep.data = p;
349         p += ap_rep.length;
350         
351         ret = krb5_rd_rep(context, auth_context, &ap_rep, &ap_rep_enc);
352         if (ret) {
353                 DEBUG(1,("failed to rd setpw reply (%s)\n", error_message(ret)));
354                 return KRB5KRB_AP_ERR_MODIFIED;
355         }
356         
357         krb5_free_ap_rep_enc_part(context, ap_rep_enc);
358         
359         cipherresult.data = p;
360         cipherresult.length = ((char *)packet->data + packet->length) - p;
361                 
362         ret = krb5_rd_priv(context, auth_context, &cipherresult, &clearresult,
363                            &replay);
364         if (ret) {
365                 DEBUG(1,("failed to decrypt setpw reply (%s)\n", error_message(ret)));
366                 return KRB5KRB_AP_ERR_MODIFIED;
367         }
368
369         if (clearresult.length < 2) {
370                 free(clearresult.data);
371                 ret = KRB5KRB_AP_ERR_MODIFIED;
372                 return KRB5KRB_AP_ERR_MODIFIED;
373         }
374         
375         p = (char *)clearresult.data;
376         
377         res_code = RSVAL(p, 0);
378         
379         free(clearresult.data);
380
381         if ((res_code < KRB5_KPASSWD_SUCCESS) || 
382             (res_code > KRB5_KPASSWD_ETYPE_NOSUPP)) {
383                 return KRB5KRB_AP_ERR_MODIFIED;
384         }
385
386         if (res_code == KRB5_KPASSWD_SUCCESS) {
387                 return 0;
388         } else {
389                 const char *errstr;
390                 setpw_result_code_string(context, res_code, &errstr);
391                 DEBUG(1, ("Error changing password: %s (%d)\n", errstr, res_code));
392
393                 return kpasswd_err_to_krb5_err(res_code);
394         }
395 }
396
397 static ADS_STATUS do_krb5_kpasswd_request(krb5_context context,
398                                           const char *kdc_host,
399                                           uint16 pversion,
400                                           krb5_creds *credsp,
401                                           const char *princ,
402                                           const char *newpw)
403 {
404         krb5_auth_context auth_context = NULL;
405         krb5_data ap_req, chpw_req, chpw_rep;
406         int ret, sock;
407         socklen_t addr_len;
408         struct sockaddr_storage remote_addr, local_addr;
409         struct sockaddr_storage addr;
410         krb5_address local_kaddr, remote_kaddr;
411         bool use_tcp = False;
412
413
414         if (!interpret_string_addr(&addr, kdc_host, 0)) {
415         }
416
417         ret = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SUBKEY,
418                                    NULL, credsp, &ap_req);
419         if (ret) {
420                 DEBUG(1,("krb5_mk_req_extended failed (%s)\n", error_message(ret)));
421                 return ADS_ERROR_KRB5(ret);
422         }
423
424         do {
425
426                 if (!use_tcp) {
427
428                         sock = open_udp_socket(kdc_host, DEFAULT_KPASSWD_PORT);
429                         if (sock == -1) {
430                                 int rc = errno;
431                                 SAFE_FREE(ap_req.data);
432                                 krb5_auth_con_free(context, auth_context);
433                                 DEBUG(1,("failed to open kpasswd socket to %s "
434                                          "(%s)\n", kdc_host, strerror(errno)));
435                                 return ADS_ERROR_SYSTEM(rc);
436                         }
437                 } else {
438                         NTSTATUS status;
439                         status = open_socket_out(&addr, DEFAULT_KPASSWD_PORT,
440                                                  LONG_CONNECT_TIMEOUT, &sock);
441                         if (!NT_STATUS_IS_OK(status)) {
442                                 SAFE_FREE(ap_req.data);
443                                 krb5_auth_con_free(context, auth_context);
444                                 DEBUG(1,("failed to open kpasswd socket to %s "
445                                          "(%s)\n", kdc_host,
446                                          nt_errstr(status)));
447                                 return ADS_ERROR_NT(status);
448                         }
449                 }
450
451                 addr_len = sizeof(remote_addr);
452                 if (getpeername(sock, (struct sockaddr *)&remote_addr, &addr_len) != 0) {
453                         close(sock);
454                         SAFE_FREE(ap_req.data);
455                         krb5_auth_con_free(context, auth_context);
456                         DEBUG(1,("getpeername() failed (%s)\n", error_message(errno)));
457                         return ADS_ERROR_SYSTEM(errno);
458                 }
459                 addr_len = sizeof(local_addr);
460                 if (getsockname(sock, (struct sockaddr *)&local_addr, &addr_len) != 0) {
461                         close(sock);
462                         SAFE_FREE(ap_req.data);
463                         krb5_auth_con_free(context, auth_context);
464                         DEBUG(1,("getsockname() failed (%s)\n", error_message(errno)));
465                         return ADS_ERROR_SYSTEM(errno);
466                 }
467                 if (!setup_kaddr(&remote_kaddr, &remote_addr) ||
468                                 !setup_kaddr(&local_kaddr, &local_addr)) {
469                         DEBUG(1,("do_krb5_kpasswd_request: "
470                                 "Failed to setup addresses.\n"));
471                         close(sock);
472                         SAFE_FREE(ap_req.data);
473                         krb5_auth_con_free(context, auth_context);
474                         errno = EINVAL;
475                         return ADS_ERROR_SYSTEM(EINVAL);
476                 }
477
478                 ret = krb5_auth_con_setaddrs(context, auth_context, &local_kaddr, NULL);
479                 if (ret) {
480                         close(sock);
481                         SAFE_FREE(ap_req.data);
482                         krb5_auth_con_free(context, auth_context);
483                         DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n", error_message(ret)));
484                         return ADS_ERROR_KRB5(ret);
485                 }
486
487                 ret = build_kpasswd_request(pversion, context, auth_context, &ap_req,
488                                           princ, newpw, use_tcp, &chpw_req);
489                 if (ret) {
490                         close(sock);
491                         SAFE_FREE(ap_req.data);
492                         krb5_auth_con_free(context, auth_context);
493                         DEBUG(1,("build_setpw_request failed (%s)\n", error_message(ret)));
494                         return ADS_ERROR_KRB5(ret);
495                 }
496
497                 ret = write(sock, chpw_req.data, chpw_req.length); 
498
499                 if (ret != chpw_req.length) {
500                         close(sock);
501                         SAFE_FREE(chpw_req.data);
502                         SAFE_FREE(ap_req.data);
503                         krb5_auth_con_free(context, auth_context);
504                         DEBUG(1,("send of chpw failed (%s)\n", strerror(errno)));
505                         return ADS_ERROR_SYSTEM(errno);
506                 }
507         
508                 SAFE_FREE(chpw_req.data);
509         
510                 chpw_rep.length = 1500;
511                 chpw_rep.data = (char *) SMB_MALLOC(chpw_rep.length);
512                 if (!chpw_rep.data) {
513                         close(sock);
514                         SAFE_FREE(ap_req.data);
515                         krb5_auth_con_free(context, auth_context);
516                         DEBUG(1,("send of chpw failed (%s)\n", strerror(errno)));
517                         errno = ENOMEM;
518                         return ADS_ERROR_SYSTEM(errno);
519                 }
520         
521                 ret = read(sock, chpw_rep.data, chpw_rep.length);
522                 if (ret < 0) {
523                         close(sock);
524                         SAFE_FREE(chpw_rep.data);
525                         SAFE_FREE(ap_req.data);
526                         krb5_auth_con_free(context, auth_context);
527                         DEBUG(1,("recv of chpw reply failed (%s)\n", strerror(errno)));
528                         return ADS_ERROR_SYSTEM(errno);
529                 }
530         
531                 close(sock);
532                 chpw_rep.length = ret;
533         
534                 ret = krb5_auth_con_setaddrs(context, auth_context, NULL,&remote_kaddr);
535                 if (ret) {
536                         SAFE_FREE(chpw_rep.data);
537                         SAFE_FREE(ap_req.data);
538                         krb5_auth_con_free(context, auth_context);
539                         DEBUG(1,("krb5_auth_con_setaddrs on reply failed (%s)\n", 
540                                  error_message(ret)));
541                         return ADS_ERROR_KRB5(ret);
542                 }
543         
544                 ret = parse_setpw_reply(context, use_tcp, auth_context, &chpw_rep);
545                 SAFE_FREE(chpw_rep.data);
546         
547                 if (ret) {
548                         
549                         if (ret == KRB5KRB_ERR_RESPONSE_TOO_BIG && !use_tcp) {
550                                 DEBUG(5, ("Trying setpw with TCP!!!\n"));
551                                 use_tcp = True;
552                                 continue;
553                         }
554
555                         SAFE_FREE(ap_req.data);
556                         krb5_auth_con_free(context, auth_context);
557                         DEBUG(1,("parse_setpw_reply failed (%s)\n", 
558                                  error_message(ret)));
559                         return ADS_ERROR_KRB5(ret);
560                 }
561         
562                 SAFE_FREE(ap_req.data);
563                 krb5_auth_con_free(context, auth_context);
564         } while ( ret );
565
566         return ADS_SUCCESS;
567 }
568
569 ADS_STATUS ads_krb5_set_password(const char *kdc_host, const char *princ, 
570                                  const char *newpw, int time_offset)
571 {
572
573         ADS_STATUS aret;
574         krb5_error_code ret = 0;
575         krb5_context context = NULL;
576         krb5_principal principal = NULL;
577         char *princ_name = NULL;
578         char *realm = NULL;
579         krb5_creds creds, *credsp = NULL;
580 #if KRB5_PRINC_REALM_RETURNS_REALM
581         krb5_realm orig_realm;
582 #else
583         krb5_data orig_realm;
584 #endif
585         krb5_ccache ccache = NULL;
586
587         ZERO_STRUCT(creds);
588         
589         initialize_krb5_error_table();
590         ret = krb5_init_context(&context);
591         if (ret) {
592                 DEBUG(1,("Failed to init krb5 context (%s)\n", error_message(ret)));
593                 return ADS_ERROR_KRB5(ret);
594         }
595         
596         if (time_offset != 0) {
597                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
598         }
599
600         ret = krb5_cc_default(context, &ccache);
601         if (ret) {
602                 krb5_free_context(context);
603                 DEBUG(1,("Failed to get default creds (%s)\n", error_message(ret)));
604                 return ADS_ERROR_KRB5(ret);
605         }
606
607         realm = strchr_m(princ, '@');
608         if (!realm) {
609                 krb5_cc_close(context, ccache);
610                 krb5_free_context(context);
611                 DEBUG(1,("Failed to get realm\n"));
612                 return ADS_ERROR_KRB5(-1);
613         }
614         realm++;
615
616         if (asprintf(&princ_name, "kadmin/changepw@%s", realm) == -1) {
617                 krb5_cc_close(context, ccache);
618                 krb5_free_context(context);
619                 DEBUG(1,("asprintf failed\n"));
620                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
621         }
622
623         ret = smb_krb5_parse_name(context, princ_name, &creds.server);
624         if (ret) {
625                 krb5_cc_close(context, ccache);
626                 krb5_free_context(context);
627                 DEBUG(1,("Failed to parse kadmin/changepw (%s)\n", error_message(ret)));
628                 return ADS_ERROR_KRB5(ret);
629         }
630
631         /* parse the principal we got as a function argument */
632         ret = smb_krb5_parse_name(context, princ, &principal);
633         if (ret) {
634                 krb5_cc_close(context, ccache);
635                 krb5_free_principal(context, creds.server);
636                 krb5_free_context(context);
637                 DEBUG(1,("Failed to parse %s (%s)\n", princ_name, error_message(ret)));
638                 free(princ_name);
639                 return ADS_ERROR_KRB5(ret);
640         }
641
642         free(princ_name);
643
644         /* The creds.server principal takes ownership of this memory.
645                 Remember to set back to original value before freeing. */
646         orig_realm = *krb5_princ_realm(context, creds.server);
647         krb5_princ_set_realm(context, creds.server, krb5_princ_realm(context, principal));
648         
649         ret = krb5_cc_get_principal(context, ccache, &creds.client);
650         if (ret) {
651                 krb5_cc_close(context, ccache);
652                 krb5_princ_set_realm(context, creds.server, &orig_realm);
653                 krb5_free_principal(context, creds.server);
654                 krb5_free_principal(context, principal);
655                 krb5_free_context(context);
656                 DEBUG(1,("Failed to get principal from ccache (%s)\n", 
657                          error_message(ret)));
658                 return ADS_ERROR_KRB5(ret);
659         }
660         
661         ret = krb5_get_credentials(context, 0, ccache, &creds, &credsp); 
662         if (ret) {
663                 krb5_cc_close(context, ccache);
664                 krb5_free_principal(context, creds.client);
665                 krb5_princ_set_realm(context, creds.server, &orig_realm);
666                 krb5_free_principal(context, creds.server);
667                 krb5_free_principal(context, principal);
668                 krb5_free_context(context);
669                 DEBUG(1,("krb5_get_credentials failed (%s)\n", error_message(ret)));
670                 return ADS_ERROR_KRB5(ret);
671         }
672         
673         /* we might have to call krb5_free_creds(...) from now on ... */
674
675         aret = do_krb5_kpasswd_request(context, kdc_host,
676                                        KRB5_KPASSWD_VERS_SETPW,
677                                        credsp, princ, newpw);
678
679         krb5_free_creds(context, credsp);
680         krb5_free_principal(context, creds.client);
681         krb5_princ_set_realm(context, creds.server, &orig_realm);
682         krb5_free_principal(context, creds.server);
683         krb5_free_principal(context, principal);
684         krb5_cc_close(context, ccache);
685         krb5_free_context(context);
686
687         return aret;
688 }
689
690 /*
691   we use a prompter to avoid a crash bug in the kerberos libs when 
692   dealing with empty passwords
693   this prompter is just a string copy ...
694 */
695 static krb5_error_code 
696 kerb_prompter(krb5_context ctx, void *data,
697                const char *name,
698                const char *banner,
699                int num_prompts,
700                krb5_prompt prompts[])
701 {
702         if (num_prompts == 0) return 0;
703
704         memset(prompts[0].reply->data, 0, prompts[0].reply->length);
705         if (prompts[0].reply->length > 0) {
706                 if (data) {
707                         strncpy((char *)prompts[0].reply->data,
708                                 (const char *)data,
709                                 prompts[0].reply->length-1);
710                         prompts[0].reply->length = strlen((const char *)prompts[0].reply->data);
711                 } else {
712                         prompts[0].reply->length = 0;
713                 }
714         }
715         return 0;
716 }
717
718 static ADS_STATUS ads_krb5_chg_password(const char *kdc_host,
719                                         const char *principal,
720                                         const char *oldpw, 
721                                         const char *newpw, 
722                                         int time_offset)
723 {
724     ADS_STATUS aret;
725     krb5_error_code ret;
726     krb5_context context = NULL;
727     krb5_principal princ;
728     krb5_get_init_creds_opt opts;
729     krb5_creds creds;
730     char *chpw_princ = NULL, *password;
731
732     initialize_krb5_error_table();
733     ret = krb5_init_context(&context);
734     if (ret) {
735         DEBUG(1,("Failed to init krb5 context (%s)\n", error_message(ret)));
736         return ADS_ERROR_KRB5(ret);
737     }
738
739     if ((ret = smb_krb5_parse_name(context, principal,
740                                     &princ))) {
741         krb5_free_context(context);
742         DEBUG(1,("Failed to parse %s (%s)\n", principal, error_message(ret)));
743         return ADS_ERROR_KRB5(ret);
744     }
745
746     krb5_get_init_creds_opt_init(&opts);
747     krb5_get_init_creds_opt_set_tkt_life(&opts, 5*60);
748     krb5_get_init_creds_opt_set_renew_life(&opts, 0);
749     krb5_get_init_creds_opt_set_forwardable(&opts, 0);
750     krb5_get_init_creds_opt_set_proxiable(&opts, 0);
751
752     /* We have to obtain an INITIAL changepw ticket for changing password */
753     if (asprintf(&chpw_princ, "kadmin/changepw@%s",
754                                 (char *) krb5_princ_realm(context, princ)) == -1) {
755         krb5_free_context(context);
756         DEBUG(1,("ads_krb5_chg_password: asprintf fail\n"));
757         return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
758     }
759
760     password = SMB_STRDUP(oldpw);
761     ret = krb5_get_init_creds_password(context, &creds, princ, password,
762                                            kerb_prompter, NULL, 
763                                            0, chpw_princ, &opts);
764     SAFE_FREE(chpw_princ);
765     SAFE_FREE(password);
766
767     if (ret) {
768       if (ret == KRB5KRB_AP_ERR_BAD_INTEGRITY)
769         DEBUG(1,("Password incorrect while getting initial ticket"));
770       else
771         DEBUG(1,("krb5_get_init_creds_password failed (%s)\n", error_message(ret)));
772
773         krb5_free_principal(context, princ);
774         krb5_free_context(context);
775         return ADS_ERROR_KRB5(ret);
776     }
777
778     aret = do_krb5_kpasswd_request(context, kdc_host,
779                                    KRB5_KPASSWD_VERS_CHANGEPW,
780                                    &creds, principal, newpw);
781
782     krb5_free_principal(context, princ);
783     krb5_free_context(context);
784
785     return aret;
786 }
787
788
789 ADS_STATUS kerberos_set_password(const char *kpasswd_server, 
790                                  const char *auth_principal, const char *auth_password,
791                                  const char *target_principal, const char *new_password,
792                                  int time_offset)
793 {
794     int ret;
795
796     if ((ret = kerberos_kinit_password(auth_principal, auth_password, time_offset, NULL))) {
797         DEBUG(1,("Failed kinit for principal %s (%s)\n", auth_principal, error_message(ret)));
798         return ADS_ERROR_KRB5(ret);
799     }
800
801     if (!strcmp(auth_principal, target_principal))
802         return ads_krb5_chg_password(kpasswd_server, target_principal,
803                                      auth_password, new_password, time_offset);
804     else
805         return ads_krb5_set_password(kpasswd_server, target_principal,
806                                      new_password, time_offset);
807 }
808
809
810 /**
811  * Set the machine account password
812  * @param ads connection to ads server
813  * @param hostname machine whose password is being set
814  * @param password new password
815  * @return status of password change
816  **/
817 ADS_STATUS ads_set_machine_password(ADS_STRUCT *ads,
818                                     const char *machine_account,
819                                     const char *password)
820 {
821         ADS_STATUS status;
822         char *principal = NULL; 
823
824         /*
825           we need to use the '$' form of the name here (the machine account name), 
826           as otherwise the server might end up setting the password for a user
827           instead
828          */
829         if (asprintf(&principal, "%s@%s", machine_account, ads->config.realm) < 0) {
830                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
831         }
832         
833         status = ads_krb5_set_password(ads->auth.kdc_server, principal, 
834                                        password, ads->auth.time_offset);
835         
836         SAFE_FREE(principal);
837         return status;
838 }
839 #endif