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