Specify event_context to ldb_wrap_connect explicitly.
[kai/samba.git] / source4 / kdc / kpasswdd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    kpasswd Server implementation
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7    Copyright (C) Andrew Tridgell        2005
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "smbd/service_task.h"
25 #include "lib/events/events.h"
26 #include "lib/socket/socket.h"
27 #include "kdc/kdc.h"
28 #include "system/network.h"
29 #include "lib/util/dlinklist.h"
30 #include "lib/ldb/include/ldb.h"
31 #include "heimdal/lib/krb5/krb5_locl.h"
32 #include "heimdal/lib/krb5/krb5-private.h"
33 #include "auth/gensec/gensec.h"
34 #include "auth/credentials/credentials.h"
35 #include "auth/credentials/credentials_krb5.h"
36 #include "auth/auth.h"
37 #include "dsdb/samdb/samdb.h"
38 #include "rpc_server/dcerpc_server.h"
39 #include "rpc_server/samr/proto.h"
40 #include "libcli/security/security.h"
41 #include "param/param.h"
42
43 /* hold information about one kdc socket */
44 struct kpasswd_socket {
45         struct socket_context *sock;
46         struct kdc_server *kdc;
47         struct fd_event *fde;
48
49         /* a queue of outgoing replies that have been deferred */
50         struct kdc_reply *send_queue;
51 };
52
53 /* Return true if there is a valid error packet formed in the error_blob */
54 static bool kpasswdd_make_error_reply(struct kdc_server *kdc, 
55                                      TALLOC_CTX *mem_ctx, 
56                                      uint16_t result_code, 
57                                      const char *error_string, 
58                                      DATA_BLOB *error_blob) 
59 {
60         char *error_string_utf8;
61         ssize_t len;
62         
63         DEBUG(result_code ? 3 : 10, ("kpasswdd: %s\n", error_string));
64
65         len = push_utf8_talloc(mem_ctx, lp_iconv_convenience(kdc->task->lp_ctx), &error_string_utf8, error_string);
66         if (len == -1) {
67                 return false;
68         }
69
70         *error_blob = data_blob_talloc(mem_ctx, NULL, 2 + len + 1);
71         if (!error_blob->data) {
72                 return false;
73         }
74         RSSVAL(error_blob->data, 0, result_code);
75         memcpy(error_blob->data + 2, error_string_utf8, len + 1);
76         return true;
77 }
78
79 /* Return true if there is a valid error packet formed in the error_blob */
80 static bool kpasswdd_make_unauth_error_reply(struct kdc_server *kdc, 
81                                             TALLOC_CTX *mem_ctx, 
82                                             uint16_t result_code, 
83                                             const char *error_string, 
84                                             DATA_BLOB *error_blob) 
85 {
86         bool ret;
87         int kret;
88         DATA_BLOB error_bytes;
89         krb5_data k5_error_bytes, k5_error_blob;
90         ret = kpasswdd_make_error_reply(kdc, mem_ctx, result_code, error_string, 
91                                        &error_bytes);
92         if (!ret) {
93                 return false;
94         }
95         k5_error_bytes.data = error_bytes.data;
96         k5_error_bytes.length = error_bytes.length;
97         kret = krb5_mk_error(kdc->smb_krb5_context->krb5_context,
98                              result_code, NULL, &k5_error_bytes, 
99                              NULL, NULL, NULL, NULL, &k5_error_blob);
100         if (kret) {
101                 return false;
102         }
103         *error_blob = data_blob_talloc(mem_ctx, k5_error_blob.data, k5_error_blob.length);
104         krb5_data_free(&k5_error_blob);
105         if (!error_blob->data) {
106                 return false;
107         }
108         return true;
109 }
110
111 static bool kpasswd_make_pwchange_reply(struct kdc_server *kdc, 
112                                         TALLOC_CTX *mem_ctx, 
113                                         NTSTATUS status, 
114                                         enum samr_RejectReason reject_reason,
115                                         struct samr_DomInfo1 *dominfo,
116                                         DATA_BLOB *error_blob) 
117 {
118         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
119                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
120                                                 KRB5_KPASSWD_ACCESSDENIED,
121                                                 "No such user when changing password",
122                                                 error_blob);
123         }
124         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
125                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
126                                                 KRB5_KPASSWD_ACCESSDENIED,
127                                                 "Not permitted to change password",
128                                                 error_blob);
129         }
130         if (dominfo && NT_STATUS_EQUAL(status, NT_STATUS_PASSWORD_RESTRICTION)) {
131                 const char *reject_string;
132                 switch (reject_reason) {
133                 case SAMR_REJECT_TOO_SHORT:
134                         reject_string = talloc_asprintf(mem_ctx, "Password too short, password must be at least %d characters long",
135                                                         dominfo->min_password_length);
136                         break;
137                 case SAMR_REJECT_COMPLEXITY:
138                         reject_string = "Password does not meet complexity requirements";
139                         break;
140                 case SAMR_REJECT_IN_HISTORY:
141                         reject_string = "Password is already in password history";
142                         break;
143                 case SAMR_REJECT_OTHER:
144                 default:
145                         reject_string = talloc_asprintf(mem_ctx, "Password must be at least %d characters long, and cannot match any of your %d previous passwords",
146                                                         dominfo->min_password_length, dominfo->password_history_length);
147                         break;
148                 }
149                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
150                                                 KRB5_KPASSWD_SOFTERROR,
151                                                 reject_string,
152                                                 error_blob);
153         }
154         if (!NT_STATUS_IS_OK(status)) {
155                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
156                                                  KRB5_KPASSWD_HARDERROR,
157                                                  talloc_asprintf(mem_ctx, "failed to set password: %s", nt_errstr(status)),
158                                                  error_blob);
159                 
160         }
161         return kpasswdd_make_error_reply(kdc, mem_ctx, KRB5_KPASSWD_SUCCESS,
162                                         "Password changed",
163                                         error_blob);
164 }
165
166 /* 
167    A user password change
168    
169    Return true if there is a valid error packet (or sucess) formed in
170    the error_blob
171 */
172 static bool kpasswdd_change_password(struct kdc_server *kdc,
173                                      TALLOC_CTX *mem_ctx, 
174                                      struct auth_session_info *session_info,
175                                      const char *password,
176                                      DATA_BLOB *reply)
177 {
178         NTSTATUS status;
179         enum samr_RejectReason reject_reason;
180         struct samr_DomInfo1 *dominfo;
181         struct ldb_context *samdb;
182
183         samdb = samdb_connect(mem_ctx, kdc->task->event_ctx, kdc->task->lp_ctx, system_session(mem_ctx, kdc->task->lp_ctx));
184         if (!samdb) {
185                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
186                                                 KRB5_KPASSWD_HARDERROR,
187                                                 "Failed to open samdb",
188                                                 reply);
189         }
190         
191         DEBUG(3, ("Changing password of %s\\%s (%s)\n", 
192                   session_info->server_info->domain_name,
193                   session_info->server_info->account_name,
194                   dom_sid_string(mem_ctx, session_info->security_token->user_sid)));
195
196         /* User password change */
197         status = samdb_set_password_sid(samdb, mem_ctx, 
198                                         session_info->security_token->user_sid,
199                                         password, NULL, NULL, 
200                                         true, /* this is a user password change */
201                                         &reject_reason,
202                                         &dominfo);
203         return kpasswd_make_pwchange_reply(kdc, mem_ctx, 
204                                            status, 
205                                            reject_reason,
206                                            dominfo, 
207                                            reply);
208
209 }
210
211 static bool kpasswd_process_request(struct kdc_server *kdc,
212                                     TALLOC_CTX *mem_ctx, 
213                                     struct gensec_security *gensec_security,
214                                     uint16_t version,
215                                     DATA_BLOB *input, 
216                                     DATA_BLOB *reply)
217 {
218         struct auth_session_info *session_info;
219         if (!NT_STATUS_IS_OK(gensec_session_info(gensec_security, 
220                                                  &session_info))) {
221                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
222                                                 KRB5_KPASSWD_HARDERROR,
223                                                 "gensec_session_info failed!",
224                                                 reply);
225         }
226
227         switch (version) {
228         case KRB5_KPASSWD_VERS_CHANGEPW:
229         {
230                 char *password = talloc_strndup(mem_ctx, (const char *)input->data, input->length);
231                 if (!password) {
232                         return false;
233                 }
234                 return kpasswdd_change_password(kdc, mem_ctx, session_info, 
235                                                 password, reply);
236                 break;
237         }
238         case KRB5_KPASSWD_VERS_SETPW:
239         {
240                 NTSTATUS status;
241                 enum samr_RejectReason reject_reason = SAMR_REJECT_OTHER;
242                 struct samr_DomInfo1 *dominfo = NULL;
243                 struct ldb_context *samdb;
244                 struct ldb_message *msg;
245                 krb5_context context = kdc->smb_krb5_context->krb5_context;
246
247                 ChangePasswdDataMS chpw;
248                 char *password;
249
250                 krb5_principal principal;
251                 char *set_password_on_princ;
252                 struct ldb_dn *set_password_on_dn;
253
254                 size_t len;
255                 int ret;
256
257                 msg = ldb_msg_new(mem_ctx);
258                 if (!msg) {
259                         return false;
260                 }
261
262                 ret = decode_ChangePasswdDataMS(input->data, input->length,
263                                                 &chpw, &len);
264                 if (ret) {
265                         return kpasswdd_make_error_reply(kdc, mem_ctx, 
266                                                         KRB5_KPASSWD_MALFORMED,
267                                                         "failed to decode password change structure",
268                                                         reply);
269                 }
270                 
271                 password = talloc_strndup(mem_ctx, 
272                                           (const char *)chpw.newpasswd.data, 
273                                           chpw.newpasswd.length);
274                 if (!password) {
275                         free_ChangePasswdDataMS(&chpw);
276                         return false;
277                 }
278                 if ((chpw.targname && !chpw.targrealm) 
279                     || (!chpw.targname && chpw.targrealm)) {
280                         return kpasswdd_make_error_reply(kdc, mem_ctx, 
281                                                         KRB5_KPASSWD_MALFORMED,
282                                                         "Realm and principal must be both present, or neither present",
283                                                         reply);
284                 }
285                 if (chpw.targname && chpw.targrealm) {
286                         if (_krb5_principalname2krb5_principal(kdc->smb_krb5_context->krb5_context,
287                                                                &principal, *chpw.targname, 
288                                                                *chpw.targrealm) != 0) {
289                                 free_ChangePasswdDataMS(&chpw);
290                                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
291                                                                 KRB5_KPASSWD_MALFORMED,
292                                                                 "failed to extract principal to set",
293                                                                 reply);
294                                 
295                         }
296                 } else {
297                         free_ChangePasswdDataMS(&chpw);
298                         return kpasswdd_change_password(kdc, mem_ctx, session_info, 
299                                                         password, reply);
300                 }
301                 free_ChangePasswdDataMS(&chpw);
302
303                 if (krb5_unparse_name(context, principal, &set_password_on_princ) != 0) {
304                         krb5_free_principal(context, principal);
305                         return kpasswdd_make_error_reply(kdc, mem_ctx, 
306                                                         KRB5_KPASSWD_MALFORMED,
307                                                         "krb5_unparse_name failed!",
308                                                         reply);
309                 }
310                 
311                 krb5_free_principal(context, principal);
312                 
313                 samdb = samdb_connect(mem_ctx, kdc->task->event_ctx, kdc->task->lp_ctx, session_info);
314                 if (!samdb) {
315                         return kpasswdd_make_error_reply(kdc, mem_ctx, 
316                                                          KRB5_KPASSWD_HARDERROR,
317                                                          "Unable to open database!",
318                                                          reply);
319                 }
320
321                 DEBUG(3, ("%s\\%s (%s) is changing password of %s\n", 
322                           session_info->server_info->domain_name,
323                           session_info->server_info->account_name,
324                           dom_sid_string(mem_ctx, session_info->security_token->user_sid), 
325                           set_password_on_princ));
326                 ret = ldb_transaction_start(samdb);
327                 if (ret) {
328                         status = NT_STATUS_TRANSACTION_ABORTED;
329                         return kpasswd_make_pwchange_reply(kdc, mem_ctx, 
330                                                            status,
331                                                            SAMR_REJECT_OTHER, 
332                                                            NULL, 
333                                                            reply);
334                 }
335
336                 status = crack_user_principal_name(samdb, mem_ctx, 
337                                                    set_password_on_princ, 
338                                                    &set_password_on_dn, NULL);
339                 free(set_password_on_princ);
340                 if (!NT_STATUS_IS_OK(status)) {
341                         ldb_transaction_cancel(samdb);
342                         return kpasswd_make_pwchange_reply(kdc, mem_ctx, 
343                                                            status,
344                                                            SAMR_REJECT_OTHER, 
345                                                            NULL, 
346                                                            reply);
347                 }
348
349                 msg = ldb_msg_new(mem_ctx);
350                 if (msg == NULL) {
351                         ldb_transaction_cancel(samdb);
352                         status = NT_STATUS_NO_MEMORY;
353                 } else {
354                         msg->dn = ldb_dn_copy(msg, set_password_on_dn);
355                         if (!msg->dn) {
356                                 status = NT_STATUS_NO_MEMORY;
357                         }
358                 }
359
360                 if (NT_STATUS_IS_OK(status)) {
361                         /* Admin password set */
362                         status = samdb_set_password(samdb, mem_ctx,
363                                                     set_password_on_dn, NULL,
364                                                     msg, password, NULL, NULL, 
365                                                     false, /* this is not a user password change */
366                                                     &reject_reason, &dominfo);
367                 }
368
369                 if (NT_STATUS_IS_OK(status)) {
370                         /* modify the samdb record */
371                         ret = samdb_replace(samdb, mem_ctx, msg);
372                         if (ret != 0) {
373                                 DEBUG(2,("Failed to modify record to set password on %s: %s\n",
374                                          ldb_dn_get_linearized(msg->dn),
375                                          ldb_errstring(samdb)));
376                                 status = NT_STATUS_ACCESS_DENIED;
377                         }
378                 }
379                 if (NT_STATUS_IS_OK(status)) {
380                         ret = ldb_transaction_commit(samdb);
381                         if (ret != 0) {
382                                 DEBUG(1,("Failed to commit transaction to set password on %s: %s\n",
383                                          ldb_dn_get_linearized(msg->dn),
384                                          ldb_errstring(samdb)));
385                                 status = NT_STATUS_TRANSACTION_ABORTED;
386                         }
387                 } else {
388                         ldb_transaction_cancel(samdb);
389                 }
390                 return kpasswd_make_pwchange_reply(kdc, mem_ctx, 
391                                                    status,
392                                                    reject_reason, 
393                                                    dominfo, 
394                                                    reply);
395         }
396         default:
397                 return kpasswdd_make_error_reply(kdc, mem_ctx, 
398                                                  KRB5_KPASSWD_BAD_VERSION,
399                                                  talloc_asprintf(mem_ctx, 
400                                                                  "Protocol version %u not supported", 
401                                                                  version),
402                                                  reply);
403         }
404         return true;
405 }
406
407 bool kpasswdd_process(struct kdc_server *kdc,
408                       TALLOC_CTX *mem_ctx, 
409                       DATA_BLOB *input, 
410                       DATA_BLOB *reply,
411                       struct socket_address *peer_addr,
412                       struct socket_address *my_addr,
413                       int datagram_reply)
414 {
415         bool ret;
416         const uint16_t header_len = 6;
417         uint16_t len;
418         uint16_t ap_req_len;
419         uint16_t krb_priv_len;
420         uint16_t version;
421         NTSTATUS nt_status;
422         DATA_BLOB ap_req, krb_priv_req;
423         DATA_BLOB krb_priv_rep = data_blob(NULL, 0);
424         DATA_BLOB ap_rep = data_blob(NULL, 0);
425         DATA_BLOB kpasswd_req, kpasswd_rep;
426         struct cli_credentials *server_credentials;
427         struct gensec_security *gensec_security;
428         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
429         
430         if (!tmp_ctx) {
431                 return false;
432         }
433
434         /* Be parinoid.  We need to ensure we don't just let the
435          * caller lead us into a buffer overflow */
436         if (input->length <= header_len) {
437                 talloc_free(tmp_ctx);
438                 return false;
439         }
440
441         len = RSVAL(input->data, 0);
442         if (input->length != len) {
443                 talloc_free(tmp_ctx);
444                 return false;
445         }
446
447         /* There are two different versions of this protocol so far,
448          * plus others in the standards pipe.  Fortunetly they all
449          * take a very similar framing */
450         version = RSVAL(input->data, 2);
451         ap_req_len = RSVAL(input->data, 4);
452         if ((ap_req_len >= len) || (ap_req_len + header_len) >= len) {
453                 talloc_free(tmp_ctx);
454                 return false;
455         }
456         
457         krb_priv_len = len - ap_req_len;
458         ap_req = data_blob_const(&input->data[header_len], ap_req_len);
459         krb_priv_req = data_blob_const(&input->data[header_len + ap_req_len], krb_priv_len);
460         
461         nt_status = gensec_server_start(tmp_ctx, kdc->task->event_ctx, kdc->task->lp_ctx, kdc->task->msg_ctx, &gensec_security);
462         if (!NT_STATUS_IS_OK(nt_status)) {
463                 talloc_free(tmp_ctx);
464                 return false;
465         }
466
467         server_credentials = cli_credentials_init(tmp_ctx);
468         if (!server_credentials) {
469                 DEBUG(1, ("Failed to init server credentials\n"));
470                 return false;
471         }
472
473         /* We want the credentials subsystem to use the krb5 context
474          * we already have, rather than a new context */        
475         cli_credentials_set_krb5_context(server_credentials, kdc->smb_krb5_context);
476         cli_credentials_set_conf(server_credentials, kdc->task->lp_ctx);
477         nt_status = cli_credentials_set_stored_principal(server_credentials, kdc->task->event_ctx, kdc->task->lp_ctx, "kadmin/changepw");
478         if (!NT_STATUS_IS_OK(nt_status)) {
479                 ret = kpasswdd_make_unauth_error_reply(kdc, mem_ctx, 
480                                                        KRB5_KPASSWD_HARDERROR,
481                                                        talloc_asprintf(mem_ctx, 
482                                                                        "Failed to obtain server credentials for kadmin/changepw: %s\n", 
483                                                                        nt_errstr(nt_status)),
484                                                        &krb_priv_rep);
485                 ap_rep.length = 0;
486                 if (ret) {
487                         goto reply;
488                 }
489                 talloc_free(tmp_ctx);
490                 return ret;
491         }
492         
493         nt_status = gensec_set_credentials(gensec_security, server_credentials);
494         if (!NT_STATUS_IS_OK(nt_status)) {
495                 talloc_free(tmp_ctx);
496                 return false;
497         }
498
499         /* The kerberos PRIV packets include these addresses.  MIT
500          * clients check that they are present */
501         nt_status = gensec_set_peer_addr(gensec_security, peer_addr);
502         if (!NT_STATUS_IS_OK(nt_status)) {
503                 talloc_free(tmp_ctx);
504                 return false;
505         }
506         nt_status = gensec_set_my_addr(gensec_security, my_addr);
507         if (!NT_STATUS_IS_OK(nt_status)) {
508                 talloc_free(tmp_ctx);
509                 return false;
510         }
511
512         /* We want the GENSEC wrap calls to generate PRIV tokens */
513         gensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL);
514
515         nt_status = gensec_start_mech_by_name(gensec_security, "krb5");
516         if (!NT_STATUS_IS_OK(nt_status)) {
517                 talloc_free(tmp_ctx);
518                 return false;
519         }
520
521         /* Accept the AP-REQ and generate teh AP-REP we need for the reply */
522         nt_status = gensec_update(gensec_security, tmp_ctx, ap_req, &ap_rep);
523         if (!NT_STATUS_IS_OK(nt_status) && !NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
524                 
525                 ret = kpasswdd_make_unauth_error_reply(kdc, mem_ctx, 
526                                                        KRB5_KPASSWD_HARDERROR,
527                                                        talloc_asprintf(mem_ctx, 
528                                                                        "gensec_update failed: %s", 
529                                                                        nt_errstr(nt_status)),
530                                                        &krb_priv_rep);
531                 ap_rep.length = 0;
532                 if (ret) {
533                         goto reply;
534                 }
535                 talloc_free(tmp_ctx);
536                 return ret;
537         }
538
539         /* Extract the data from the KRB-PRIV half of the message */
540         nt_status = gensec_unwrap(gensec_security, tmp_ctx, &krb_priv_req, &kpasswd_req);
541         if (!NT_STATUS_IS_OK(nt_status)) {
542                 ret = kpasswdd_make_unauth_error_reply(kdc, mem_ctx, 
543                                                        KRB5_KPASSWD_HARDERROR,
544                                                        talloc_asprintf(mem_ctx, 
545                                                                        "gensec_unwrap failed: %s", 
546                                                                        nt_errstr(nt_status)),
547                                                        &krb_priv_rep);
548                 ap_rep.length = 0;
549                 if (ret) {
550                         goto reply;
551                 }
552                 talloc_free(tmp_ctx);
553                 return ret;
554         }
555
556         /* Figure out something to do with it (probably changing a password...) */
557         ret = kpasswd_process_request(kdc, tmp_ctx, 
558                                       gensec_security, 
559                                       version, 
560                                       &kpasswd_req, &kpasswd_rep); 
561         if (!ret) {
562                 /* Argh! */
563                 return false;
564         }
565
566         /* And wrap up the reply: This ensures that the error message
567          * or success can be verified by the client */
568         nt_status = gensec_wrap(gensec_security, tmp_ctx, 
569                                 &kpasswd_rep, &krb_priv_rep);
570         if (!NT_STATUS_IS_OK(nt_status)) {
571                 ret = kpasswdd_make_unauth_error_reply(kdc, mem_ctx, 
572                                                        KRB5_KPASSWD_HARDERROR,
573                                                        talloc_asprintf(mem_ctx, 
574                                                                        "gensec_wrap failed: %s", 
575                                                                        nt_errstr(nt_status)),
576                                                        &krb_priv_rep);
577                 ap_rep.length = 0;
578                 if (ret) {
579                         goto reply;
580                 }
581                 talloc_free(tmp_ctx);
582                 return ret;
583         }
584         
585 reply:
586         *reply = data_blob_talloc(mem_ctx, NULL, krb_priv_rep.length + ap_rep.length + header_len);
587         if (!reply->data) {
588                 return false;
589         }
590
591         RSSVAL(reply->data, 0, reply->length);
592         RSSVAL(reply->data, 2, 1); /* This is a version 1 reply, MS change/set or otherwise */
593         RSSVAL(reply->data, 4, ap_rep.length);
594         memcpy(reply->data + header_len, 
595                ap_rep.data, 
596                ap_rep.length);
597         memcpy(reply->data + header_len + ap_rep.length, 
598                krb_priv_rep.data, 
599                krb_priv_rep.length);
600
601         talloc_free(tmp_ctx);
602         return ret;
603 }
604