LCOV - code coverage report
Current view: top level - source3/libads - ldap.c (source / functions) Hit Total Coverage
Test: coverage report for fix-15632 9995c5c2 Lines: 1029 2102 49.0 %
Date: 2024-04-13 12:30:31 Functions: 73 97 75.3 %

          Line data    Source code
       1             : /*
       2             :    Unix SMB/CIFS implementation.
       3             :    ads (active directory) utility library
       4             :    Copyright (C) Andrew Tridgell 2001
       5             :    Copyright (C) Remus Koos 2001
       6             :    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2002
       7             :    Copyright (C) Guenther Deschner 2005
       8             :    Copyright (C) Gerald Carter 2006
       9             : 
      10             :    This program is free software; you can redistribute it and/or modify
      11             :    it under the terms of the GNU General Public License as published by
      12             :    the Free Software Foundation; either version 3 of the License, or
      13             :    (at your option) any later version.
      14             : 
      15             :    This program is distributed in the hope that it will be useful,
      16             :    but WITHOUT ANY WARRANTY; without even the implied warranty of
      17             :    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      18             :    GNU General Public License for more details.
      19             : 
      20             :    You should have received a copy of the GNU General Public License
      21             :    along with this program.  If not, see <http://www.gnu.org/licenses/>.
      22             : */
      23             : 
      24             : #include "includes.h"
      25             : #include "ads.h"
      26             : #include "libads/sitename_cache.h"
      27             : #include "libads/cldap.h"
      28             : #include "../lib/tsocket/tsocket.h"
      29             : #include "../lib/addns/dnsquery.h"
      30             : #include "../libds/common/flags.h"
      31             : #include "smbldap.h"
      32             : #include "../libcli/security/security.h"
      33             : #include "../librpc/gen_ndr/netlogon.h"
      34             : #include "lib/param/loadparm.h"
      35             : #include "libsmb/namequery.h"
      36             : #include "../librpc/gen_ndr/ndr_ads.h"
      37             : 
      38             : #ifdef HAVE_LDAP
      39             : 
      40             : /**
      41             :  * @file ldap.c
      42             :  * @brief basic ldap client-side routines for ads server communications
      43             :  *
      44             :  * The routines contained here should do the necessary ldap calls for
      45             :  * ads setups.
      46             :  *
      47             :  * Important note: attribute names passed into ads_ routines must
      48             :  * already be in UTF-8 format.  We do not convert them because in almost
      49             :  * all cases, they are just ascii (which is represented with the same
      50             :  * codepoints in UTF-8).  This may have to change at some point
      51             :  **/
      52             : 
      53             : 
      54             : #define LDAP_SERVER_TREE_DELETE_OID     "1.2.840.113556.1.4.805"
      55             : 
      56             : static SIG_ATOMIC_T gotalarm;
      57             : 
      58             : /***************************************************************
      59             :  Signal function to tell us we timed out.
      60             : ****************************************************************/
      61             : 
      62           0 : static void gotalarm_sig(int signum)
      63             : {
      64           0 :         gotalarm = 1;
      65           0 : }
      66             : 
      67         327 :  LDAP *ldap_open_with_timeout(const char *server,
      68             :                               struct sockaddr_storage *ss,
      69             :                               int port, unsigned int to)
      70             : {
      71         327 :         LDAP *ldp = NULL;
      72           0 :         int ldap_err;
      73           0 :         char *uri;
      74             : 
      75         327 :         DEBUG(10, ("Opening connection to LDAP server '%s:%d', timeout "
      76             :                    "%u seconds\n", server, port, to));
      77             : 
      78         327 :         if (to) {
      79             :                 /* Setup timeout */
      80         327 :                 gotalarm = 0;
      81         327 :                 CatchSignal(SIGALRM, gotalarm_sig);
      82         327 :                 alarm(to);
      83             :                 /* End setup timeout. */
      84             :         }
      85             : 
      86         327 :         if ( strchr_m(server, ':') ) {
      87             :                 /* IPv6 URI */
      88           0 :                 uri = talloc_asprintf(talloc_tos(), "ldap://[%s]:%u", server, port);
      89             :         } else {
      90             :                 /* IPv4 URI */
      91         327 :                 uri = talloc_asprintf(talloc_tos(), "ldap://%s:%u", server, port);
      92             :         }
      93         327 :         if (uri == NULL) {
      94           0 :                 return NULL;
      95             :         }
      96             : 
      97             : #ifdef HAVE_LDAP_INIT_FD
      98             :         {
      99         327 :                 int fd = -1;
     100         327 :                 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
     101         327 :                 unsigned timeout_ms = 1000 * to;
     102             : 
     103         327 :                 status = open_socket_out(ss, port, timeout_ms, &fd);
     104         327 :                 if (!NT_STATUS_IS_OK(status)) {
     105           0 :                         DEBUG(3, ("open_socket_out: failed to open socket\n"));
     106           0 :                         return NULL;
     107             :                 }
     108             : 
     109             : /* define LDAP_PROTO_TCP from openldap.h if required */
     110             : #ifndef LDAP_PROTO_TCP
     111             : #define LDAP_PROTO_TCP 1
     112             : #endif
     113         327 :                 ldap_err = ldap_init_fd(fd, LDAP_PROTO_TCP, uri, &ldp);
     114             :         }
     115             : #elif defined(HAVE_LDAP_INITIALIZE)
     116             :         ldap_err = ldap_initialize(&ldp, uri);
     117             : #else
     118             :         ldp = ldap_open(server, port);
     119             :         if (ldp != NULL) {
     120             :                 ldap_err = LDAP_SUCCESS;
     121             :         } else {
     122             :                 ldap_err = LDAP_OTHER;
     123             :         }
     124             : #endif
     125         327 :         if (ldap_err != LDAP_SUCCESS) {
     126           0 :                 DEBUG(2,("Could not initialize connection for LDAP server '%s': %s\n",
     127             :                          uri, ldap_err2string(ldap_err)));
     128             :         } else {
     129         327 :                 DEBUG(10, ("Initialized connection for LDAP server '%s'\n", uri));
     130             :         }
     131             : 
     132         327 :         if (to) {
     133             :                 /* Teardown timeout. */
     134         327 :                 alarm(0);
     135         327 :                 CatchSignal(SIGALRM, SIG_IGN);
     136             :         }
     137             : 
     138         327 :         return ldp;
     139             : }
     140             : 
     141        1738 : static int ldap_search_with_timeout(LDAP *ld,
     142             :                                     LDAP_CONST char *base,
     143             :                                     int scope,
     144             :                                     LDAP_CONST char *filter,
     145             :                                     char **attrs,
     146             :                                     int attrsonly,
     147             :                                     LDAPControl **sctrls,
     148             :                                     LDAPControl **cctrls,
     149             :                                     int sizelimit,
     150             :                                     LDAPMessage **res )
     151             : {
     152        1738 :         int to = lp_ldap_timeout();
     153           0 :         struct timeval timeout;
     154        1738 :         struct timeval *timeout_ptr = NULL;
     155           0 :         int result;
     156             : 
     157             :         /* Setup timeout for the ldap_search_ext_s call - local and remote. */
     158        1738 :         gotalarm = 0;
     159             : 
     160        1738 :         if (to) {
     161        1738 :                 timeout.tv_sec = to;
     162        1738 :                 timeout.tv_usec = 0;
     163        1738 :                 timeout_ptr = &timeout;
     164             : 
     165             :                 /* Setup alarm timeout. */
     166        1738 :                 CatchSignal(SIGALRM, gotalarm_sig);
     167             :                 /* Make the alarm time one second beyond
     168             :                    the timeout we're setting for the
     169             :                    remote search timeout, to allow that
     170             :                    to fire in preference. */
     171        1738 :                 alarm(to+1);
     172             :                 /* End setup timeout. */
     173             :         }
     174             : 
     175             : 
     176        1738 :         result = ldap_search_ext_s(ld, base, scope, filter, attrs,
     177             :                                    attrsonly, sctrls, cctrls, timeout_ptr,
     178             :                                    sizelimit, res);
     179             : 
     180        1738 :         if (to) {
     181             :                 /* Teardown alarm timeout. */
     182        1738 :                 CatchSignal(SIGALRM, SIG_IGN);
     183        1738 :                 alarm(0);
     184             :         }
     185             : 
     186        1738 :         if (gotalarm != 0)
     187           0 :                 return LDAP_TIMELIMIT_EXCEEDED;
     188             : 
     189             :         /*
     190             :          * A bug in OpenLDAP means ldap_search_ext_s can return
     191             :          * LDAP_SUCCESS but with a NULL res pointer. Cope with
     192             :          * this. See bug #6279 for details. JRA.
     193             :          */
     194             : 
     195        1738 :         if (*res == NULL) {
     196           0 :                 return LDAP_TIMELIMIT_EXCEEDED;
     197             :         }
     198             : 
     199        1738 :         return result;
     200             : }
     201             : 
     202             : /**********************************************
     203             :  Do client and server sitename match ?
     204             : **********************************************/
     205             : 
     206           0 : bool ads_sitename_match(ADS_STRUCT *ads)
     207             : {
     208           0 :         if (ads->config.server_site_name == NULL &&
     209           0 :             ads->config.client_site_name == NULL ) {
     210           0 :                 DEBUG(10,("ads_sitename_match: both null\n"));
     211           0 :                 return True;
     212             :         }
     213           0 :         if (ads->config.server_site_name &&
     214           0 :             ads->config.client_site_name &&
     215           0 :             strequal(ads->config.server_site_name,
     216             :                      ads->config.client_site_name)) {
     217           0 :                 DEBUG(10,("ads_sitename_match: name %s match\n", ads->config.server_site_name));
     218           0 :                 return True;
     219             :         }
     220           0 :         DEBUG(10,("ads_sitename_match: no match between server: %s and client: %s\n",
     221             :                 ads->config.server_site_name ? ads->config.server_site_name : "NULL",
     222             :                 ads->config.client_site_name ? ads->config.client_site_name : "NULL"));
     223           0 :         return False;
     224             : }
     225             : 
     226             : /**********************************************
     227             :  Is this the closest DC ?
     228             : **********************************************/
     229             : 
     230         684 : bool ads_closest_dc(ADS_STRUCT *ads)
     231             : {
     232         684 :         if (ads->config.flags & NBT_SERVER_CLOSEST) {
     233         684 :                 DEBUG(10,("ads_closest_dc: NBT_SERVER_CLOSEST flag set\n"));
     234         684 :                 return True;
     235             :         }
     236             : 
     237             :         /* not sure if this can ever happen */
     238           0 :         if (ads_sitename_match(ads)) {
     239           0 :                 DEBUG(10,("ads_closest_dc: NBT_SERVER_CLOSEST flag not set but sites match\n"));
     240           0 :                 return True;
     241             :         }
     242             : 
     243           0 :         if (ads->config.client_site_name == NULL) {
     244           0 :                 DEBUG(10,("ads_closest_dc: client belongs to no site\n"));
     245           0 :                 return True;
     246             :         }
     247             : 
     248           0 :         DEBUG(10,("ads_closest_dc: %s is not the closest DC\n",
     249             :                 ads->config.ldap_server_name));
     250             : 
     251           0 :         return False;
     252             : }
     253             : 
     254         581 : static bool ads_fill_cldap_reply(ADS_STRUCT *ads,
     255             :                                  bool gc,
     256             :                                  const struct sockaddr_storage *ss,
     257             :                                  const struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply)
     258             : {
     259         581 :         TALLOC_CTX *frame = talloc_stackframe();
     260         581 :         bool ret = false;
     261           0 :         char addr[INET6_ADDRSTRLEN];
     262           0 :         ADS_STATUS status;
     263           0 :         char *dn;
     264             : 
     265         581 :         print_sockaddr(addr, sizeof(addr), ss);
     266             : 
     267             :         /* Check the CLDAP reply flags */
     268             : 
     269         581 :         if (!(cldap_reply->server_type & NBT_SERVER_LDAP)) {
     270           0 :                 DBG_WARNING("%s's CLDAP reply says it is not an LDAP server!\n",
     271             :                             addr);
     272           0 :                 ret = false;
     273           0 :                 goto out;
     274             :         }
     275             : 
     276             :         /* Fill in the ads->config values */
     277             : 
     278         581 :         ADS_TALLOC_CONST_FREE(ads->config.realm);
     279         581 :         ADS_TALLOC_CONST_FREE(ads->config.bind_path);
     280         581 :         ADS_TALLOC_CONST_FREE(ads->config.ldap_server_name);
     281         581 :         ADS_TALLOC_CONST_FREE(ads->config.server_site_name);
     282         581 :         ADS_TALLOC_CONST_FREE(ads->config.client_site_name);
     283         581 :         ADS_TALLOC_CONST_FREE(ads->server.workgroup);
     284             : 
     285         581 :         if (!check_cldap_reply_required_flags(cldap_reply->server_type,
     286             :                                               ads->config.flags)) {
     287           0 :                 ret = false;
     288           0 :                 goto out;
     289             :         }
     290             : 
     291        1162 :         ads->config.ldap_server_name = talloc_strdup(ads,
     292         581 :                                                      cldap_reply->pdc_dns_name);
     293         581 :         if (ads->config.ldap_server_name == NULL) {
     294           0 :                 DBG_WARNING("Out of memory\n");
     295           0 :                 ret = false;
     296           0 :                 goto out;
     297             :         }
     298             : 
     299        1162 :         ads->config.realm = talloc_asprintf_strupper_m(ads,
     300             :                                                        "%s",
     301         581 :                                                        cldap_reply->dns_domain);
     302         581 :         if (ads->config.realm == NULL) {
     303           0 :                 DBG_WARNING("Out of memory\n");
     304           0 :                 ret = false;
     305           0 :                 goto out;
     306             :         }
     307             : 
     308         581 :         status = ads_build_dn(ads->config.realm, ads, &dn);
     309         581 :         if (!ADS_ERR_OK(status)) {
     310           0 :                 DBG_DEBUG("Failed to build bind path: %s\n",
     311             :                           ads_errstr(status));
     312           0 :                 ret = false;
     313           0 :                 goto out;
     314             :         }
     315         581 :         ads->config.bind_path = dn;
     316             : 
     317         581 :         if (*cldap_reply->server_site) {
     318         581 :                 ads->config.server_site_name =
     319         581 :                         talloc_strdup(ads, cldap_reply->server_site);
     320         581 :                 if (ads->config.server_site_name == NULL) {
     321           0 :                         DBG_WARNING("Out of memory\n");
     322           0 :                         ret = false;
     323           0 :                         goto out;
     324             :                 }
     325             :         }
     326             : 
     327         581 :         if (*cldap_reply->client_site) {
     328         581 :                 ads->config.client_site_name =
     329         581 :                         talloc_strdup(ads, cldap_reply->client_site);
     330         581 :                 if (ads->config.client_site_name == NULL) {
     331           0 :                         DBG_WARNING("Out of memory\n");
     332           0 :                         ret = false;
     333           0 :                         goto out;
     334             :                 }
     335             :         }
     336             : 
     337         581 :         ads->server.workgroup = talloc_strdup(ads, cldap_reply->domain_name);
     338         581 :         if (ads->server.workgroup == NULL) {
     339           0 :                 DBG_WARNING("Out of memory\n");
     340           0 :                 ret = false;
     341           0 :                 goto out;
     342             :         }
     343             : 
     344         581 :         ads->ldap.port = gc ? LDAP_GC_PORT : LDAP_PORT;
     345         581 :         ads->ldap.ss = *ss;
     346             : 
     347             :         /* Store our site name. */
     348         581 :         sitename_store(cldap_reply->domain_name, cldap_reply->client_site);
     349         581 :         sitename_store(cldap_reply->dns_domain, cldap_reply->client_site);
     350             : 
     351             :         /* Leave this until last so that the flags are not clobbered */
     352         581 :         ads->config.flags = cldap_reply->server_type;
     353             : 
     354         581 :         ret = true;
     355             : 
     356         581 :  out:
     357             : 
     358         581 :         TALLOC_FREE(frame);
     359         581 :         return ret;
     360             : }
     361             : 
     362             : /*
     363             :   try a connection to a given ldap server, returning True and setting the servers IP
     364             :   in the ads struct if successful
     365             :  */
     366         331 : static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
     367             :                             struct sockaddr_storage *ss)
     368             : {
     369         331 :         struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply = {};
     370         331 :         TALLOC_CTX *frame = talloc_stackframe();
     371           0 :         bool ok;
     372         331 :         char addr[INET6_ADDRSTRLEN] = { 0, };
     373             : 
     374         331 :         if (ss == NULL) {
     375           0 :                 TALLOC_FREE(frame);
     376           0 :                 return false;
     377             :         }
     378             : 
     379         331 :         print_sockaddr(addr, sizeof(addr), ss);
     380             : 
     381         331 :         DBG_INFO("ads_try_connect: sending CLDAP request to %s (realm: %s)\n",
     382             :                  addr, ads->server.realm);
     383             : 
     384         331 :         ok = ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply);
     385         331 :         if (!ok) {
     386           0 :                 DBG_NOTICE("ads_cldap_netlogon_5(%s, %s) failed.\n",
     387             :                            addr, ads->server.realm);
     388           0 :                 TALLOC_FREE(frame);
     389           0 :                 return false;
     390             :         }
     391             : 
     392         331 :         ok = ads_fill_cldap_reply(ads, gc, ss, &cldap_reply);
     393         331 :         if (!ok) {
     394           0 :                 DBG_NOTICE("ads_fill_cldap_reply(%s, %s) failed.\n",
     395             :                            addr, ads->server.realm);
     396           0 :                 TALLOC_FREE(frame);
     397           0 :                 return false;
     398             :         }
     399             : 
     400         331 :         TALLOC_FREE(frame);
     401         331 :         return true;
     402             : }
     403             : 
     404             : /**********************************************************************
     405             :  send a cldap ping to list of servers, one at a time, until one of
     406             :  them answers it's an ldap server. Record success in the ADS_STRUCT.
     407             :  Take note of and update negative connection cache.
     408             : **********************************************************************/
     409             : 
     410         250 : static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,
     411             :                         const char *domain,
     412             :                         struct samba_sockaddr *sa_list,
     413             :                         size_t count)
     414             : {
     415         250 :         TALLOC_CTX *frame = talloc_stackframe();
     416         250 :         struct timeval endtime = timeval_current_ofs(MAX(3,lp_ldap_timeout()/2), 0);
     417         250 :         uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX;
     418         250 :         struct tsocket_address **ts_list = NULL;
     419         250 :         const struct tsocket_address * const *ts_list_const = NULL;
     420         250 :         struct samba_sockaddr **req_sa_list = NULL;
     421         250 :         struct netlogon_samlogon_response **responses = NULL;
     422         250 :         size_t num_requests = 0;
     423           0 :         NTSTATUS status;
     424           0 :         size_t i;
     425         250 :         bool ok = false;
     426           0 :         bool retry;
     427             : 
     428         250 :         ts_list = talloc_zero_array(frame,
     429             :                                     struct tsocket_address *,
     430             :                                     count);
     431         250 :         if (ts_list == NULL) {
     432           0 :                 TALLOC_FREE(frame);
     433           0 :                 return NT_STATUS_NO_MEMORY;
     434             :         }
     435             : 
     436         250 :         req_sa_list = talloc_zero_array(frame,
     437             :                                         struct samba_sockaddr *,
     438             :                                         count);
     439         250 :         if (req_sa_list == NULL) {
     440           0 :                 TALLOC_FREE(frame);
     441           0 :                 return NT_STATUS_NO_MEMORY;
     442             :         }
     443             : 
     444         250 : again:
     445             :         /*
     446             :          * The retry loop is bound by the timeout
     447             :          */
     448         250 :         retry = false;
     449         250 :         num_requests = 0;
     450             : 
     451         694 :         for (i = 0; i < count; i++) {
     452           0 :                 char server[INET6_ADDRSTRLEN];
     453           0 :                 int ret;
     454             : 
     455         444 :                 if (is_zero_addr(&sa_list[i].u.ss)) {
     456           0 :                         continue;
     457             :                 }
     458             : 
     459         444 :                 print_sockaddr(server, sizeof(server), &sa_list[i].u.ss);
     460             : 
     461         444 :                 status = check_negative_conn_cache(domain, server);
     462         444 :                 if (!NT_STATUS_IS_OK(status)) {
     463           0 :                         continue;
     464             :                 }
     465             : 
     466         444 :                 ret = tsocket_address_inet_from_strings(ts_list, "ip",
     467             :                                                         server, LDAP_PORT,
     468             :                                                         &ts_list[num_requests]);
     469         444 :                 if (ret != 0) {
     470           0 :                         status = map_nt_error_from_unix(errno);
     471           0 :                         DBG_WARNING("Failed to create tsocket_address for %s - %s\n",
     472             :                                     server, nt_errstr(status));
     473           0 :                         TALLOC_FREE(frame);
     474           0 :                         return status;
     475             :                 }
     476             : 
     477         444 :                 req_sa_list[num_requests] = &sa_list[i];
     478         444 :                 num_requests += 1;
     479             :         }
     480             : 
     481         250 :         DBG_DEBUG("Try to create %zu netlogon connections for domain '%s' "
     482             :                   "(provided count of addresses was %zu).\n",
     483             :                   num_requests,
     484             :                   domain,
     485             :                   count);
     486             : 
     487         250 :         if (num_requests == 0) {
     488           0 :                 status = NT_STATUS_NO_LOGON_SERVERS;
     489           0 :                 DBG_WARNING("domain[%s] num_requests[%zu] for count[%zu] - %s\n",
     490             :                             domain, num_requests, count, nt_errstr(status));
     491           0 :                 TALLOC_FREE(frame);
     492           0 :                 return status;
     493             :         }
     494             : 
     495         250 :         ts_list_const = (const struct tsocket_address * const *)ts_list;
     496             : 
     497         250 :         status = cldap_multi_netlogon(frame,
     498             :                                       ts_list_const, num_requests,
     499             :                                       ads->server.realm, NULL,
     500             :                                       nt_version,
     501             :                                       1, endtime, &responses);
     502         250 :         if (!NT_STATUS_IS_OK(status)) {
     503           0 :                 DBG_WARNING("cldap_multi_netlogon(realm=%s, num_requests=%zu) "
     504             :                             "for count[%zu] - %s\n",
     505             :                             ads->server.realm,
     506             :                             num_requests, count,
     507             :                             nt_errstr(status));
     508           0 :                 TALLOC_FREE(frame);
     509           0 :                 return NT_STATUS_NO_LOGON_SERVERS;
     510             :         }
     511             : 
     512         250 :         for (i = 0; i < num_requests; i++) {
     513         250 :                 struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply = NULL;
     514           0 :                 char server[INET6_ADDRSTRLEN];
     515             : 
     516         250 :                 if (responses[i] == NULL) {
     517           0 :                         continue;
     518             :                 }
     519             : 
     520         250 :                 print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
     521             : 
     522         250 :                 if (responses[i]->ntver != NETLOGON_NT_VERSION_5EX) {
     523           0 :                         DBG_NOTICE("realm=[%s] nt_version mismatch: 0x%08x for %s\n",
     524             :                                    ads->server.realm,
     525             :                                    responses[i]->ntver, server);
     526           0 :                         continue;
     527             :                 }
     528             : 
     529         250 :                 cldap_reply = &responses[i]->data.nt5_ex;
     530             : 
     531             :                 /* Returns ok only if it matches the correct server type */
     532         250 :                 ok = ads_fill_cldap_reply(ads,
     533             :                                           false,
     534         250 :                                           &req_sa_list[i]->u.ss,
     535             :                                           cldap_reply);
     536         250 :                 if (ok) {
     537         250 :                         DBG_DEBUG("realm[%s]: selected %s => %s\n",
     538             :                                   ads->server.realm,
     539             :                                   server, cldap_reply->pdc_dns_name);
     540         250 :                         if (CHECK_DEBUGLVL(DBGLVL_DEBUG)) {
     541           1 :                                 NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
     542             :                                                 cldap_reply);
     543             :                         }
     544         250 :                         TALLOC_FREE(frame);
     545         250 :                         return NT_STATUS_OK;
     546             :                 }
     547             : 
     548           0 :                 DBG_NOTICE("realm[%s] server %s %s - not usable\n",
     549             :                            ads->server.realm,
     550             :                            server, cldap_reply->pdc_dns_name);
     551           0 :                 if (CHECK_DEBUGLVL(DBGLVL_NOTICE)) {
     552           0 :                         NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
     553             :                                         cldap_reply);
     554             :                 }
     555           0 :                 add_failed_connection_entry(domain, server,
     556           0 :                                 NT_STATUS_CLIENT_SERVER_PARAMETERS_INVALID);
     557           0 :                 retry = true;
     558             :         }
     559             : 
     560           0 :         if (retry) {
     561           0 :                 bool expired;
     562             : 
     563           0 :                 expired = timeval_expired(&endtime);
     564           0 :                 if (!expired) {
     565           0 :                         goto again;
     566             :                 }
     567             :         }
     568             : 
     569             :         /* keep track of failures as all were not suitable */
     570           0 :         for (i = 0; i < num_requests; i++) {
     571           0 :                 char server[INET6_ADDRSTRLEN];
     572             : 
     573           0 :                 print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
     574             : 
     575           0 :                 add_failed_connection_entry(domain, server,
     576           0 :                                             NT_STATUS_UNSUCCESSFUL);
     577             :         }
     578             : 
     579           0 :         status = NT_STATUS_NO_LOGON_SERVERS;
     580           0 :         DBG_WARNING("realm[%s] no valid response "
     581             :                     "num_requests[%zu] for count[%zu] - %s\n",
     582             :                     ads->server.realm,
     583             :                     num_requests, count, nt_errstr(status));
     584           0 :         TALLOC_FREE(frame);
     585           0 :         return NT_STATUS_NO_LOGON_SERVERS;
     586             : }
     587             : 
     588             : /***************************************************************************
     589             :  resolve a name and perform an "ldap ping" using NetBIOS and related methods
     590             : ****************************************************************************/
     591             : 
     592           8 : static NTSTATUS resolve_and_ping_netbios(ADS_STRUCT *ads,
     593             :                                          const char *domain, const char *realm)
     594             : {
     595           0 :         size_t i;
     596           8 :         size_t count = 0;
     597           8 :         struct samba_sockaddr *sa_list = NULL;
     598           0 :         NTSTATUS status;
     599             : 
     600           8 :         DEBUG(6, ("resolve_and_ping_netbios: (cldap) looking for domain '%s'\n",
     601             :                   domain));
     602             : 
     603           8 :         status = get_sorted_dc_list(talloc_tos(),
     604             :                                 domain,
     605             :                                 NULL,
     606             :                                 &sa_list,
     607             :                                 &count,
     608             :                                 false);
     609           8 :         if (!NT_STATUS_IS_OK(status)) {
     610           0 :                 return status;
     611             :         }
     612             : 
     613             :         /* remove servers which are known to be dead based on
     614             :            the corresponding DNS method */
     615           8 :         if (*realm) {
     616           0 :                 for (i = 0; i < count; ++i) {
     617           0 :                         char server[INET6_ADDRSTRLEN];
     618             : 
     619           0 :                         print_sockaddr(server, sizeof(server), &sa_list[i].u.ss);
     620             : 
     621           0 :                         if(!NT_STATUS_IS_OK(
     622             :                                 check_negative_conn_cache(realm, server))) {
     623             :                                 /* Ensure we add the workgroup name for this
     624             :                                    IP address as negative too. */
     625           0 :                                 add_failed_connection_entry(
     626             :                                     domain, server,
     627           0 :                                     NT_STATUS_UNSUCCESSFUL);
     628             :                         }
     629             :                 }
     630             :         }
     631             : 
     632           8 :         status = cldap_ping_list(ads, domain, sa_list, count);
     633             : 
     634           8 :         TALLOC_FREE(sa_list);
     635             : 
     636           8 :         return status;
     637             : }
     638             : 
     639             : 
     640             : /**********************************************************************
     641             :  resolve a name and perform an "ldap ping" using DNS
     642             : **********************************************************************/
     643             : 
     644         242 : static NTSTATUS resolve_and_ping_dns(ADS_STRUCT *ads, const char *sitename,
     645             :                                      const char *realm)
     646             : {
     647         242 :         size_t count = 0;
     648         242 :         struct samba_sockaddr *sa_list = NULL;
     649           0 :         NTSTATUS status;
     650             : 
     651         242 :         DEBUG(6, ("resolve_and_ping_dns: (cldap) looking for realm '%s'\n",
     652             :                   realm));
     653             : 
     654         242 :         status = get_sorted_dc_list(talloc_tos(),
     655             :                                 realm,
     656             :                                 sitename,
     657             :                                 &sa_list,
     658             :                                 &count,
     659             :                                 true);
     660         242 :         if (!NT_STATUS_IS_OK(status)) {
     661           0 :                 TALLOC_FREE(sa_list);
     662           0 :                 return status;
     663             :         }
     664             : 
     665         242 :         status = cldap_ping_list(ads, realm, sa_list, count);
     666             : 
     667         242 :         TALLOC_FREE(sa_list);
     668             : 
     669         242 :         return status;
     670             : }
     671             : 
     672             : /**********************************************************************
     673             :  Try to find an AD dc using our internal name resolution routines
     674             :  Try the realm first and then the workgroup name if netbios is not
     675             :  disabled
     676             : **********************************************************************/
     677             : 
     678         400 : static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
     679             : {
     680         400 :         const char *c_domain = "";
     681           0 :         const char *c_realm;
     682         400 :         bool use_own_domain = False;
     683         400 :         char *sitename = NULL;
     684         400 :         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
     685         400 :         bool ok = false;
     686             : 
     687             :         /* if the realm and workgroup are both empty, assume they are ours */
     688             : 
     689             :         /* realm */
     690         400 :         c_realm = ads->server.realm;
     691             : 
     692         400 :         if (c_realm == NULL)
     693           8 :                 c_realm = "";
     694             : 
     695         400 :         if (!*c_realm) {
     696             :                 /* special case where no realm and no workgroup means our own */
     697           8 :                 if ( !ads->server.workgroup || !*ads->server.workgroup ) {
     698           0 :                         use_own_domain = True;
     699           0 :                         c_realm = lp_realm();
     700             :                 }
     701             :         }
     702             : 
     703         400 :         if (!lp_disable_netbios()) {
     704         400 :                 if (use_own_domain) {
     705           0 :                         c_domain = lp_workgroup();
     706             :                 } else {
     707         400 :                         c_domain = ads->server.workgroup;
     708         400 :                         if (!*c_realm && (!c_domain || !*c_domain)) {
     709           0 :                                 c_domain = lp_workgroup();
     710             :                         }
     711             :                 }
     712             : 
     713         400 :                 if (!c_domain) {
     714           0 :                         c_domain = "";
     715             :                 }
     716             :         }
     717             : 
     718         400 :         if (!*c_realm && !*c_domain) {
     719           0 :                 DEBUG(0, ("ads_find_dc: no realm or workgroup!  Don't know "
     720             :                           "what to do\n"));
     721           0 :                 return NT_STATUS_INVALID_PARAMETER; /* rather need MISSING_PARAMETER ... */
     722             :         }
     723             : 
     724             :         /*
     725             :          * In case of LDAP we use get_dc_name() as that
     726             :          * creates the custom krb5.conf file
     727             :          */
     728         400 :         if (!(ads->auth.flags & ADS_AUTH_NO_BIND)) {
     729           0 :                 fstring srv_name;
     730           0 :                 struct sockaddr_storage ip_out;
     731             : 
     732         150 :                 DEBUG(6, ("ads_find_dc: (ldap) looking for realm '%s'"
     733             :                           " and falling back to domain '%s'\n",
     734             :                           c_realm, c_domain));
     735             : 
     736         150 :                 ok = get_dc_name(c_domain, c_realm, srv_name, &ip_out);
     737         150 :                 if (ok) {
     738         150 :                         if (is_zero_addr(&ip_out)) {
     739           0 :                                 return NT_STATUS_NO_LOGON_SERVERS;
     740             :                         }
     741             : 
     742             :                         /*
     743             :                          * we call ads_try_connect() to fill in the
     744             :                          * ads->config details
     745             :                          */
     746         150 :                         ok = ads_try_connect(ads, false, &ip_out);
     747         150 :                         if (ok) {
     748         150 :                                 return NT_STATUS_OK;
     749             :                         }
     750             :                 }
     751             : 
     752           0 :                 return NT_STATUS_NO_LOGON_SERVERS;
     753             :         }
     754             : 
     755         250 :         if (*c_realm) {
     756         242 :                 sitename = sitename_fetch(talloc_tos(), c_realm);
     757         242 :                 status = resolve_and_ping_dns(ads, sitename, c_realm);
     758             : 
     759         242 :                 if (NT_STATUS_IS_OK(status)) {
     760         242 :                         TALLOC_FREE(sitename);
     761         242 :                         return status;
     762             :                 }
     763             : 
     764             :                 /* In case we failed to contact one of our closest DC on our
     765             :                  * site we
     766             :                  * need to try to find another DC, retry with a site-less SRV
     767             :                  * DNS query
     768             :                  * - Guenther */
     769             : 
     770           0 :                 if (sitename) {
     771           0 :                         DEBUG(3, ("ads_find_dc: failed to find a valid DC on "
     772             :                                   "our site (%s), Trying to find another DC "
     773             :                                   "for realm '%s' (domain '%s')\n",
     774             :                                   sitename, c_realm, c_domain));
     775           0 :                         namecache_delete(c_realm, 0x1C);
     776           0 :                         status =
     777           0 :                             resolve_and_ping_dns(ads, NULL, c_realm);
     778             : 
     779           0 :                         if (NT_STATUS_IS_OK(status)) {
     780           0 :                                 TALLOC_FREE(sitename);
     781           0 :                                 return status;
     782             :                         }
     783             :                 }
     784             : 
     785           0 :                 TALLOC_FREE(sitename);
     786             :         }
     787             : 
     788             :         /* try netbios as fallback - if permitted,
     789             :            or if configuration specifically requests it */
     790           8 :         if (*c_domain) {
     791           8 :                 if (*c_realm) {
     792           0 :                         DEBUG(3, ("ads_find_dc: falling back to netbios "
     793             :                                   "name resolution for domain '%s' (realm '%s')\n",
     794             :                                   c_domain, c_realm));
     795             :                 }
     796             : 
     797           8 :                 status = resolve_and_ping_netbios(ads, c_domain, c_realm);
     798           8 :                 if (NT_STATUS_IS_OK(status)) {
     799           8 :                         return status;
     800             :                 }
     801             :         }
     802             : 
     803           0 :         DEBUG(1, ("ads_find_dc: "
     804             :                   "name resolution for realm '%s' (domain '%s') failed: %s\n",
     805             :                   c_realm, c_domain, nt_errstr(status)));
     806           0 :         return status;
     807             : }
     808             : /**
     809             :  * Connect to the LDAP server
     810             :  * @param ads Pointer to an existing ADS_STRUCT
     811             :  * @return status of connection
     812             :  **/
     813         583 : ADS_STATUS ads_connect(ADS_STRUCT *ads)
     814             : {
     815         583 :         int version = LDAP_VERSION3;
     816           0 :         ADS_STATUS status;
     817           0 :         NTSTATUS ntstatus;
     818           0 :         char addr[INET6_ADDRSTRLEN];
     819           0 :         struct sockaddr_storage existing_ss;
     820             : 
     821         583 :         zero_sockaddr(&existing_ss);
     822             : 
     823             :         /*
     824             :          * ads_connect can be passed in a reused ADS_STRUCT
     825             :          * with an existing non-zero ads->ldap.ss IP address
     826             :          * that was stored by going through ads_find_dc()
     827             :          * if ads->server.ldap_server was NULL.
     828             :          *
     829             :          * If ads->server.ldap_server is still NULL but
     830             :          * the target address isn't the zero address, then
     831             :          * store that address off off before zeroing out
     832             :          * ads->ldap so we don't keep doing multiple calls
     833             :          * to ads_find_dc() in the reuse case.
     834             :          *
     835             :          * If a caller wants a clean ADS_STRUCT they
     836             :          * will TALLOC_FREE it and allocate a new one
     837             :          * by calling ads_init(), which ensures
     838             :          * ads->ldap.ss is a properly zero'ed out valid IP
     839             :          * address.
     840             :          */
     841         583 :         if (ads->server.ldap_server == NULL && !is_zero_addr(&ads->ldap.ss)) {
     842             :                 /* Save off the address we previously found by ads_find_dc(). */
     843          15 :                 existing_ss = ads->ldap.ss;
     844             :         }
     845             : 
     846         583 :         ads_zero_ldap(ads);
     847         583 :         ZERO_STRUCT(ads->ldap_wrap_data);
     848         583 :         ads->ldap.last_attempt       = time_mono(NULL);
     849         583 :         ads->ldap_wrap_data.wrap_type        = ADS_SASLWRAP_TYPE_PLAIN;
     850             : 
     851             :         /* try with a user specified server */
     852             : 
     853         583 :         if (DEBUGLEVEL >= 11) {
     854           0 :                 char *s = NDR_PRINT_STRUCT_STRING(talloc_tos(), ads_struct, ads);
     855           0 :                 DEBUG(11,("ads_connect: entering\n"));
     856           0 :                 DEBUGADD(11,("%s\n", s));
     857           0 :                 TALLOC_FREE(s);
     858             :         }
     859             : 
     860         583 :         if (ads->server.ldap_server) {
     861         168 :                 bool ok = false;
     862           0 :                 struct sockaddr_storage ss;
     863             : 
     864         168 :                 DBG_DEBUG("Resolving name of LDAP server '%s'.\n",
     865             :                           ads->server.ldap_server);
     866         168 :                 ok = resolve_name(ads->server.ldap_server, &ss, 0x20, true);
     867         168 :                 if (!ok) {
     868           2 :                         DEBUG(5,("ads_connect: unable to resolve name %s\n",
     869             :                                  ads->server.ldap_server));
     870           2 :                         status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
     871           2 :                         goto out;
     872             :                 }
     873             : 
     874         166 :                 if (is_zero_addr(&ss)) {
     875           0 :                         status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
     876           0 :                         goto out;
     877             :                 }
     878             : 
     879         166 :                 ok = ads_try_connect(ads, ads->server.gc, &ss);
     880         166 :                 if (ok) {
     881         166 :                         goto got_connection;
     882             :                 }
     883             : 
     884             :                 /* The choice of which GC use is handled one level up in
     885             :                    ads_connect_gc().  If we continue on from here with
     886             :                    ads_find_dc() we will get GC searches on port 389 which
     887             :                    doesn't work.   --jerry */
     888             : 
     889           0 :                 if (ads->server.gc == true) {
     890           0 :                         return ADS_ERROR(LDAP_OPERATIONS_ERROR);
     891             :                 }
     892             : 
     893           0 :                 if (ads->server.no_fallback) {
     894           0 :                         status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
     895           0 :                         goto out;
     896             :                 }
     897             :         }
     898             : 
     899         415 :         if (!is_zero_addr(&existing_ss)) {
     900             :                 /* We saved off who we should talk to. */
     901          15 :                 bool ok = ads_try_connect(ads,
     902          15 :                                           ads->server.gc,
     903             :                                           &existing_ss);
     904          15 :                 if (ok) {
     905          15 :                         goto got_connection;
     906             :                 }
     907             :                 /*
     908             :                  * Keep trying to find a server and fall through
     909             :                  * into ads_find_dc() again.
     910             :                  */
     911           0 :                 DBG_DEBUG("Failed to connect to DC via LDAP server IP address, "
     912             :                           "trying to find another DC.\n");
     913             :         }
     914             : 
     915         400 :         ntstatus = ads_find_dc(ads);
     916         400 :         if (NT_STATUS_IS_OK(ntstatus)) {
     917         400 :                 goto got_connection;
     918             :         }
     919             : 
     920           0 :         status = ADS_ERROR_NT(ntstatus);
     921           0 :         goto out;
     922             : 
     923         581 : got_connection:
     924             : 
     925         581 :         print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
     926         581 :         DEBUG(3,("Successfully contacted LDAP server %s\n", addr));
     927             : 
     928         581 :         if (!ads->auth.user_name) {
     929             :                 /* Must use the userPrincipalName value here or sAMAccountName
     930             :                    and not servicePrincipalName; found by Guenther Deschner */
     931         224 :                 ads->auth.user_name = talloc_asprintf(ads,
     932             :                                                       "%s$",
     933             :                                                       lp_netbios_name());
     934         224 :                 if (ads->auth.user_name == NULL) {
     935           0 :                         DBG_ERR("talloc_asprintf failed\n");
     936           0 :                         status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
     937           0 :                         goto out;
     938             :                 }
     939             :         }
     940             : 
     941         581 :         if (ads->auth.realm == NULL) {
     942         310 :                 ads->auth.realm = talloc_strdup(ads, ads->config.realm);
     943         310 :                 if (ads->auth.realm == NULL) {
     944           0 :                         status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
     945           0 :                         goto out;
     946             :                 }
     947             :         }
     948             : 
     949         581 :         if (!ads->auth.kdc_server) {
     950         566 :                 print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
     951         566 :                 ads->auth.kdc_server = talloc_strdup(ads, addr);
     952         566 :                 if (ads->auth.kdc_server == NULL) {
     953           0 :                         status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
     954           0 :                         goto out;
     955             :                 }
     956             :         }
     957             : 
     958             :         /* If the caller() requested no LDAP bind, then we are done */
     959             : 
     960         581 :         if (ads->auth.flags & ADS_AUTH_NO_BIND) {
     961         254 :                 status = ADS_SUCCESS;
     962         254 :                 goto out;
     963             :         }
     964             : 
     965         327 :         ads->ldap_wrap_data.mem_ctx = talloc_init("ads LDAP connection memory");
     966         327 :         if (!ads->ldap_wrap_data.mem_ctx) {
     967           0 :                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
     968           0 :                 goto out;
     969             :         }
     970             : 
     971             :         /* Otherwise setup the TCP LDAP session */
     972             : 
     973         327 :         ads->ldap.ld = ldap_open_with_timeout(ads->config.ldap_server_name,
     974             :                                               &ads->ldap.ss,
     975         327 :                                               ads->ldap.port, lp_ldap_timeout());
     976         327 :         if (ads->ldap.ld == NULL) {
     977           0 :                 status = ADS_ERROR(LDAP_OPERATIONS_ERROR);
     978           0 :                 goto out;
     979             :         }
     980         327 :         DEBUG(3,("Connected to LDAP server %s\n", ads->config.ldap_server_name));
     981             : 
     982             :         /* cache the successful connection for workgroup and realm */
     983         327 :         if (ads_closest_dc(ads)) {
     984         327 :                 saf_store( ads->server.workgroup, ads->config.ldap_server_name);
     985         327 :                 saf_store( ads->server.realm, ads->config.ldap_server_name);
     986             :         }
     987             : 
     988         327 :         ldap_set_option(ads->ldap.ld, LDAP_OPT_PROTOCOL_VERSION, &version);
     989             : 
     990             :         /* fill in the current time and offsets */
     991             : 
     992         327 :         status = ads_current_time( ads );
     993         327 :         if ( !ADS_ERR_OK(status) ) {
     994           0 :                 goto out;
     995             :         }
     996             : 
     997             :         /* Now do the bind */
     998             : 
     999         327 :         if (ads->auth.flags & ADS_AUTH_ANON_BIND) {
    1000          15 :                 status = ADS_ERROR(ldap_simple_bind_s(ads->ldap.ld, NULL, NULL));
    1001          15 :                 goto out;
    1002             :         }
    1003             : 
    1004         312 :         if (ads->auth.flags & ADS_AUTH_SIMPLE_BIND) {
    1005           0 :                 status = ADS_ERROR(ldap_simple_bind_s(ads->ldap.ld, ads->auth.user_name, ads->auth.password));
    1006           0 :                 goto out;
    1007             :         }
    1008             : 
    1009         312 :         status = ads_sasl_bind(ads);
    1010             : 
    1011         583 :  out:
    1012         583 :         if (DEBUGLEVEL >= 11) {
    1013           0 :                 char *s = NDR_PRINT_STRUCT_STRING(talloc_tos(), ads_struct, ads);
    1014           0 :                 DEBUG(11,("ads_connect: leaving with: %s\n",
    1015             :                         ads_errstr(status)));
    1016           0 :                 DEBUGADD(11,("%s\n", s));
    1017           0 :                 TALLOC_FREE(s);
    1018             :         }
    1019             : 
    1020         583 :         return status;
    1021             : }
    1022             : 
    1023             : /**
    1024             :  * Connect to the LDAP server using given credentials
    1025             :  * @param ads Pointer to an existing ADS_STRUCT
    1026             :  * @return status of connection
    1027             :  **/
    1028         150 : ADS_STATUS ads_connect_user_creds(ADS_STRUCT *ads)
    1029             : {
    1030         150 :         ads->auth.flags |= ADS_AUTH_USER_CREDS;
    1031             : 
    1032         150 :         return ads_connect(ads);
    1033             : }
    1034             : 
    1035             : /**
    1036             :  * Zero out the internal ads->ldap struct and initialize the address to zero IP.
    1037             :  * @param ads Pointer to an existing ADS_STRUCT
    1038             :  *
    1039             :  * Sets the ads->ldap.ss to a valid
    1040             :  * zero ip address that can be detected by
    1041             :  * our is_zero_addr() function. Otherwise
    1042             :  * it is left as AF_UNSPEC (0).
    1043             :  **/
    1044        1811 : void ads_zero_ldap(ADS_STRUCT *ads)
    1045             : {
    1046        1811 :         ZERO_STRUCT(ads->ldap);
    1047             :         /*
    1048             :          * Initialize the sockaddr_storage so we can use
    1049             :          * sockaddr test functions against it.
    1050             :          */
    1051        1811 :         zero_sockaddr(&ads->ldap.ss);
    1052        1811 : }
    1053             : 
    1054             : /**
    1055             :  * Disconnect the LDAP server
    1056             :  * @param ads Pointer to an existing ADS_STRUCT
    1057             :  **/
    1058         614 : void ads_disconnect(ADS_STRUCT *ads)
    1059             : {
    1060         614 :         if (ads->ldap.ld) {
    1061         327 :                 ldap_unbind(ads->ldap.ld);
    1062         327 :                 ads->ldap.ld = NULL;
    1063             :         }
    1064         614 :         if (ads->ldap_wrap_data.wrap_ops &&
    1065         307 :                 ads->ldap_wrap_data.wrap_ops->disconnect) {
    1066         307 :                 ads->ldap_wrap_data.wrap_ops->disconnect(&ads->ldap_wrap_data);
    1067             :         }
    1068         614 :         if (ads->ldap_wrap_data.mem_ctx) {
    1069         327 :                 talloc_free(ads->ldap_wrap_data.mem_ctx);
    1070             :         }
    1071         614 :         ads_zero_ldap(ads);
    1072         614 :         ZERO_STRUCT(ads->ldap_wrap_data);
    1073         614 : }
    1074             : 
    1075             : /*
    1076             :   Duplicate a struct berval into talloc'ed memory
    1077             :  */
    1078          60 : static struct berval *dup_berval(TALLOC_CTX *ctx, const struct berval *in_val)
    1079             : {
    1080           0 :         struct berval *value;
    1081             : 
    1082          60 :         if (!in_val) return NULL;
    1083             : 
    1084          60 :         value = talloc_zero(ctx, struct berval);
    1085          60 :         if (value == NULL)
    1086           0 :                 return NULL;
    1087          60 :         if (in_val->bv_len == 0) return value;
    1088             : 
    1089          60 :         value->bv_len = in_val->bv_len;
    1090          60 :         value->bv_val = (char *)talloc_memdup(ctx, in_val->bv_val,
    1091             :                                               in_val->bv_len);
    1092          60 :         return value;
    1093             : }
    1094             : 
    1095             : /*
    1096             :   Make a values list out of an array of (struct berval *)
    1097             :  */
    1098          60 : static struct berval **ads_dup_values(TALLOC_CTX *ctx,
    1099             :                                       const struct berval **in_vals)
    1100             : {
    1101           0 :         struct berval **values;
    1102           0 :         int i;
    1103             : 
    1104          60 :         if (!in_vals) return NULL;
    1105         120 :         for (i=0; in_vals[i]; i++)
    1106             :                 ; /* count values */
    1107          60 :         values = talloc_zero_array(ctx, struct berval *, i+1);
    1108          60 :         if (!values) return NULL;
    1109             : 
    1110         120 :         for (i=0; in_vals[i]; i++) {
    1111          60 :                 values[i] = dup_berval(ctx, in_vals[i]);
    1112             :         }
    1113          60 :         return values;
    1114             : }
    1115             : 
    1116             : /*
    1117             :   UTF8-encode a values list out of an array of (char *)
    1118             :  */
    1119         500 : static char **ads_push_strvals(TALLOC_CTX *ctx, const char **in_vals)
    1120             : {
    1121           0 :         char **values;
    1122           0 :         int i;
    1123           0 :         size_t size;
    1124             : 
    1125         500 :         if (!in_vals) return NULL;
    1126        1394 :         for (i=0; in_vals[i]; i++)
    1127             :                 ; /* count values */
    1128         500 :         values = talloc_zero_array(ctx, char *, i+1);
    1129         500 :         if (!values) return NULL;
    1130             : 
    1131        1394 :         for (i=0; in_vals[i]; i++) {
    1132         894 :                 if (!push_utf8_talloc(ctx, &values[i], in_vals[i], &size)) {
    1133           0 :                         TALLOC_FREE(values);
    1134           0 :                         return NULL;
    1135             :                 }
    1136             :         }
    1137         500 :         return values;
    1138             : }
    1139             : 
    1140             : /*
    1141             :   Pull a (char *) array out of a UTF8-encoded values list
    1142             :  */
    1143          71 : static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
    1144             : {
    1145           0 :         char **values;
    1146           0 :         int i;
    1147           0 :         size_t converted_size;
    1148             : 
    1149          71 :         if (!in_vals) return NULL;
    1150         218 :         for (i=0; in_vals[i]; i++)
    1151             :                 ; /* count values */
    1152          71 :         values = talloc_zero_array(ctx, char *, i+1);
    1153          71 :         if (!values) return NULL;
    1154             : 
    1155         218 :         for (i=0; in_vals[i]; i++) {
    1156         147 :                 if (!pull_utf8_talloc(ctx, &values[i], in_vals[i],
    1157             :                                       &converted_size)) {
    1158           0 :                         DEBUG(0,("ads_pull_strvals: pull_utf8_talloc failed: "
    1159             :                                  "%s\n", strerror(errno)));
    1160             :                 }
    1161             :         }
    1162          71 :         return values;
    1163             : }
    1164             : 
    1165             : /**
    1166             :  * Do a search with paged results.  cookie must be null on the first
    1167             :  *  call, and then returned on each subsequent call.  It will be null
    1168             :  *  again when the entire search is complete
    1169             :  * @param ads connection to ads server
    1170             :  * @param bind_path Base dn for the search
    1171             :  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
    1172             :  * @param expr Search expression - specified in local charset
    1173             :  * @param attrs Attributes to retrieve - specified in utf8 or ascii
    1174             :  * @param res ** which will contain results - free res* with ads_msgfree()
    1175             :  * @param count Number of entries retrieved on this page
    1176             :  * @param cookie The paged results cookie to be returned on subsequent calls
    1177             :  * @return status of search
    1178             :  **/
    1179          41 : static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
    1180             :                                            const char *bind_path,
    1181             :                                            int scope, const char *expr,
    1182             :                                            const char **attrs, void *args,
    1183             :                                            LDAPMessage **res,
    1184             :                                            int *count, struct berval **cookie)
    1185             : {
    1186           0 :         int rc, i, version;
    1187          41 :         char *utf8_expr, *utf8_path, **search_attrs = NULL;
    1188           0 :         size_t converted_size;
    1189           0 :         LDAPControl PagedResults, NoReferrals, ExternalCtrl, *controls[4], **rcontrols;
    1190          41 :         BerElement *cookie_be = NULL;
    1191          41 :         struct berval *cookie_bv= NULL;
    1192          41 :         BerElement *ext_be = NULL;
    1193          41 :         struct berval *ext_bv= NULL;
    1194             : 
    1195           0 :         TALLOC_CTX *ctx;
    1196          41 :         ads_control *external_control = (ads_control *) args;
    1197             : 
    1198          41 :         *res = NULL;
    1199             : 
    1200          41 :         if (!(ctx = talloc_init("ads_do_paged_search_args")))
    1201           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    1202             : 
    1203             :         /* 0 means the conversion worked but the result was empty
    1204             :            so we only fail if it's -1.  In any case, it always
    1205             :            at least nulls out the dest */
    1206          41 :         if (!push_utf8_talloc(ctx, &utf8_expr, expr, &converted_size) ||
    1207          41 :             !push_utf8_talloc(ctx, &utf8_path, bind_path, &converted_size))
    1208             :         {
    1209           0 :                 rc = LDAP_NO_MEMORY;
    1210           0 :                 goto done;
    1211             :         }
    1212             : 
    1213          41 :         if (!attrs || !(*attrs))
    1214           0 :                 search_attrs = NULL;
    1215             :         else {
    1216             :                 /* This would be the utf8-encoded version...*/
    1217             :                 /* if (!(search_attrs = ads_push_strvals(ctx, attrs))) */
    1218          41 :                 if (!(search_attrs = str_list_copy(talloc_tos(), attrs))) {
    1219           0 :                         rc = LDAP_NO_MEMORY;
    1220           0 :                         goto done;
    1221             :                 }
    1222             :         }
    1223             : 
    1224             :         /* Paged results only available on ldap v3 or later */
    1225          41 :         ldap_get_option(ads->ldap.ld, LDAP_OPT_PROTOCOL_VERSION, &version);
    1226          41 :         if (version < LDAP_VERSION3) {
    1227           0 :                 rc =  LDAP_NOT_SUPPORTED;
    1228           0 :                 goto done;
    1229             :         }
    1230             : 
    1231          41 :         cookie_be = ber_alloc_t(LBER_USE_DER);
    1232          41 :         if (*cookie) {
    1233           0 :                 ber_printf(cookie_be, "{iO}", (ber_int_t) ads->config.ldap_page_size, *cookie);
    1234           0 :                 ber_bvfree(*cookie); /* don't need it from last time */
    1235           0 :                 *cookie = NULL;
    1236             :         } else {
    1237          41 :                 ber_printf(cookie_be, "{io}", (ber_int_t) ads->config.ldap_page_size, "", 0);
    1238             :         }
    1239          41 :         ber_flatten(cookie_be, &cookie_bv);
    1240          41 :         PagedResults.ldctl_oid = discard_const_p(char, ADS_PAGE_CTL_OID);
    1241          41 :         PagedResults.ldctl_iscritical = (char) 1;
    1242          41 :         PagedResults.ldctl_value.bv_len = cookie_bv->bv_len;
    1243          41 :         PagedResults.ldctl_value.bv_val = cookie_bv->bv_val;
    1244             : 
    1245          41 :         NoReferrals.ldctl_oid = discard_const_p(char, ADS_NO_REFERRALS_OID);
    1246          41 :         NoReferrals.ldctl_iscritical = (char) 0;
    1247          41 :         NoReferrals.ldctl_value.bv_len = 0;
    1248          41 :         NoReferrals.ldctl_value.bv_val = discard_const_p(char, "");
    1249             : 
    1250          45 :         if (external_control &&
    1251           8 :             (strequal(external_control->control, ADS_EXTENDED_DN_OID) ||
    1252           4 :              strequal(external_control->control, ADS_SD_FLAGS_OID))) {
    1253             : 
    1254           4 :                 ExternalCtrl.ldctl_oid = discard_const_p(char, external_control->control);
    1255           4 :                 ExternalCtrl.ldctl_iscritical = (char) external_control->critical;
    1256             : 
    1257             :                 /* win2k does not accept a ldctl_value being passed in */
    1258             : 
    1259           4 :                 if (external_control->val != 0) {
    1260             : 
    1261           4 :                         if ((ext_be = ber_alloc_t(LBER_USE_DER)) == NULL ) {
    1262           0 :                                 rc = LDAP_NO_MEMORY;
    1263           0 :                                 goto done;
    1264             :                         }
    1265             : 
    1266           4 :                         if ((ber_printf(ext_be, "{i}", (ber_int_t) external_control->val)) == -1) {
    1267           0 :                                 rc = LDAP_NO_MEMORY;
    1268           0 :                                 goto done;
    1269             :                         }
    1270           4 :                         if ((ber_flatten(ext_be, &ext_bv)) == -1) {
    1271           0 :                                 rc = LDAP_NO_MEMORY;
    1272           0 :                                 goto done;
    1273             :                         }
    1274             : 
    1275           4 :                         ExternalCtrl.ldctl_value.bv_len = ext_bv->bv_len;
    1276           4 :                         ExternalCtrl.ldctl_value.bv_val = ext_bv->bv_val;
    1277             : 
    1278             :                 } else {
    1279           0 :                         ExternalCtrl.ldctl_value.bv_len = 0;
    1280           0 :                         ExternalCtrl.ldctl_value.bv_val = NULL;
    1281             :                 }
    1282             : 
    1283           4 :                 controls[0] = &NoReferrals;
    1284           4 :                 controls[1] = &PagedResults;
    1285           4 :                 controls[2] = &ExternalCtrl;
    1286           4 :                 controls[3] = NULL;
    1287             : 
    1288             :         } else {
    1289          37 :                 controls[0] = &NoReferrals;
    1290          37 :                 controls[1] = &PagedResults;
    1291          37 :                 controls[2] = NULL;
    1292             :         }
    1293             : 
    1294             :         /* we need to disable referrals as the openldap libs don't
    1295             :            handle them and paged results at the same time.  Using them
    1296             :            together results in the result record containing the server
    1297             :            page control being removed from the result list (tridge/jmcd)
    1298             : 
    1299             :            leaving this in despite the control that says don't generate
    1300             :            referrals, in case the server doesn't support it (jmcd)
    1301             :         */
    1302          41 :         ldap_set_option(ads->ldap.ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
    1303             : 
    1304          41 :         rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr,
    1305             :                                       search_attrs, 0, controls,
    1306             :                                       NULL, LDAP_NO_LIMIT,
    1307             :                                       (LDAPMessage **)res);
    1308             : 
    1309          41 :         ber_free(cookie_be, 1);
    1310          41 :         ber_bvfree(cookie_bv);
    1311             : 
    1312          41 :         if (rc) {
    1313           0 :                 DEBUG(3,("ads_do_paged_search_args: ldap_search_with_timeout(%s) -> %s\n", expr,
    1314             :                          ldap_err2string(rc)));
    1315           0 :                 if (rc == LDAP_OTHER) {
    1316           0 :                         char *ldap_errmsg;
    1317           0 :                         int ret;
    1318             : 
    1319           0 :                         ret = ldap_parse_result(ads->ldap.ld,
    1320             :                                                 *res,
    1321             :                                                 NULL,
    1322             :                                                 NULL,
    1323             :                                                 &ldap_errmsg,
    1324             :                                                 NULL,
    1325             :                                                 NULL,
    1326             :                                                 0);
    1327           0 :                         if (ret == LDAP_SUCCESS) {
    1328           0 :                                 DEBUG(3, ("ldap_search_with_timeout(%s) "
    1329             :                                           "error: %s\n", expr, ldap_errmsg));
    1330           0 :                                 ldap_memfree(ldap_errmsg);
    1331             :                         }
    1332             :                 }
    1333           0 :                 goto done;
    1334             :         }
    1335             : 
    1336          41 :         rc = ldap_parse_result(ads->ldap.ld, *res, NULL, NULL, NULL,
    1337             :                                         NULL, &rcontrols,  0);
    1338             : 
    1339          41 :         if (!rcontrols) {
    1340           0 :                 goto done;
    1341             :         }
    1342             : 
    1343          41 :         for (i=0; rcontrols[i]; i++) {
    1344          41 :                 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) == 0) {
    1345          41 :                         cookie_be = ber_init(&rcontrols[i]->ldctl_value);
    1346          41 :                         ber_scanf(cookie_be,"{iO}", (ber_int_t *) count,
    1347             :                                   &cookie_bv);
    1348             :                         /* the berval is the cookie, but must be freed when
    1349             :                            it is all done */
    1350          41 :                         if (cookie_bv->bv_len) /* still more to do */
    1351           0 :                                 *cookie=ber_bvdup(cookie_bv);
    1352             :                         else
    1353          41 :                                 *cookie=NULL;
    1354          41 :                         ber_bvfree(cookie_bv);
    1355          41 :                         ber_free(cookie_be, 1);
    1356          41 :                         break;
    1357             :                 }
    1358             :         }
    1359          41 :         ldap_controls_free(rcontrols);
    1360             : 
    1361          41 : done:
    1362          41 :         talloc_destroy(ctx);
    1363             : 
    1364          41 :         if (ext_be) {
    1365           4 :                 ber_free(ext_be, 1);
    1366             :         }
    1367             : 
    1368          41 :         if (ext_bv) {
    1369           4 :                 ber_bvfree(ext_bv);
    1370             :         }
    1371             : 
    1372          41 :         if (rc != LDAP_SUCCESS && *res != NULL) {
    1373           0 :                 ads_msgfree(ads, *res);
    1374           0 :                 *res = NULL;
    1375             :         }
    1376             : 
    1377             :         /* if/when we decide to utf8-encode attrs, take out this next line */
    1378          41 :         TALLOC_FREE(search_attrs);
    1379             : 
    1380          41 :         return ADS_ERROR(rc);
    1381             : }
    1382             : 
    1383           0 : static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
    1384             :                                       int scope, const char *expr,
    1385             :                                       const char **attrs, LDAPMessage **res,
    1386             :                                       int *count, struct berval **cookie)
    1387             : {
    1388           0 :         return ads_do_paged_search_args(ads, bind_path, scope, expr, attrs, NULL, res, count, cookie);
    1389             : }
    1390             : 
    1391             : 
    1392             : /**
    1393             :  * Get all results for a search.  This uses ads_do_paged_search() to return
    1394             :  * all entries in a large search.
    1395             :  * @param ads connection to ads server
    1396             :  * @param bind_path Base dn for the search
    1397             :  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
    1398             :  * @param expr Search expression
    1399             :  * @param attrs Attributes to retrieve
    1400             :  * @param res ** which will contain results - free res* with ads_msgfree()
    1401             :  * @return status of search
    1402             :  **/
    1403          41 :  ADS_STATUS ads_do_search_all_args(ADS_STRUCT *ads, const char *bind_path,
    1404             :                                    int scope, const char *expr,
    1405             :                                    const char **attrs, void *args,
    1406             :                                    LDAPMessage **res)
    1407             : {
    1408          41 :         struct berval *cookie = NULL;
    1409          41 :         int count = 0;
    1410           0 :         ADS_STATUS status;
    1411             : 
    1412          41 :         *res = NULL;
    1413          41 :         status = ads_do_paged_search_args(ads, bind_path, scope, expr, attrs, args, res,
    1414             :                                      &count, &cookie);
    1415             : 
    1416          41 :         if (!ADS_ERR_OK(status))
    1417           0 :                 return status;
    1418             : 
    1419             : #ifdef HAVE_LDAP_ADD_RESULT_ENTRY
    1420          41 :         while (cookie) {
    1421           0 :                 LDAPMessage *res2 = NULL;
    1422           0 :                 LDAPMessage *msg, *next;
    1423             : 
    1424           0 :                 status = ads_do_paged_search_args(ads, bind_path, scope, expr,
    1425             :                                               attrs, args, &res2, &count, &cookie);
    1426           0 :                 if (!ADS_ERR_OK(status)) {
    1427           0 :                         break;
    1428             :                 }
    1429             : 
    1430             :                 /* this relies on the way that ldap_add_result_entry() works internally. I hope
    1431             :                    that this works on all ldap libs, but I have only tested with openldap */
    1432           0 :                 for (msg = ads_first_message(ads, res2); msg; msg = next) {
    1433           0 :                         next = ads_next_message(ads, msg);
    1434           0 :                         ldap_add_result_entry((LDAPMessage **)res, msg);
    1435             :                 }
    1436             :                 /* note that we do not free res2, as the memory is now
    1437             :                    part of the main returned list */
    1438             :         }
    1439             : #else
    1440             :         DEBUG(0, ("no ldap_add_result_entry() support in LDAP libs!\n"));
    1441             :         status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
    1442             : #endif
    1443             : 
    1444          41 :         return status;
    1445             : }
    1446             : 
    1447           2 :  ADS_STATUS ads_do_search_all(ADS_STRUCT *ads, const char *bind_path,
    1448             :                               int scope, const char *expr,
    1449             :                               const char **attrs, LDAPMessage **res)
    1450             : {
    1451           2 :         return ads_do_search_all_args(ads, bind_path, scope, expr, attrs, NULL, res);
    1452             : }
    1453             : 
    1454           0 :  ADS_STATUS ads_do_search_all_sd_flags(ADS_STRUCT *ads, const char *bind_path,
    1455             :                                        int scope, const char *expr,
    1456             :                                        const char **attrs, uint32_t sd_flags,
    1457             :                                        LDAPMessage **res)
    1458             : {
    1459           0 :         ads_control args;
    1460             : 
    1461           0 :         args.control = ADS_SD_FLAGS_OID;
    1462           0 :         args.val = sd_flags;
    1463           0 :         args.critical = True;
    1464             : 
    1465           0 :         return ads_do_search_all_args(ads, bind_path, scope, expr, attrs, &args, res);
    1466             : }
    1467             : 
    1468             : 
    1469             : /**
    1470             :  * Run a function on all results for a search.  Uses ads_do_paged_search() and
    1471             :  *  runs the function as each page is returned, using ads_process_results()
    1472             :  * @param ads connection to ads server
    1473             :  * @param bind_path Base dn for the search
    1474             :  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
    1475             :  * @param expr Search expression - specified in local charset
    1476             :  * @param attrs Attributes to retrieve - specified in UTF-8 or ascii
    1477             :  * @param fn Function which takes attr name, values list, and data_area
    1478             :  * @param data_area Pointer which is passed to function on each call
    1479             :  * @return status of search
    1480             :  **/
    1481           0 : ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
    1482             :                                 int scope, const char *expr, const char **attrs,
    1483             :                                 bool (*fn)(ADS_STRUCT *, char *, void **, void *),
    1484             :                                 void *data_area)
    1485             : {
    1486           0 :         struct berval *cookie = NULL;
    1487           0 :         int count = 0;
    1488           0 :         ADS_STATUS status;
    1489           0 :         LDAPMessage *res;
    1490             : 
    1491           0 :         status = ads_do_paged_search(ads, bind_path, scope, expr, attrs, &res,
    1492             :                                      &count, &cookie);
    1493             : 
    1494           0 :         if (!ADS_ERR_OK(status)) return status;
    1495             : 
    1496           0 :         ads_process_results(ads, res, fn, data_area);
    1497           0 :         ads_msgfree(ads, res);
    1498             : 
    1499           0 :         while (cookie) {
    1500           0 :                 status = ads_do_paged_search(ads, bind_path, scope, expr, attrs,
    1501             :                                              &res, &count, &cookie);
    1502             : 
    1503           0 :                 if (!ADS_ERR_OK(status)) break;
    1504             : 
    1505           0 :                 ads_process_results(ads, res, fn, data_area);
    1506           0 :                 ads_msgfree(ads, res);
    1507             :         }
    1508             : 
    1509           0 :         return status;
    1510             : }
    1511             : 
    1512             : /**
    1513             :  * Do a search with a timeout.
    1514             :  * @param ads connection to ads server
    1515             :  * @param bind_path Base dn for the search
    1516             :  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
    1517             :  * @param expr Search expression
    1518             :  * @param attrs Attributes to retrieve
    1519             :  * @param res ** which will contain results - free res* with ads_msgfree()
    1520             :  * @return status of search
    1521             :  **/
    1522        1697 :  ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope,
    1523             :                           const char *expr,
    1524             :                           const char **attrs, LDAPMessage **res)
    1525             : {
    1526           0 :         int rc;
    1527        1697 :         char *utf8_expr, *utf8_path, **search_attrs = NULL;
    1528           0 :         size_t converted_size;
    1529           0 :         TALLOC_CTX *ctx;
    1530             : 
    1531        1697 :         *res = NULL;
    1532        1697 :         if (!(ctx = talloc_init("ads_do_search"))) {
    1533           0 :                 DEBUG(1,("ads_do_search: talloc_init() failed!\n"));
    1534           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    1535             :         }
    1536             : 
    1537             :         /* 0 means the conversion worked but the result was empty
    1538             :            so we only fail if it's negative.  In any case, it always
    1539             :            at least nulls out the dest */
    1540        1697 :         if (!push_utf8_talloc(ctx, &utf8_expr, expr, &converted_size) ||
    1541        1697 :             !push_utf8_talloc(ctx, &utf8_path, bind_path, &converted_size))
    1542             :         {
    1543           0 :                 DEBUG(1,("ads_do_search: push_utf8_talloc() failed!\n"));
    1544           0 :                 rc = LDAP_NO_MEMORY;
    1545           0 :                 goto done;
    1546             :         }
    1547             : 
    1548        1697 :         if (!attrs || !(*attrs))
    1549           0 :                 search_attrs = NULL;
    1550             :         else {
    1551             :                 /* This would be the utf8-encoded version...*/
    1552             :                 /* if (!(search_attrs = ads_push_strvals(ctx, attrs)))  */
    1553        1697 :                 if (!(search_attrs = str_list_copy(talloc_tos(), attrs)))
    1554             :                 {
    1555           0 :                         DEBUG(1,("ads_do_search: str_list_copy() failed!\n"));
    1556           0 :                         rc = LDAP_NO_MEMORY;
    1557           0 :                         goto done;
    1558             :                 }
    1559             :         }
    1560             : 
    1561             :         /* see the note in ads_do_paged_search - we *must* disable referrals */
    1562        1697 :         ldap_set_option(ads->ldap.ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
    1563             : 
    1564        1697 :         rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr,
    1565             :                                       search_attrs, 0, NULL, NULL,
    1566             :                                       LDAP_NO_LIMIT,
    1567             :                                       (LDAPMessage **)res);
    1568             : 
    1569        1697 :         if (rc == LDAP_SIZELIMIT_EXCEEDED) {
    1570           0 :                 DEBUG(3,("Warning! sizelimit exceeded in ldap. Truncating.\n"));
    1571           0 :                 rc = 0;
    1572             :         }
    1573             : 
    1574        1697 :  done:
    1575        1697 :         talloc_destroy(ctx);
    1576             :         /* if/when we decide to utf8-encode attrs, take out this next line */
    1577        1697 :         TALLOC_FREE(search_attrs);
    1578        1697 :         return ADS_ERROR(rc);
    1579             : }
    1580             : /**
    1581             :  * Do a general ADS search
    1582             :  * @param ads connection to ads server
    1583             :  * @param res ** which will contain results - free res* with ads_msgfree()
    1584             :  * @param expr Search expression
    1585             :  * @param attrs Attributes to retrieve
    1586             :  * @return status of search
    1587             :  **/
    1588         756 :  ADS_STATUS ads_search(ADS_STRUCT *ads, LDAPMessage **res,
    1589             :                        const char *expr, const char **attrs)
    1590             : {
    1591         756 :         return ads_do_search(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE,
    1592             :                              expr, attrs, res);
    1593             : }
    1594             : 
    1595             : /**
    1596             :  * Do a search on a specific DistinguishedName
    1597             :  * @param ads connection to ads server
    1598             :  * @param res ** which will contain results - free res* with ads_msgfree()
    1599             :  * @param dn DistinguishedName to search
    1600             :  * @param attrs Attributes to retrieve
    1601             :  * @return status of search
    1602             :  **/
    1603         132 :  ADS_STATUS ads_search_dn(ADS_STRUCT *ads, LDAPMessage **res,
    1604             :                           const char *dn, const char **attrs)
    1605             : {
    1606         132 :         return ads_do_search(ads, dn, LDAP_SCOPE_BASE, "(objectclass=*)",
    1607             :                              attrs, res);
    1608             : }
    1609             : 
    1610             : /**
    1611             :  * Free up memory from a ads_search
    1612             :  * @param ads connection to ads server
    1613             :  * @param msg Search results to free
    1614             :  **/
    1615        1361 :  void ads_msgfree(ADS_STRUCT *ads, LDAPMessage *msg)
    1616             : {
    1617        1361 :         if (!msg) return;
    1618        1360 :         ldap_msgfree(msg);
    1619             : }
    1620             : 
    1621             : /**
    1622             :  * Get a dn from search results
    1623             :  * @param ads connection to ads server
    1624             :  * @param msg Search result
    1625             :  * @return dn string
    1626             :  **/
    1627         364 :  char *ads_get_dn(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, LDAPMessage *msg)
    1628             : {
    1629           0 :         char *utf8_dn, *unix_dn;
    1630           0 :         size_t converted_size;
    1631             : 
    1632         364 :         utf8_dn = ldap_get_dn(ads->ldap.ld, msg);
    1633             : 
    1634         364 :         if (!utf8_dn) {
    1635           0 :                 DEBUG (5, ("ads_get_dn: ldap_get_dn failed\n"));
    1636           0 :                 return NULL;
    1637             :         }
    1638             : 
    1639         364 :         if (!pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn, &converted_size)) {
    1640           0 :                 DEBUG(0,("ads_get_dn: string conversion failure utf8 [%s]\n",
    1641             :                         utf8_dn ));
    1642           0 :                 return NULL;
    1643             :         }
    1644         364 :         ldap_memfree(utf8_dn);
    1645         364 :         return unix_dn;
    1646             : }
    1647             : 
    1648             : /**
    1649             :  * Get the parent from a dn
    1650             :  * @param dn the dn to return the parent from
    1651             :  * @return parent dn string
    1652             :  **/
    1653          30 : char *ads_parent_dn(const char *dn)
    1654             : {
    1655           0 :         char *p;
    1656             : 
    1657          30 :         if (dn == NULL) {
    1658           0 :                 return NULL;
    1659             :         }
    1660             : 
    1661          30 :         p = strchr(dn, ',');
    1662             : 
    1663          30 :         if (p == NULL) {
    1664           0 :                 return NULL;
    1665             :         }
    1666             : 
    1667          30 :         return p+1;
    1668             : }
    1669             : 
    1670             : /**
    1671             :  * Find a machine account given a hostname
    1672             :  * @param ads connection to ads server
    1673             :  * @param res ** which will contain results - free res* with ads_msgfree()
    1674             :  * @param host Hostname to search for
    1675             :  * @return status of search
    1676             :  **/
    1677         674 :  ADS_STATUS ads_find_machine_acct(ADS_STRUCT *ads, LDAPMessage **res,
    1678             :                                   const char *machine)
    1679             : {
    1680           0 :         ADS_STATUS status;
    1681           0 :         char *expr;
    1682         674 :         const char *attrs[] = {
    1683             :                 /* This is how Windows checks for machine accounts */
    1684             :                 "objectClass",
    1685             :                 "SamAccountName",
    1686             :                 "userAccountControl",
    1687             :                 "DnsHostName",
    1688             :                 "ServicePrincipalName",
    1689             :                 "userPrincipalName",
    1690             :                 "unicodePwd",
    1691             : 
    1692             :                 /* Additional attributes Samba checks */
    1693             :                 "msDS-AdditionalDnsHostName",
    1694             :                 "msDS-SupportedEncryptionTypes",
    1695             :                 "nTSecurityDescriptor",
    1696             :                 "objectSid",
    1697             : 
    1698             :                 NULL
    1699             :         };
    1700         674 :         TALLOC_CTX *frame = talloc_stackframe();
    1701             : 
    1702         674 :         *res = NULL;
    1703             : 
    1704             :         /* the easiest way to find a machine account anywhere in the tree
    1705             :            is to look for hostname$ */
    1706         674 :         expr = talloc_asprintf(frame, "(samAccountName=%s$)", machine);
    1707         674 :         if (expr == NULL) {
    1708           0 :                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1709           0 :                 goto done;
    1710             :         }
    1711             : 
    1712         674 :         status = ads_search(ads, res, expr, attrs);
    1713         674 :         if (ADS_ERR_OK(status)) {
    1714         674 :                 if (ads_count_replies(ads, *res) != 1) {
    1715          88 :                         status = ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
    1716             :                 }
    1717             :         }
    1718             : 
    1719         586 : done:
    1720         674 :         TALLOC_FREE(frame);
    1721         674 :         return status;
    1722             : }
    1723             : 
    1724             : /**
    1725             :  * Initialize a list of mods to be used in a modify request
    1726             :  * @param ctx An initialized TALLOC_CTX
    1727             :  * @return allocated ADS_MODLIST
    1728             :  **/
    1729         194 : ADS_MODLIST ads_init_mods(TALLOC_CTX *ctx)
    1730             : {
    1731             : #define ADS_MODLIST_ALLOC_SIZE 10
    1732           0 :         LDAPMod **mods;
    1733             : 
    1734         194 :         if ((mods = talloc_zero_array(ctx, LDAPMod *, ADS_MODLIST_ALLOC_SIZE + 1)))
    1735             :                 /* -1 is safety to make sure we don't go over the end.
    1736             :                    need to reset it to NULL before doing ldap modify */
    1737         194 :                 mods[ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
    1738             : 
    1739         194 :         return (ADS_MODLIST)mods;
    1740             : }
    1741             : 
    1742             : 
    1743             : /*
    1744             :   add an attribute to the list, with values list already constructed
    1745             : */
    1746         560 : static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1747             :                                   int mod_op, const char *name,
    1748             :                                   const void *_invals)
    1749             : {
    1750           0 :         int curmod;
    1751         560 :         LDAPMod **modlist = (LDAPMod **) *mods;
    1752         560 :         struct berval **ber_values = NULL;
    1753         560 :         char **char_values = NULL;
    1754             : 
    1755         560 :         if (!_invals) {
    1756           0 :                 mod_op = LDAP_MOD_DELETE;
    1757             :         } else {
    1758         560 :                 if (mod_op & LDAP_MOD_BVALUES) {
    1759           0 :                         const struct berval **b;
    1760          60 :                         b = discard_const_p(const struct berval *, _invals);
    1761          60 :                         ber_values = ads_dup_values(ctx, b);
    1762             :                 } else {
    1763           0 :                         const char **c;
    1764         500 :                         c = discard_const_p(const char *, _invals);
    1765         500 :                         char_values = ads_push_strvals(ctx, c);
    1766             :                 }
    1767             :         }
    1768             : 
    1769             :         /* find the first empty slot */
    1770        1548 :         for (curmod=0; modlist[curmod] && modlist[curmod] != (LDAPMod *) -1;
    1771         988 :              curmod++);
    1772         560 :         if (modlist[curmod] == (LDAPMod *) -1) {
    1773           0 :                 if (!(modlist = talloc_realloc(ctx, modlist, LDAPMod *,
    1774             :                                 curmod+ADS_MODLIST_ALLOC_SIZE+1)))
    1775           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    1776           0 :                 memset(&modlist[curmod], 0,
    1777             :                        ADS_MODLIST_ALLOC_SIZE*sizeof(LDAPMod *));
    1778           0 :                 modlist[curmod+ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
    1779           0 :                 *mods = (ADS_MODLIST)modlist;
    1780             :         }
    1781             : 
    1782         560 :         if (!(modlist[curmod] = talloc_zero(ctx, LDAPMod)))
    1783           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    1784         560 :         modlist[curmod]->mod_type = talloc_strdup(ctx, name);
    1785         560 :         if (mod_op & LDAP_MOD_BVALUES) {
    1786          60 :                 modlist[curmod]->mod_bvalues = ber_values;
    1787         500 :         } else if (mod_op & LDAP_MOD_DELETE) {
    1788           0 :                 modlist[curmod]->mod_values = NULL;
    1789             :         } else {
    1790         500 :                 modlist[curmod]->mod_values = char_values;
    1791             :         }
    1792             : 
    1793         560 :         modlist[curmod]->mod_op = mod_op;
    1794         560 :         return ADS_ERROR(LDAP_SUCCESS);
    1795             : }
    1796             : 
    1797             : /**
    1798             :  * Add a single string value to a mod list
    1799             :  * @param ctx An initialized TALLOC_CTX
    1800             :  * @param mods An initialized ADS_MODLIST
    1801             :  * @param name The attribute name to add
    1802             :  * @param val The value to add - NULL means DELETE
    1803             :  * @return ADS STATUS indicating success of add
    1804             :  **/
    1805         372 : ADS_STATUS ads_mod_str(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1806             :                        const char *name, const char *val)
    1807             : {
    1808           0 :         const char *values[2];
    1809             : 
    1810         372 :         values[0] = val;
    1811         372 :         values[1] = NULL;
    1812             : 
    1813         372 :         if (!val)
    1814           0 :                 return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
    1815         372 :         return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE, name, values);
    1816             : }
    1817             : 
    1818             : /**
    1819             :  * Add an array of string values to a mod list
    1820             :  * @param ctx An initialized TALLOC_CTX
    1821             :  * @param mods An initialized ADS_MODLIST
    1822             :  * @param name The attribute name to add
    1823             :  * @param vals The array of string values to add - NULL means DELETE
    1824             :  * @return ADS STATUS indicating success of add
    1825             :  **/
    1826         124 : ADS_STATUS ads_mod_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1827             :                            const char *name, const char **vals)
    1828             : {
    1829         124 :         if (!vals)
    1830           0 :                 return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
    1831         124 :         return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE,
    1832             :                                name, (const void **) vals);
    1833             : }
    1834             : 
    1835             : /**
    1836             :  * Add a single ber-encoded value to a mod list
    1837             :  * @param ctx An initialized TALLOC_CTX
    1838             :  * @param mods An initialized ADS_MODLIST
    1839             :  * @param name The attribute name to add
    1840             :  * @param val The value to add - NULL means DELETE
    1841             :  * @return ADS STATUS indicating success of add
    1842             :  **/
    1843          60 : static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1844             :                               const char *name, const struct berval *val)
    1845             : {
    1846           0 :         const struct berval *values[2];
    1847             : 
    1848          60 :         values[0] = val;
    1849          60 :         values[1] = NULL;
    1850          60 :         if (!val)
    1851           0 :                 return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
    1852          60 :         return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE|LDAP_MOD_BVALUES,
    1853             :                                name, (const void **) values);
    1854             : }
    1855             : 
    1856         198 : static void ads_print_error(int ret, LDAP *ld)
    1857             : {
    1858         198 :         if (ret != 0) {
    1859           0 :                 char *ld_error = NULL;
    1860           0 :                 ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &ld_error);
    1861           0 :                 DBG_ERR("AD LDAP ERROR: %d (%s): %s\n",
    1862             :                         ret,
    1863             :                         ldap_err2string(ret),
    1864             :                         ld_error);
    1865           0 :                 SAFE_FREE(ld_error);
    1866             :         }
    1867         198 : }
    1868             : 
    1869             : /**
    1870             :  * Perform an ldap modify
    1871             :  * @param ads connection to ads server
    1872             :  * @param mod_dn DistinguishedName to modify
    1873             :  * @param mods list of modifications to perform
    1874             :  * @return status of modify
    1875             :  **/
    1876         134 : ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
    1877             : {
    1878           0 :         int ret,i;
    1879         134 :         char *utf8_dn = NULL;
    1880           0 :         size_t converted_size;
    1881             :         /*
    1882             :            this control is needed to modify that contains a currently
    1883             :            non-existent attribute (but allowable for the object) to run
    1884             :         */
    1885         134 :         LDAPControl PermitModify = {
    1886             :                 discard_const_p(char, ADS_PERMIT_MODIFY_OID),
    1887             :                 {0, NULL},
    1888             :                 (char) 1};
    1889           0 :         LDAPControl *controls[2];
    1890             : 
    1891         134 :         DBG_INFO("AD LDAP: Modifying %s\n", mod_dn);
    1892             : 
    1893         134 :         controls[0] = &PermitModify;
    1894         134 :         controls[1] = NULL;
    1895             : 
    1896         134 :         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, mod_dn, &converted_size)) {
    1897           0 :                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1898             :         }
    1899             : 
    1900             :         /* find the end of the list, marked by NULL or -1 */
    1901         330 :         for(i=0;(mods[i]!=0)&&(mods[i]!=(LDAPMod *) -1);i++);
    1902             :         /* make sure the end of the list is NULL */
    1903         134 :         mods[i] = NULL;
    1904         134 :         ret = ldap_modify_ext_s(ads->ldap.ld, utf8_dn,
    1905             :                                 (LDAPMod **) mods, controls, NULL);
    1906         134 :         ads_print_error(ret, ads->ldap.ld);
    1907         134 :         TALLOC_FREE(utf8_dn);
    1908         134 :         return ADS_ERROR(ret);
    1909             : }
    1910             : 
    1911             : /**
    1912             :  * Perform an ldap add
    1913             :  * @param ads connection to ads server
    1914             :  * @param new_dn DistinguishedName to add
    1915             :  * @param mods list of attributes and values for DN
    1916             :  * @return status of add
    1917             :  **/
    1918          60 : ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
    1919             : {
    1920           0 :         int ret, i;
    1921          60 :         char *utf8_dn = NULL;
    1922           0 :         size_t converted_size;
    1923             : 
    1924          60 :         DBG_INFO("AD LDAP: Adding %s\n", new_dn);
    1925             : 
    1926          60 :         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, new_dn, &converted_size)) {
    1927           0 :                 DEBUG(1, ("ads_gen_add: push_utf8_talloc failed!\n"));
    1928           0 :                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1929             :         }
    1930             : 
    1931             :         /* find the end of the list, marked by NULL or -1 */
    1932         424 :         for(i=0;(mods[i]!=0)&&(mods[i]!=(LDAPMod *) -1);i++);
    1933             :         /* make sure the end of the list is NULL */
    1934          60 :         mods[i] = NULL;
    1935             : 
    1936          60 :         ret = ldap_add_ext_s(ads->ldap.ld, utf8_dn, (LDAPMod**)mods, NULL, NULL);
    1937          60 :         ads_print_error(ret, ads->ldap.ld);
    1938          60 :         TALLOC_FREE(utf8_dn);
    1939          60 :         return ADS_ERROR(ret);
    1940             : }
    1941             : 
    1942             : /**
    1943             :  * Delete a DistinguishedName
    1944             :  * @param ads connection to ads server
    1945             :  * @param new_dn DistinguishedName to delete
    1946             :  * @return status of delete
    1947             :  **/
    1948           4 : ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
    1949             : {
    1950           0 :         int ret;
    1951           4 :         char *utf8_dn = NULL;
    1952           0 :         size_t converted_size;
    1953           4 :         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, del_dn, &converted_size)) {
    1954           0 :                 DEBUG(1, ("ads_del_dn: push_utf8_talloc failed!\n"));
    1955           0 :                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1956             :         }
    1957             : 
    1958           4 :         DBG_INFO("AD LDAP: Deleting %s\n", del_dn);
    1959             : 
    1960           4 :         ret = ldap_delete_s(ads->ldap.ld, utf8_dn);
    1961           4 :         ads_print_error(ret, ads->ldap.ld);
    1962           4 :         TALLOC_FREE(utf8_dn);
    1963           4 :         return ADS_ERROR(ret);
    1964             : }
    1965             : 
    1966             : /**
    1967             :  * Build an org unit string
    1968             :  *  if org unit is Computers or blank then assume a container, otherwise
    1969             :  *  assume a / separated list of organisational units.
    1970             :  * jmcd: '\' is now used for escapes so certain chars can be in the ou (e.g. #)
    1971             :  * @param ads connection to ads server
    1972             :  * @param org_unit Organizational unit
    1973             :  * @return org unit string - caller must free
    1974             :  **/
    1975          60 : char *ads_ou_string(ADS_STRUCT *ads, const char *org_unit)
    1976             : {
    1977           0 :         ADS_STATUS status;
    1978          60 :         char *ret = NULL;
    1979          60 :         char *dn = NULL;
    1980             : 
    1981          60 :         if (!org_unit || !*org_unit) {
    1982             : 
    1983          58 :                 ret = ads_default_ou_string(ads, DS_GUID_COMPUTERS_CONTAINER);
    1984             : 
    1985             :                 /* samba4 might not yet respond to a wellknownobject-query */
    1986          58 :                 return ret ? ret : SMB_STRDUP("cn=Computers");
    1987             :         }
    1988             : 
    1989           2 :         if (strequal(org_unit, "Computers")) {
    1990           0 :                 return SMB_STRDUP("cn=Computers");
    1991             :         }
    1992             : 
    1993             :         /* jmcd: removed "\\" from the separation chars, because it is
    1994             :            needed as an escape for chars like '#' which are valid in an
    1995             :            OU name */
    1996           2 :         status = ads_build_path(org_unit, "/", "ou=", 1, &dn);
    1997           2 :         if (!ADS_ERR_OK(status)) {
    1998           0 :                 return NULL;
    1999             :         }
    2000             : 
    2001           2 :         return dn;
    2002             : }
    2003             : 
    2004             : /**
    2005             :  * Get a org unit string for a well-known GUID
    2006             :  * @param ads connection to ads server
    2007             :  * @param wknguid Well known GUID
    2008             :  * @return org unit string - caller must free
    2009             :  **/
    2010          62 : char *ads_default_ou_string(ADS_STRUCT *ads, const char *wknguid)
    2011             : {
    2012           0 :         ADS_STATUS status;
    2013          62 :         LDAPMessage *res = NULL;
    2014          62 :         char *base, *wkn_dn = NULL, *ret = NULL, **wkn_dn_exp = NULL,
    2015          62 :                 **bind_dn_exp = NULL;
    2016          62 :         const char *attrs[] = {"distinguishedName", NULL};
    2017           0 :         int new_ln, wkn_ln, bind_ln, i;
    2018             : 
    2019          62 :         if (wknguid == NULL) {
    2020           0 :                 return NULL;
    2021             :         }
    2022             : 
    2023          62 :         if (asprintf(&base, "<WKGUID=%s,%s>", wknguid, ads->config.bind_path ) == -1) {
    2024           0 :                 DEBUG(1, ("asprintf failed!\n"));
    2025           0 :                 return NULL;
    2026             :         }
    2027             : 
    2028          62 :         status = ads_search_dn(ads, &res, base, attrs);
    2029          62 :         if (!ADS_ERR_OK(status)) {
    2030           0 :                 DEBUG(1,("Failed while searching for: %s\n", base));
    2031           0 :                 goto out;
    2032             :         }
    2033             : 
    2034          62 :         if (ads_count_replies(ads, res) != 1) {
    2035           0 :                 goto out;
    2036             :         }
    2037             : 
    2038             :         /* substitute the bind-path from the well-known-guid-search result */
    2039          62 :         wkn_dn = ads_get_dn(ads, talloc_tos(), res);
    2040          62 :         if (!wkn_dn) {
    2041           0 :                 goto out;
    2042             :         }
    2043             : 
    2044          62 :         wkn_dn_exp = ldap_explode_dn(wkn_dn, 0);
    2045          62 :         if (!wkn_dn_exp) {
    2046           0 :                 goto out;
    2047             :         }
    2048             : 
    2049          62 :         bind_dn_exp = ldap_explode_dn(ads->config.bind_path, 0);
    2050          62 :         if (!bind_dn_exp) {
    2051           0 :                 goto out;
    2052             :         }
    2053             : 
    2054         362 :         for (wkn_ln=0; wkn_dn_exp[wkn_ln]; wkn_ln++)
    2055             :                 ;
    2056         300 :         for (bind_ln=0; bind_dn_exp[bind_ln]; bind_ln++)
    2057             :                 ;
    2058             : 
    2059          62 :         new_ln = wkn_ln - bind_ln;
    2060             : 
    2061          62 :         ret = SMB_STRDUP(wkn_dn_exp[0]);
    2062          62 :         if (!ret) {
    2063           0 :                 goto out;
    2064             :         }
    2065             : 
    2066          62 :         for (i=1; i < new_ln; i++) {
    2067           0 :                 char *s = NULL;
    2068             : 
    2069           0 :                 if (asprintf(&s, "%s,%s", ret, wkn_dn_exp[i]) == -1) {
    2070           0 :                         SAFE_FREE(ret);
    2071           0 :                         goto out;
    2072             :                 }
    2073             : 
    2074           0 :                 SAFE_FREE(ret);
    2075           0 :                 ret = SMB_STRDUP(s);
    2076           0 :                 free(s);
    2077           0 :                 if (!ret) {
    2078           0 :                         goto out;
    2079             :                 }
    2080             :         }
    2081             : 
    2082          62 :  out:
    2083          62 :         SAFE_FREE(base);
    2084          62 :         ads_msgfree(ads, res);
    2085          62 :         TALLOC_FREE(wkn_dn);
    2086          62 :         if (wkn_dn_exp) {
    2087          62 :                 ldap_value_free(wkn_dn_exp);
    2088             :         }
    2089          62 :         if (bind_dn_exp) {
    2090          62 :                 ldap_value_free(bind_dn_exp);
    2091             :         }
    2092             : 
    2093          62 :         return ret;
    2094             : }
    2095             : 
    2096             : /**
    2097             :  * Adds (appends) an item to an attribute array, rather then
    2098             :  * replacing the whole list
    2099             :  * @param ctx An initialized TALLOC_CTX
    2100             :  * @param mods An initialized ADS_MODLIST
    2101             :  * @param name name of the ldap attribute to append to
    2102             :  * @param vals an array of values to add
    2103             :  * @return status of addition
    2104             :  **/
    2105             : 
    2106           4 : ADS_STATUS ads_add_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    2107             :                                 const char *name, const char **vals)
    2108             : {
    2109           4 :         return ads_modlist_add(ctx, mods, LDAP_MOD_ADD, name,
    2110             :                                (const void *) vals);
    2111             : }
    2112             : 
    2113             : /**
    2114             :  * Determines the an account's current KVNO via an LDAP lookup
    2115             :  * @param ads An initialized ADS_STRUCT
    2116             :  * @param account_name the NT samaccountname.
    2117             :  * @return the kvno for the account, or -1 in case of a failure.
    2118             :  **/
    2119             : 
    2120          74 : uint32_t ads_get_kvno(ADS_STRUCT *ads, const char *account_name)
    2121             : {
    2122          74 :         LDAPMessage *res = NULL;
    2123          74 :         uint32_t kvno = (uint32_t)-1;      /* -1 indicates a failure */
    2124           0 :         char *filter;
    2125          74 :         const char *attrs[] = {"msDS-KeyVersionNumber", NULL};
    2126          74 :         char *dn_string = NULL;
    2127           0 :         ADS_STATUS ret;
    2128             : 
    2129          74 :         DEBUG(5,("ads_get_kvno: Searching for account %s\n", account_name));
    2130          74 :         if (asprintf(&filter, "(samAccountName=%s)", account_name) == -1) {
    2131           0 :                 return kvno;
    2132             :         }
    2133          74 :         ret = ads_search(ads, &res, filter, attrs);
    2134          74 :         SAFE_FREE(filter);
    2135          74 :         if (!ADS_ERR_OK(ret) || (ads_count_replies(ads, res) != 1)) {
    2136           0 :                 DEBUG(1,("ads_get_kvno: Account for %s not found.\n", account_name));
    2137           0 :                 ads_msgfree(ads, res);
    2138           0 :                 return kvno;
    2139             :         }
    2140             : 
    2141          74 :         dn_string = ads_get_dn(ads, talloc_tos(), res);
    2142          74 :         if (!dn_string) {
    2143           0 :                 DEBUG(0,("ads_get_kvno: out of memory.\n"));
    2144           0 :                 ads_msgfree(ads, res);
    2145           0 :                 return kvno;
    2146             :         }
    2147          74 :         DEBUG(5,("ads_get_kvno: Using: %s\n", dn_string));
    2148          74 :         TALLOC_FREE(dn_string);
    2149             : 
    2150             :         /* ---------------------------------------------------------
    2151             :          * 0 is returned as a default KVNO from this point on...
    2152             :          * This is done because Windows 2000 does not support key
    2153             :          * version numbers.  Chances are that a failure in the next
    2154             :          * step is simply due to Windows 2000 being used for a
    2155             :          * domain controller. */
    2156          74 :         kvno = 0;
    2157             : 
    2158          74 :         if (!ads_pull_uint32(ads, res, "msDS-KeyVersionNumber", &kvno)) {
    2159           0 :                 DEBUG(3,("ads_get_kvno: Error Determining KVNO!\n"));
    2160           0 :                 DEBUG(3,("ads_get_kvno: Windows 2000 does not support KVNO's, so this may be normal.\n"));
    2161           0 :                 ads_msgfree(ads, res);
    2162           0 :                 return kvno;
    2163             :         }
    2164             : 
    2165             :         /* Success */
    2166          74 :         DEBUG(5,("ads_get_kvno: Looked Up KVNO of: %d\n", kvno));
    2167          74 :         ads_msgfree(ads, res);
    2168          74 :         return kvno;
    2169             : }
    2170             : 
    2171             : /**
    2172             :  * Determines the computer account's current KVNO via an LDAP lookup
    2173             :  * @param ads An initialized ADS_STRUCT
    2174             :  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
    2175             :  * @return the kvno for the computer account, or -1 in case of a failure.
    2176             :  **/
    2177             : 
    2178          74 : uint32_t ads_get_machine_kvno(ADS_STRUCT *ads, const char *machine_name)
    2179             : {
    2180          74 :         char *computer_account = NULL;
    2181          74 :         uint32_t kvno = -1;
    2182             : 
    2183          74 :         if (asprintf(&computer_account, "%s$", machine_name) < 0) {
    2184           0 :                 return kvno;
    2185             :         }
    2186             : 
    2187          74 :         kvno = ads_get_kvno(ads, computer_account);
    2188          74 :         free(computer_account);
    2189             : 
    2190          74 :         return kvno;
    2191             : }
    2192             : 
    2193             : /**
    2194             :  * This clears out all registered spn's for a given hostname
    2195             :  * @param ads An initialized ADS_STRUCT
    2196             :  * @param machine_name the NetBIOS name of the computer.
    2197             :  * @return 0 upon success, non-zero otherwise.
    2198             :  **/
    2199             : 
    2200           0 : ADS_STATUS ads_clear_service_principal_names(ADS_STRUCT *ads, const char *machine_name)
    2201             : {
    2202           0 :         TALLOC_CTX *ctx;
    2203           0 :         LDAPMessage *res = NULL;
    2204           0 :         ADS_MODLIST mods;
    2205           0 :         const char *servicePrincipalName[1] = {NULL};
    2206           0 :         ADS_STATUS ret;
    2207           0 :         char *dn_string = NULL;
    2208             : 
    2209           0 :         ret = ads_find_machine_acct(ads, &res, machine_name);
    2210           0 :         if (!ADS_ERR_OK(ret)) {
    2211           0 :                 DEBUG(5,("ads_clear_service_principal_names: WARNING: Host Account for %s not found... skipping operation.\n", machine_name));
    2212           0 :                 DEBUG(5,("ads_clear_service_principal_names: WARNING: Service Principals for %s have NOT been cleared.\n", machine_name));
    2213           0 :                 ads_msgfree(ads, res);
    2214           0 :                 return ret;
    2215             :         }
    2216             : 
    2217           0 :         DEBUG(5,("ads_clear_service_principal_names: Host account for %s found\n", machine_name));
    2218           0 :         ctx = talloc_init("ads_clear_service_principal_names");
    2219           0 :         if (!ctx) {
    2220           0 :                 ads_msgfree(ads, res);
    2221           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2222             :         }
    2223             : 
    2224           0 :         if (!(mods = ads_init_mods(ctx))) {
    2225           0 :                 talloc_destroy(ctx);
    2226           0 :                 ads_msgfree(ads, res);
    2227           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2228             :         }
    2229           0 :         ret = ads_mod_strlist(ctx, &mods, "servicePrincipalName", servicePrincipalName);
    2230           0 :         if (!ADS_ERR_OK(ret)) {
    2231           0 :                 DEBUG(1,("ads_clear_service_principal_names: Error creating strlist.\n"));
    2232           0 :                 ads_msgfree(ads, res);
    2233           0 :                 talloc_destroy(ctx);
    2234           0 :                 return ret;
    2235             :         }
    2236           0 :         dn_string = ads_get_dn(ads, talloc_tos(), res);
    2237           0 :         if (!dn_string) {
    2238           0 :                 talloc_destroy(ctx);
    2239           0 :                 ads_msgfree(ads, res);
    2240           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2241             :         }
    2242           0 :         ret = ads_gen_mod(ads, dn_string, mods);
    2243           0 :         TALLOC_FREE(dn_string);
    2244           0 :         if (!ADS_ERR_OK(ret)) {
    2245           0 :                 DEBUG(1,("ads_clear_service_principal_names: Error: Updating Service Principals for machine %s in LDAP\n",
    2246             :                         machine_name));
    2247           0 :                 ads_msgfree(ads, res);
    2248           0 :                 talloc_destroy(ctx);
    2249           0 :                 return ret;
    2250             :         }
    2251             : 
    2252           0 :         ads_msgfree(ads, res);
    2253           0 :         talloc_destroy(ctx);
    2254           0 :         return ret;
    2255             : }
    2256             : 
    2257             : /**
    2258             :  * @brief Search for an element in a string array.
    2259             :  *
    2260             :  * @param[in]  el_array  The string array to search.
    2261             :  *
    2262             :  * @param[in]  num_el    The number of elements in the string array.
    2263             :  *
    2264             :  * @param[in]  el        The string to search.
    2265             :  *
    2266             :  * @return               True if found, false if not.
    2267             :  */
    2268         140 : bool ads_element_in_array(const char **el_array, size_t num_el, const char *el)
    2269             : {
    2270           0 :         size_t i;
    2271             : 
    2272         140 :         if (el_array == NULL || num_el == 0 || el == NULL) {
    2273           0 :                 return false;
    2274             :         }
    2275             : 
    2276         394 :         for (i = 0; i < num_el && el_array[i] != NULL; i++) {
    2277           0 :                 int cmp;
    2278             : 
    2279         370 :                 cmp = strcasecmp_m(el_array[i], el);
    2280         370 :                 if (cmp == 0) {
    2281         116 :                         return true;
    2282             :                 }
    2283             :         }
    2284             : 
    2285          24 :         return false;
    2286             : }
    2287             : 
    2288             : /**
    2289             :  * @brief This gets the service principal names of an existing computer account.
    2290             :  *
    2291             :  * @param[in]  mem_ctx      The memory context to use to allocate the spn array.
    2292             :  *
    2293             :  * @param[in]  ads          The ADS context to use.
    2294             :  *
    2295             :  * @param[in]  machine_name The NetBIOS name of the computer, which is used to
    2296             :  *                          identify the computer account.
    2297             :  *
    2298             :  * @param[in]  spn_array    A pointer to store the array for SPNs.
    2299             :  *
    2300             :  * @param[in]  num_spns     The number of principals stored in the array.
    2301             :  *
    2302             :  * @return                  0 on success, or a ADS error if a failure occurred.
    2303             :  */
    2304          90 : ADS_STATUS ads_get_service_principal_names(TALLOC_CTX *mem_ctx,
    2305             :                                            ADS_STRUCT *ads,
    2306             :                                            const char *machine_name,
    2307             :                                            char ***spn_array,
    2308             :                                            size_t *num_spns)
    2309             : {
    2310           0 :         ADS_STATUS status;
    2311          90 :         LDAPMessage *res = NULL;
    2312           0 :         int count;
    2313             : 
    2314          90 :         status = ads_find_machine_acct(ads,
    2315             :                                        &res,
    2316             :                                        machine_name);
    2317          90 :         if (!ADS_ERR_OK(status)) {
    2318           0 :                 DEBUG(1,("Host Account for %s not found... skipping operation.\n",
    2319             :                          machine_name));
    2320           0 :                 return status;
    2321             :         }
    2322             : 
    2323          90 :         count = ads_count_replies(ads, res);
    2324          90 :         if (count != 1) {
    2325           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    2326           0 :                 goto done;
    2327             :         }
    2328             : 
    2329          90 :         *spn_array = ads_pull_strings(ads,
    2330             :                                       mem_ctx,
    2331             :                                       res,
    2332             :                                       "servicePrincipalName",
    2333             :                                       num_spns);
    2334          90 :         if (*spn_array == NULL) {
    2335           0 :                 DEBUG(1, ("Host account for %s does not have service principal "
    2336             :                           "names.\n",
    2337             :                           machine_name));
    2338           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    2339           0 :                 goto done;
    2340             :         }
    2341             : 
    2342          90 : done:
    2343          90 :         ads_msgfree(ads, res);
    2344             : 
    2345          90 :         return status;
    2346             : }
    2347             : 
    2348             : /**
    2349             :  * This adds a service principal name to an existing computer account
    2350             :  * (found by hostname) in AD.
    2351             :  * @param ads An initialized ADS_STRUCT
    2352             :  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
    2353             :  * @param spns An array or strings for the service principals to add,
    2354             :  *        i.e. 'cifs/machine_name', 'http/machine.full.domain.com' etc.
    2355             :  * @return 0 upon success, or non-zero if a failure occurs
    2356             :  **/
    2357             : 
    2358           4 : ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
    2359             :                                            const char *machine_name,
    2360             :                                            const char **spns)
    2361             : {
    2362           0 :         ADS_STATUS ret;
    2363           0 :         TALLOC_CTX *ctx;
    2364           4 :         LDAPMessage *res = NULL;
    2365           0 :         ADS_MODLIST mods;
    2366           4 :         char *dn_string = NULL;
    2367           4 :         const char **servicePrincipalName = spns;
    2368             : 
    2369           4 :         ret = ads_find_machine_acct(ads, &res, machine_name);
    2370           4 :         if (!ADS_ERR_OK(ret)) {
    2371           0 :                 DEBUG(1,("ads_add_service_principal_name: WARNING: Host Account for %s not found... skipping operation.\n",
    2372             :                         machine_name));
    2373           0 :                 DEBUG(1,("ads_add_service_principal_name: WARNING: Service Principals have NOT been added.\n"));
    2374           0 :                 ads_msgfree(ads, res);
    2375           0 :                 return ret;
    2376             :         }
    2377             : 
    2378           4 :         DEBUG(1,("ads_add_service_principal_name: Host account for %s found\n", machine_name));
    2379           4 :         if (!(ctx = talloc_init("ads_add_service_principal_name"))) {
    2380           0 :                 ads_msgfree(ads, res);
    2381           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2382             :         }
    2383             : 
    2384           4 :         DEBUG(5,("ads_add_service_principal_name: INFO: "
    2385             :                 "Adding %s to host %s\n",
    2386             :                 spns[0] ? "N/A" : spns[0], machine_name));
    2387             : 
    2388             : 
    2389           4 :         DEBUG(5,("ads_add_service_principal_name: INFO: "
    2390             :                 "Adding %s to host %s\n",
    2391             :                 spns[1] ? "N/A" : spns[1], machine_name));
    2392             : 
    2393           4 :         if ( (mods = ads_init_mods(ctx)) == NULL ) {
    2394           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2395           0 :                 goto out;
    2396             :         }
    2397             : 
    2398           4 :         ret = ads_add_strlist(ctx,
    2399             :                               &mods,
    2400             :                               "servicePrincipalName",
    2401             :                               servicePrincipalName);
    2402           4 :         if (!ADS_ERR_OK(ret)) {
    2403           0 :                 DEBUG(1,("ads_add_service_principal_name: Error: Updating Service Principals in LDAP\n"));
    2404           0 :                 goto out;
    2405             :         }
    2406             : 
    2407           4 :         if ( (dn_string = ads_get_dn(ads, ctx, res)) == NULL ) {
    2408           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2409           0 :                 goto out;
    2410             :         }
    2411             : 
    2412           4 :         ret = ads_gen_mod(ads, dn_string, mods);
    2413           4 :         if (!ADS_ERR_OK(ret)) {
    2414           0 :                 DEBUG(1,("ads_add_service_principal_name: Error: Updating Service Principals in LDAP\n"));
    2415           0 :                 goto out;
    2416             :         }
    2417             : 
    2418           4 :  out:
    2419           4 :         TALLOC_FREE( ctx );
    2420           4 :         ads_msgfree(ads, res);
    2421           4 :         return ret;
    2422             : }
    2423             : 
    2424           4 : static uint32_t ads_get_acct_ctrl(ADS_STRUCT *ads,
    2425             :                                   LDAPMessage *msg)
    2426             : {
    2427           4 :         uint32_t acct_ctrl = 0;
    2428           0 :         bool ok;
    2429             : 
    2430           4 :         ok = ads_pull_uint32(ads, msg, "userAccountControl", &acct_ctrl);
    2431           4 :         if (!ok) {
    2432           0 :                 return 0;
    2433             :         }
    2434             : 
    2435           4 :         return acct_ctrl;
    2436             : }
    2437             : 
    2438           4 : static ADS_STATUS ads_change_machine_acct(ADS_STRUCT *ads,
    2439             :                                           LDAPMessage *msg,
    2440             :                                           const struct berval *machine_pw_val)
    2441             : {
    2442           0 :         ADS_MODLIST mods;
    2443           0 :         ADS_STATUS ret;
    2444           4 :         TALLOC_CTX *frame = talloc_stackframe();
    2445           0 :         uint32_t acct_control;
    2446           4 :         char *control_str = NULL;
    2447           4 :         const char *attrs[] = {
    2448             :                 "objectSid",
    2449             :                 NULL
    2450             :         };
    2451           4 :         LDAPMessage *res = NULL;
    2452           4 :         char *dn = NULL;
    2453             : 
    2454           4 :         dn = ads_get_dn(ads, frame, msg);
    2455           4 :         if (dn == NULL) {
    2456           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2457           0 :                 goto done;
    2458             :         }
    2459             : 
    2460           4 :         acct_control = ads_get_acct_ctrl(ads, msg);
    2461           4 :         if (acct_control == 0) {
    2462           0 :                 ret = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    2463           0 :                 goto done;
    2464             :         }
    2465             : 
    2466             :         /*
    2467             :          * Changing the password, disables the account. So we need to change the
    2468             :          * userAccountControl flags to enable it again.
    2469             :          */
    2470           4 :         mods = ads_init_mods(frame);
    2471           4 :         if (mods == NULL) {
    2472           0 :                 ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    2473           0 :                 goto done;
    2474             :         }
    2475             : 
    2476           4 :         ads_mod_ber(frame, &mods, "unicodePwd", machine_pw_val);
    2477             : 
    2478           4 :         ret = ads_gen_mod(ads, dn, mods);
    2479           4 :         if (!ADS_ERR_OK(ret)) {
    2480           0 :                 goto done;
    2481             :         }
    2482           4 :         TALLOC_FREE(mods);
    2483             : 
    2484             :         /*
    2485             :          * To activate the account, we need to disable and enable it.
    2486             :          */
    2487           4 :         acct_control |= UF_ACCOUNTDISABLE;
    2488             : 
    2489           4 :         control_str = talloc_asprintf(frame, "%u", acct_control);
    2490           4 :         if (control_str == NULL) {
    2491           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2492           0 :                 goto done;
    2493             :         }
    2494             : 
    2495           4 :         mods = ads_init_mods(frame);
    2496           4 :         if (mods == NULL) {
    2497           0 :                 ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    2498           0 :                 goto done;
    2499             :         }
    2500             : 
    2501           4 :         ads_mod_str(frame, &mods, "userAccountControl", control_str);
    2502             : 
    2503           4 :         ret = ads_gen_mod(ads, dn, mods);
    2504           4 :         if (!ADS_ERR_OK(ret)) {
    2505           0 :                 goto done;
    2506             :         }
    2507           4 :         TALLOC_FREE(mods);
    2508           4 :         TALLOC_FREE(control_str);
    2509             : 
    2510             :         /*
    2511             :          * Enable the account again.
    2512             :          */
    2513           4 :         acct_control &= ~UF_ACCOUNTDISABLE;
    2514             : 
    2515           4 :         control_str = talloc_asprintf(frame, "%u", acct_control);
    2516           4 :         if (control_str == NULL) {
    2517           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2518           0 :                 goto done;
    2519             :         }
    2520             : 
    2521           4 :         mods = ads_init_mods(frame);
    2522           4 :         if (mods == NULL) {
    2523           0 :                 ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    2524           0 :                 goto done;
    2525             :         }
    2526             : 
    2527           4 :         ads_mod_str(frame, &mods, "userAccountControl", control_str);
    2528             : 
    2529           4 :         ret = ads_gen_mod(ads, dn, mods);
    2530           4 :         if (!ADS_ERR_OK(ret)) {
    2531           0 :                 goto done;
    2532             :         }
    2533           4 :         TALLOC_FREE(mods);
    2534           4 :         TALLOC_FREE(control_str);
    2535             : 
    2536           4 :         ret = ads_search_dn(ads, &res, dn, attrs);
    2537           4 :         ads_msgfree(ads, res);
    2538             : 
    2539           4 : done:
    2540           4 :         talloc_free(frame);
    2541             : 
    2542           4 :         return ret;
    2543             : }
    2544             : 
    2545             : /**
    2546             :  * adds a machine account to the ADS server
    2547             :  * @param ads An initialized ADS_STRUCT
    2548             :  * @param machine_name - the NetBIOS machine name of this account.
    2549             :  * @param account_type A number indicating the type of account to create
    2550             :  * @param org_unit The LDAP path in which to place this account
    2551             :  * @return 0 upon success, or non-zero otherwise
    2552             : **/
    2553             : 
    2554          60 : ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads,
    2555             :                                    const char *machine_name,
    2556             :                                    const char *machine_password,
    2557             :                                    const char *org_unit,
    2558             :                                    uint32_t etype_list,
    2559             :                                    const char *dns_domain_name)
    2560             : {
    2561           0 :         ADS_STATUS ret;
    2562          60 :         char *samAccountName = NULL;
    2563          60 :         char *controlstr = NULL;
    2564          60 :         TALLOC_CTX *ctx = NULL;
    2565           0 :         ADS_MODLIST mods;
    2566          60 :         char *machine_escaped = NULL;
    2567          60 :         char *dns_hostname = NULL;
    2568          60 :         char *new_dn = NULL;
    2569          60 :         char *utf8_pw = NULL;
    2570          60 :         size_t utf8_pw_len = 0;
    2571          60 :         char *utf16_pw = NULL;
    2572          60 :         size_t utf16_pw_len = 0;
    2573           0 :         struct berval machine_pw_val;
    2574           0 :         bool ok;
    2575          60 :         const char **spn_array = NULL;
    2576          60 :         size_t num_spns = 0;
    2577          60 :         const char *spn_prefix[] = {
    2578             :                 "HOST",
    2579             :                 "RestrictedKrbHost",
    2580             :         };
    2581           0 :         size_t i;
    2582          60 :         LDAPMessage *res = NULL;
    2583          60 :         uint32_t acct_control = UF_WORKSTATION_TRUST_ACCOUNT;
    2584             : 
    2585          60 :         ctx = talloc_init("ads_add_machine_acct");
    2586          60 :         if (ctx == NULL) {
    2587           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2588             :         }
    2589             : 
    2590          60 :         machine_escaped = escape_rdn_val_string_alloc(machine_name);
    2591          60 :         if (machine_escaped == NULL) {
    2592           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2593           0 :                 goto done;
    2594             :         }
    2595             : 
    2596          60 :         utf8_pw = talloc_asprintf(ctx, "\"%s\"", machine_password);
    2597          60 :         if (utf8_pw == NULL) {
    2598           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2599           0 :                 goto done;
    2600             :         }
    2601          60 :         utf8_pw_len = strlen(utf8_pw);
    2602             : 
    2603          60 :         ok = convert_string_talloc(ctx,
    2604             :                                    CH_UTF8, CH_UTF16MUNGED,
    2605             :                                    utf8_pw, utf8_pw_len,
    2606             :                                    (void *)&utf16_pw, &utf16_pw_len);
    2607          60 :         if (!ok) {
    2608           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2609           0 :                 goto done;
    2610             :         }
    2611             : 
    2612          60 :         machine_pw_val = (struct berval) {
    2613             :                 .bv_val = utf16_pw,
    2614             :                 .bv_len = utf16_pw_len,
    2615             :         };
    2616             : 
    2617             :         /* Check if the machine account already exists. */
    2618          60 :         ret = ads_find_machine_acct(ads, &res, machine_escaped);
    2619          60 :         if (ADS_ERR_OK(ret)) {
    2620             :                 /* Change the machine account password */
    2621           4 :                 ret = ads_change_machine_acct(ads, res, &machine_pw_val);
    2622           4 :                 ads_msgfree(ads, res);
    2623             : 
    2624           4 :                 goto done;
    2625             :         }
    2626          56 :         ads_msgfree(ads, res);
    2627             : 
    2628          56 :         new_dn = talloc_asprintf(ctx, "cn=%s,%s", machine_escaped, org_unit);
    2629          56 :         if (new_dn == NULL) {
    2630           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2631           0 :                 goto done;
    2632             :         }
    2633             : 
    2634             :         /* Create machine account */
    2635             : 
    2636          56 :         samAccountName = talloc_asprintf(ctx, "%s$", machine_name);
    2637          56 :         if (samAccountName == NULL) {
    2638           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2639           0 :                 goto done;
    2640             :         }
    2641             : 
    2642          56 :         dns_hostname = talloc_asprintf(ctx,
    2643             :                                        "%s.%s",
    2644             :                                        machine_name,
    2645             :                                        dns_domain_name);
    2646          56 :         if (dns_hostname == NULL) {
    2647           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2648           0 :                 goto done;
    2649             :         }
    2650             : 
    2651             :         /* Add dns_hostname SPNs */
    2652         168 :         for (i = 0; i < ARRAY_SIZE(spn_prefix); i++) {
    2653         112 :                 char *spn = talloc_asprintf(ctx,
    2654             :                                             "%s/%s",
    2655             :                                             spn_prefix[i],
    2656             :                                             dns_hostname);
    2657         112 :                 if (spn == NULL) {
    2658           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2659           0 :                         goto done;
    2660             :                 }
    2661             : 
    2662         112 :                 ok = add_string_to_array(spn_array,
    2663             :                                          spn,
    2664             :                                          &spn_array,
    2665             :                                          &num_spns);
    2666         112 :                 if (!ok) {
    2667           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2668           0 :                         goto done;
    2669             :                 }
    2670             :         }
    2671             : 
    2672             :         /* Add machine_name SPNs */
    2673         168 :         for (i = 0; i < ARRAY_SIZE(spn_prefix); i++) {
    2674         112 :                 char *spn = talloc_asprintf(ctx,
    2675             :                                             "%s/%s",
    2676             :                                             spn_prefix[i],
    2677             :                                             machine_name);
    2678         112 :                 if (spn == NULL) {
    2679           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2680           0 :                         goto done;
    2681             :                 }
    2682             : 
    2683         112 :                 ok = add_string_to_array(spn_array,
    2684             :                                          spn,
    2685             :                                          &spn_array,
    2686             :                                          &num_spns);
    2687         112 :                 if (!ok) {
    2688           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2689           0 :                         goto done;
    2690             :                 }
    2691             :         }
    2692             : 
    2693             :         /* Make sure to NULL terminate the array */
    2694          56 :         spn_array = talloc_realloc(ctx, spn_array, const char *, num_spns + 1);
    2695          56 :         if (spn_array == NULL) {
    2696           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2697           0 :                 goto done;
    2698             :         }
    2699          56 :         spn_array[num_spns] = NULL;
    2700             : 
    2701          56 :         controlstr = talloc_asprintf(ctx, "%u", acct_control);
    2702          56 :         if (controlstr == NULL) {
    2703           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2704           0 :                 goto done;
    2705             :         }
    2706             : 
    2707          56 :         mods = ads_init_mods(ctx);
    2708          56 :         if (mods == NULL) {
    2709           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2710           0 :                 goto done;
    2711             :         }
    2712             : 
    2713          56 :         ads_mod_str(ctx, &mods, "objectClass", "Computer");
    2714          56 :         ads_mod_str(ctx, &mods, "SamAccountName", samAccountName);
    2715          56 :         ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
    2716          56 :         ads_mod_str(ctx, &mods, "DnsHostName", dns_hostname);
    2717          56 :         ads_mod_strlist(ctx, &mods, "ServicePrincipalName", spn_array);
    2718          56 :         ads_mod_ber(ctx, &mods, "unicodePwd", &machine_pw_val);
    2719             : 
    2720          56 :         ret = ads_gen_add(ads, new_dn, mods);
    2721             : 
    2722          60 : done:
    2723          60 :         SAFE_FREE(machine_escaped);
    2724          60 :         talloc_destroy(ctx);
    2725             : 
    2726          60 :         return ret;
    2727             : }
    2728             : 
    2729             : /**
    2730             :  * move a machine account to another OU on the ADS server
    2731             :  * @param ads - An initialized ADS_STRUCT
    2732             :  * @param machine_name - the NetBIOS machine name of this account.
    2733             :  * @param org_unit - The LDAP path in which to place this account
    2734             :  * @param moved - whether we moved the machine account (optional)
    2735             :  * @return 0 upon success, or non-zero otherwise
    2736             : **/
    2737             : 
    2738           0 : ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name,
    2739             :                                  const char *org_unit, bool *moved)
    2740             : {
    2741           0 :         ADS_STATUS rc;
    2742           0 :         int ldap_status;
    2743           0 :         LDAPMessage *res = NULL;
    2744           0 :         char *filter = NULL;
    2745           0 :         char *computer_dn = NULL;
    2746           0 :         char *parent_dn;
    2747           0 :         char *computer_rdn = NULL;
    2748           0 :         bool need_move = False;
    2749             : 
    2750           0 :         if (asprintf(&filter, "(samAccountName=%s$)", machine_name) == -1) {
    2751           0 :                 rc = ADS_ERROR(LDAP_NO_MEMORY);
    2752           0 :                 goto done;
    2753             :         }
    2754             : 
    2755             :         /* Find pre-existing machine */
    2756           0 :         rc = ads_search(ads, &res, filter, NULL);
    2757           0 :         if (!ADS_ERR_OK(rc)) {
    2758           0 :                 goto done;
    2759             :         }
    2760             : 
    2761           0 :         computer_dn = ads_get_dn(ads, talloc_tos(), res);
    2762           0 :         if (!computer_dn) {
    2763           0 :                 rc = ADS_ERROR(LDAP_NO_MEMORY);
    2764           0 :                 goto done;
    2765             :         }
    2766             : 
    2767           0 :         parent_dn = ads_parent_dn(computer_dn);
    2768           0 :         if (strequal(parent_dn, org_unit)) {
    2769           0 :                 goto done;
    2770             :         }
    2771             : 
    2772           0 :         need_move = True;
    2773             : 
    2774           0 :         if (asprintf(&computer_rdn, "CN=%s", machine_name) == -1) {
    2775           0 :                 rc = ADS_ERROR(LDAP_NO_MEMORY);
    2776           0 :                 goto done;
    2777             :         }
    2778             : 
    2779           0 :         ldap_status = ldap_rename_s(ads->ldap.ld, computer_dn, computer_rdn,
    2780             :                                     org_unit, 1, NULL, NULL);
    2781           0 :         rc = ADS_ERROR(ldap_status);
    2782             : 
    2783           0 : done:
    2784           0 :         ads_msgfree(ads, res);
    2785           0 :         SAFE_FREE(filter);
    2786           0 :         TALLOC_FREE(computer_dn);
    2787           0 :         SAFE_FREE(computer_rdn);
    2788             : 
    2789           0 :         if (!ADS_ERR_OK(rc)) {
    2790           0 :                 need_move = False;
    2791             :         }
    2792             : 
    2793           0 :         if (moved) {
    2794           0 :                 *moved = need_move;
    2795             :         }
    2796             : 
    2797           0 :         return rc;
    2798             : }
    2799             : 
    2800             : /*
    2801             :   dump a binary result from ldap
    2802             : */
    2803           0 : static void dump_binary(ADS_STRUCT *ads, const char *field, struct berval **values)
    2804             : {
    2805           0 :         size_t i;
    2806           0 :         for (i=0; values[i]; i++) {
    2807           0 :                 ber_len_t j;
    2808           0 :                 printf("%s: ", field);
    2809           0 :                 for (j=0; j<values[i]->bv_len; j++) {
    2810           0 :                         printf("%02X", (unsigned char)values[i]->bv_val[j]);
    2811             :                 }
    2812           0 :                 printf("\n");
    2813             :         }
    2814           0 : }
    2815             : 
    2816           0 : static void dump_guid(ADS_STRUCT *ads, const char *field, struct berval **values)
    2817             : {
    2818           0 :         int i;
    2819           0 :         for (i=0; values[i]; i++) {
    2820           0 :                 NTSTATUS status;
    2821           0 :                 DATA_BLOB in = data_blob_const(values[i]->bv_val, values[i]->bv_len);
    2822           0 :                 struct GUID guid;
    2823             : 
    2824           0 :                 status = GUID_from_ndr_blob(&in, &guid);
    2825           0 :                 if (NT_STATUS_IS_OK(status)) {
    2826           0 :                         printf("%s: %s\n", field, GUID_string(talloc_tos(), &guid));
    2827             :                 } else {
    2828           0 :                         printf("%s: INVALID GUID\n", field);
    2829             :                 }
    2830             :         }
    2831           0 : }
    2832             : 
    2833             : /*
    2834             :   dump a sid result from ldap
    2835             : */
    2836           0 : static void dump_sid(ADS_STRUCT *ads, const char *field, struct berval **values)
    2837             : {
    2838           0 :         int i;
    2839           0 :         for (i=0; values[i]; i++) {
    2840           0 :                 ssize_t ret;
    2841           0 :                 struct dom_sid sid;
    2842           0 :                 struct dom_sid_buf tmp;
    2843           0 :                 ret = sid_parse((const uint8_t *)values[i]->bv_val,
    2844           0 :                                 values[i]->bv_len, &sid);
    2845           0 :                 if (ret == -1) {
    2846           0 :                         return;
    2847             :                 }
    2848           0 :                 printf("%s: %s\n", field, dom_sid_str_buf(&sid, &tmp));
    2849             :         }
    2850             : }
    2851             : 
    2852             : /*
    2853             :   dump ntSecurityDescriptor
    2854             : */
    2855           0 : static void dump_sd(ADS_STRUCT *ads, const char *filed, struct berval **values)
    2856             : {
    2857           0 :         TALLOC_CTX *frame = talloc_stackframe();
    2858           0 :         struct security_descriptor *psd;
    2859           0 :         NTSTATUS status;
    2860             : 
    2861           0 :         status = unmarshall_sec_desc(talloc_tos(), (uint8_t *)values[0]->bv_val,
    2862           0 :                                      values[0]->bv_len, &psd);
    2863           0 :         if (!NT_STATUS_IS_OK(status)) {
    2864           0 :                 DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
    2865             :                           nt_errstr(status)));
    2866           0 :                 TALLOC_FREE(frame);
    2867           0 :                 return;
    2868             :         }
    2869             : 
    2870           0 :         if (psd) {
    2871           0 :                 ads_disp_sd(ads, talloc_tos(), psd);
    2872             :         }
    2873             : 
    2874           0 :         TALLOC_FREE(frame);
    2875             : }
    2876             : 
    2877             : /*
    2878             :   dump a string result from ldap
    2879             : */
    2880          71 : static void dump_string(const char *field, char **values)
    2881             : {
    2882           0 :         int i;
    2883         218 :         for (i=0; values[i]; i++) {
    2884         147 :                 printf("%s: %s\n", field, values[i]);
    2885             :         }
    2886          71 : }
    2887             : 
    2888             : /*
    2889             :   dump a field from LDAP on stdout
    2890             :   used for debugging
    2891             : */
    2892             : 
    2893         213 : static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *data_area)
    2894             : {
    2895           0 :         const struct {
    2896             :                 const char *name;
    2897             :                 bool string;
    2898             :                 void (*handler)(ADS_STRUCT *, const char *, struct berval **);
    2899         213 :         } handlers[] = {
    2900             :                 {"objectGUID", False, dump_guid},
    2901             :                 {"netbootGUID", False, dump_guid},
    2902             :                 {"nTSecurityDescriptor", False, dump_sd},
    2903             :                 {"dnsRecord", False, dump_binary},
    2904             :                 {"objectSid", False, dump_sid},
    2905             :                 {"tokenGroups", False, dump_sid},
    2906             :                 {"tokenGroupsNoGCAcceptable", False, dump_sid},
    2907             :                 {"tokengroupsGlobalandUniversal", False, dump_sid},
    2908             :                 {"mS-DS-CreatorSID", False, dump_sid},
    2909             :                 {"msExchMailboxGuid", False, dump_guid},
    2910             :                 {NULL, True, NULL}
    2911             :         };
    2912           0 :         int i;
    2913             : 
    2914         213 :         if (!field) { /* must be end of an entry */
    2915          71 :                 printf("\n");
    2916          71 :                 return False;
    2917             :         }
    2918             : 
    2919        1562 :         for (i=0; handlers[i].name; i++) {
    2920        1420 :                 if (strcasecmp_m(handlers[i].name, field) == 0) {
    2921           0 :                         if (!values) /* first time, indicate string or not */
    2922           0 :                                 return handlers[i].string;
    2923           0 :                         handlers[i].handler(ads, field, (struct berval **) values);
    2924           0 :                         break;
    2925             :                 }
    2926             :         }
    2927         142 :         if (!handlers[i].name) {
    2928         142 :                 if (!values) /* first time, indicate string conversion */
    2929          71 :                         return True;
    2930          71 :                 dump_string(field, (char **)values);
    2931             :         }
    2932          71 :         return False;
    2933             : }
    2934             : 
    2935             : /**
    2936             :  * Dump a result from LDAP on stdout
    2937             :  *  used for debugging
    2938             :  * @param ads connection to ads server
    2939             :  * @param res Results to dump
    2940             :  **/
    2941             : 
    2942          33 :  void ads_dump(ADS_STRUCT *ads, LDAPMessage *res)
    2943             : {
    2944          33 :         ads_process_results(ads, res, ads_dump_field, NULL);
    2945          33 : }
    2946             : 
    2947             : /**
    2948             :  * Walk through results, calling a function for each entry found.
    2949             :  *  The function receives a field name, a berval * array of values,
    2950             :  *  and a data area passed through from the start.  The function is
    2951             :  *  called once with null for field and values at the end of each
    2952             :  *  entry.
    2953             :  * @param ads connection to ads server
    2954             :  * @param res Results to process
    2955             :  * @param fn Function for processing each result
    2956             :  * @param data_area user-defined area to pass to function
    2957             :  **/
    2958          33 :  void ads_process_results(ADS_STRUCT *ads, LDAPMessage *res,
    2959             :                           bool (*fn)(ADS_STRUCT *, char *, void **, void *),
    2960             :                           void *data_area)
    2961             : {
    2962           0 :         LDAPMessage *msg;
    2963           0 :         TALLOC_CTX *ctx;
    2964           0 :         size_t converted_size;
    2965             : 
    2966          33 :         if (!(ctx = talloc_init("ads_process_results")))
    2967           0 :                 return;
    2968             : 
    2969         104 :         for (msg = ads_first_entry(ads, res); msg;
    2970          71 :              msg = ads_next_entry(ads, msg)) {
    2971           0 :                 char *utf8_field;
    2972           0 :                 BerElement *b;
    2973             : 
    2974          71 :                 for (utf8_field=ldap_first_attribute(ads->ldap.ld,
    2975             :                                                      (LDAPMessage *)msg,&b);
    2976         142 :                      utf8_field;
    2977          71 :                      utf8_field=ldap_next_attribute(ads->ldap.ld,
    2978             :                                                     (LDAPMessage *)msg,b)) {
    2979           0 :                         struct berval **ber_vals;
    2980           0 :                         char **str_vals;
    2981           0 :                         char **utf8_vals;
    2982           0 :                         char *field;
    2983           0 :                         bool string;
    2984             : 
    2985          71 :                         if (!pull_utf8_talloc(ctx, &field, utf8_field,
    2986             :                                               &converted_size))
    2987             :                         {
    2988           0 :                                 DEBUG(0,("ads_process_results: "
    2989             :                                          "pull_utf8_talloc failed: %s\n",
    2990             :                                          strerror(errno)));
    2991             :                         }
    2992             : 
    2993          71 :                         string = fn(ads, field, NULL, data_area);
    2994             : 
    2995          71 :                         if (string) {
    2996           0 :                                 const char **p;
    2997             : 
    2998          71 :                                 utf8_vals = ldap_get_values(ads->ldap.ld,
    2999             :                                                  (LDAPMessage *)msg, field);
    3000          71 :                                 p = discard_const_p(const char *, utf8_vals);
    3001          71 :                                 str_vals = ads_pull_strvals(ctx, p);
    3002          71 :                                 fn(ads, field, (void **) str_vals, data_area);
    3003          71 :                                 ldap_value_free(utf8_vals);
    3004             :                         } else {
    3005           0 :                                 ber_vals = ldap_get_values_len(ads->ldap.ld,
    3006             :                                                  (LDAPMessage *)msg, field);
    3007           0 :                                 fn(ads, field, (void **) ber_vals, data_area);
    3008             : 
    3009           0 :                                 ldap_value_free_len(ber_vals);
    3010             :                         }
    3011          71 :                         ldap_memfree(utf8_field);
    3012             :                 }
    3013          71 :                 ber_free(b, 0);
    3014          71 :                 talloc_free_children(ctx);
    3015          71 :                 fn(ads, NULL, NULL, data_area); /* completed an entry */
    3016             : 
    3017             :         }
    3018          33 :         talloc_destroy(ctx);
    3019             : }
    3020             : 
    3021             : /**
    3022             :  * count how many replies are in a LDAPMessage
    3023             :  * @param ads connection to ads server
    3024             :  * @param res Results to count
    3025             :  * @return number of replies
    3026             :  **/
    3027        1469 : int ads_count_replies(ADS_STRUCT *ads, void *res)
    3028             : {
    3029        1469 :         return ldap_count_entries(ads->ldap.ld, (LDAPMessage *)res);
    3030             : }
    3031             : 
    3032             : /**
    3033             :  * pull the first entry from a ADS result
    3034             :  * @param ads connection to ads server
    3035             :  * @param res Results of search
    3036             :  * @return first entry from result
    3037             :  **/
    3038          65 :  LDAPMessage *ads_first_entry(ADS_STRUCT *ads, LDAPMessage *res)
    3039             : {
    3040          65 :         return ldap_first_entry(ads->ldap.ld, res);
    3041             : }
    3042             : 
    3043             : /**
    3044             :  * pull the next entry from a ADS result
    3045             :  * @param ads connection to ads server
    3046             :  * @param res Results of search
    3047             :  * @return next entry from result
    3048             :  **/
    3049          71 :  LDAPMessage *ads_next_entry(ADS_STRUCT *ads, LDAPMessage *res)
    3050             : {
    3051          71 :         return ldap_next_entry(ads->ldap.ld, res);
    3052             : }
    3053             : 
    3054             : /**
    3055             :  * pull the first message from a ADS result
    3056             :  * @param ads connection to ads server
    3057             :  * @param res Results of search
    3058             :  * @return first message from result
    3059             :  **/
    3060           0 :  LDAPMessage *ads_first_message(ADS_STRUCT *ads, LDAPMessage *res)
    3061             : {
    3062           0 :         return ldap_first_message(ads->ldap.ld, res);
    3063             : }
    3064             : 
    3065             : /**
    3066             :  * pull the next message from a ADS result
    3067             :  * @param ads connection to ads server
    3068             :  * @param res Results of search
    3069             :  * @return next message from result
    3070             :  **/
    3071           0 :  LDAPMessage *ads_next_message(ADS_STRUCT *ads, LDAPMessage *res)
    3072             : {
    3073           0 :         return ldap_next_message(ads->ldap.ld, res);
    3074             : }
    3075             : 
    3076             : /**
    3077             :  * pull a single string from a ADS result
    3078             :  * @param ads connection to ads server
    3079             :  * @param mem_ctx TALLOC_CTX to use for allocating result string
    3080             :  * @param msg Results of search
    3081             :  * @param field Attribute to retrieve
    3082             :  * @return Result string in talloc context
    3083             :  **/
    3084         561 :  char *ads_pull_string(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, LDAPMessage *msg,
    3085             :                        const char *field)
    3086             : {
    3087           0 :         char **values;
    3088         561 :         char *ret = NULL;
    3089           0 :         char *ux_string;
    3090           0 :         size_t converted_size;
    3091             : 
    3092         561 :         values = ldap_get_values(ads->ldap.ld, msg, field);
    3093         561 :         if (!values)
    3094          12 :                 return NULL;
    3095             : 
    3096         549 :         if (values[0] && pull_utf8_talloc(mem_ctx, &ux_string, values[0],
    3097             :                                           &converted_size))
    3098             :         {
    3099         549 :                 ret = ux_string;
    3100             :         }
    3101         549 :         ldap_value_free(values);
    3102         549 :         return ret;
    3103             : }
    3104             : 
    3105             : /**
    3106             :  * pull an array of strings from a ADS result
    3107             :  * @param ads connection to ads server
    3108             :  * @param mem_ctx TALLOC_CTX to use for allocating result string
    3109             :  * @param msg Results of search
    3110             :  * @param field Attribute to retrieve
    3111             :  * @return Result strings in talloc context
    3112             :  **/
    3113          90 :  char **ads_pull_strings(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3114             :                          LDAPMessage *msg, const char *field,
    3115             :                          size_t *num_values)
    3116             : {
    3117           0 :         char **values;
    3118          90 :         char **ret = NULL;
    3119           0 :         size_t i, converted_size;
    3120             : 
    3121          90 :         values = ldap_get_values(ads->ldap.ld, msg, field);
    3122          90 :         if (!values)
    3123           0 :                 return NULL;
    3124             : 
    3125          90 :         *num_values = ldap_count_values(values);
    3126             : 
    3127          90 :         ret = talloc_array(mem_ctx, char *, *num_values + 1);
    3128          90 :         if (!ret) {
    3129           0 :                 ldap_value_free(values);
    3130           0 :                 return NULL;
    3131             :         }
    3132             : 
    3133         480 :         for (i=0;i<*num_values;i++) {
    3134         390 :                 if (!pull_utf8_talloc(mem_ctx, &ret[i], values[i],
    3135             :                                       &converted_size))
    3136             :                 {
    3137           0 :                         ldap_value_free(values);
    3138           0 :                         return NULL;
    3139             :                 }
    3140             :         }
    3141          90 :         ret[i] = NULL;
    3142             : 
    3143          90 :         ldap_value_free(values);
    3144          90 :         return ret;
    3145             : }
    3146             : 
    3147             : /**
    3148             :  * pull an array of strings from a ADS result
    3149             :  *  (handle large multivalue attributes with range retrieval)
    3150             :  * @param ads connection to ads server
    3151             :  * @param mem_ctx TALLOC_CTX to use for allocating result string
    3152             :  * @param msg Results of search
    3153             :  * @param field Attribute to retrieve
    3154             :  * @param current_strings strings returned by a previous call to this function
    3155             :  * @param next_attribute The next query should ask for this attribute
    3156             :  * @param num_values How many values did we get this time?
    3157             :  * @param more_values Are there more values to get?
    3158             :  * @return Result strings in talloc context
    3159             :  **/
    3160           0 :  char **ads_pull_strings_range(ADS_STRUCT *ads,
    3161             :                                TALLOC_CTX *mem_ctx,
    3162             :                                LDAPMessage *msg, const char *field,
    3163             :                                char **current_strings,
    3164             :                                const char **next_attribute,
    3165             :                                size_t *num_strings,
    3166             :                                bool *more_strings)
    3167             : {
    3168           0 :         char *attr;
    3169           0 :         char *expected_range_attrib, *range_attr = NULL;
    3170           0 :         BerElement *ptr = NULL;
    3171           0 :         char **strings;
    3172           0 :         char **new_strings;
    3173           0 :         size_t num_new_strings;
    3174           0 :         unsigned long int range_start;
    3175           0 :         unsigned long int range_end;
    3176             : 
    3177             :         /* we might have been given the whole lot anyway */
    3178           0 :         if ((strings = ads_pull_strings(ads, mem_ctx, msg, field, num_strings))) {
    3179           0 :                 *more_strings = False;
    3180           0 :                 return strings;
    3181             :         }
    3182             : 
    3183           0 :         expected_range_attrib = talloc_asprintf(mem_ctx, "%s;Range=", field);
    3184             : 
    3185             :         /* look for Range result */
    3186           0 :         for (attr = ldap_first_attribute(ads->ldap.ld, (LDAPMessage *)msg, &ptr);
    3187           0 :              attr;
    3188           0 :              attr = ldap_next_attribute(ads->ldap.ld, (LDAPMessage *)msg, ptr)) {
    3189             :                 /* we ignore the fact that this is utf8, as all attributes are ascii... */
    3190           0 :                 if (strnequal(attr, expected_range_attrib, strlen(expected_range_attrib))) {
    3191           0 :                         range_attr = attr;
    3192           0 :                         break;
    3193             :                 }
    3194           0 :                 ldap_memfree(attr);
    3195             :         }
    3196           0 :         if (!range_attr) {
    3197           0 :                 ber_free(ptr, 0);
    3198             :                 /* nothing here - this field is just empty */
    3199           0 :                 *more_strings = False;
    3200           0 :                 return NULL;
    3201             :         }
    3202             : 
    3203           0 :         if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-%lu",
    3204             :                    &range_start, &range_end) == 2) {
    3205           0 :                 *more_strings = True;
    3206             :         } else {
    3207           0 :                 if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-*",
    3208             :                            &range_start) == 1) {
    3209           0 :                         *more_strings = False;
    3210             :                 } else {
    3211           0 :                         DEBUG(1, ("ads_pull_strings_range:  Cannot parse Range attribute (%s)\n",
    3212             :                                   range_attr));
    3213           0 :                         ldap_memfree(range_attr);
    3214           0 :                         *more_strings = False;
    3215           0 :                         return NULL;
    3216             :                 }
    3217             :         }
    3218             : 
    3219           0 :         if ((*num_strings) != range_start) {
    3220           0 :                 DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) doesn't start at %u, but at %lu"
    3221             :                           " - aborting range retrieval\n",
    3222             :                           range_attr, (unsigned int)(*num_strings) + 1, range_start));
    3223           0 :                 ldap_memfree(range_attr);
    3224           0 :                 *more_strings = False;
    3225           0 :                 return NULL;
    3226             :         }
    3227             : 
    3228           0 :         new_strings = ads_pull_strings(ads, mem_ctx, msg, range_attr, &num_new_strings);
    3229             : 
    3230           0 :         if (*more_strings && ((*num_strings + num_new_strings) != (range_end + 1))) {
    3231           0 :                 DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) tells us we have %lu "
    3232             :                           "strings in this bunch, but we only got %lu - aborting range retrieval\n",
    3233             :                           range_attr, (unsigned long int)range_end - range_start + 1,
    3234             :                           (unsigned long int)num_new_strings));
    3235           0 :                 ldap_memfree(range_attr);
    3236           0 :                 *more_strings = False;
    3237           0 :                 return NULL;
    3238             :         }
    3239             : 
    3240           0 :         strings = talloc_realloc(mem_ctx, current_strings, char *,
    3241             :                                  *num_strings + num_new_strings);
    3242             : 
    3243           0 :         if (strings == NULL) {
    3244           0 :                 ldap_memfree(range_attr);
    3245           0 :                 *more_strings = False;
    3246           0 :                 return NULL;
    3247             :         }
    3248             : 
    3249           0 :         if (new_strings && num_new_strings) {
    3250           0 :                 memcpy(&strings[*num_strings], new_strings,
    3251             :                        sizeof(*new_strings) * num_new_strings);
    3252             :         }
    3253             : 
    3254           0 :         (*num_strings) += num_new_strings;
    3255             : 
    3256           0 :         if (*more_strings) {
    3257           0 :                 *next_attribute = talloc_asprintf(mem_ctx,
    3258             :                                                   "%s;range=%d-*",
    3259             :                                                   field,
    3260           0 :                                                   (int)*num_strings);
    3261             : 
    3262           0 :                 if (!*next_attribute) {
    3263           0 :                         DEBUG(1, ("talloc_asprintf for next attribute failed!\n"));
    3264           0 :                         ldap_memfree(range_attr);
    3265           0 :                         *more_strings = False;
    3266           0 :                         return NULL;
    3267             :                 }
    3268             :         }
    3269             : 
    3270           0 :         ldap_memfree(range_attr);
    3271             : 
    3272           0 :         return strings;
    3273             : }
    3274             : 
    3275             : /**
    3276             :  * pull a single uint32_t from a ADS result
    3277             :  * @param ads connection to ads server
    3278             :  * @param msg Results of search
    3279             :  * @param field Attribute to retrieve
    3280             :  * @param v Pointer to int to store result
    3281             :  * @return boolean indicating success
    3282             : */
    3283         386 :  bool ads_pull_uint32(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
    3284             :                       uint32_t *v)
    3285             : {
    3286           0 :         char **values;
    3287             : 
    3288         386 :         values = ldap_get_values(ads->ldap.ld, msg, field);
    3289         386 :         if (!values)
    3290         172 :                 return False;
    3291         214 :         if (!values[0]) {
    3292           0 :                 ldap_value_free(values);
    3293           0 :                 return False;
    3294             :         }
    3295             : 
    3296         214 :         *v = atoi(values[0]);
    3297         214 :         ldap_value_free(values);
    3298         214 :         return True;
    3299             : }
    3300             : 
    3301             : /**
    3302             :  * pull a single objectGUID from an ADS result
    3303             :  * @param ads connection to ADS server
    3304             :  * @param msg results of search
    3305             :  * @param guid 37-byte area to receive text guid
    3306             :  * @return boolean indicating success
    3307             :  **/
    3308           0 :  bool ads_pull_guid(ADS_STRUCT *ads, LDAPMessage *msg, struct GUID *guid)
    3309             : {
    3310           0 :         DATA_BLOB blob;
    3311           0 :         NTSTATUS status;
    3312             : 
    3313           0 :         if (!smbldap_talloc_single_blob(talloc_tos(), ads->ldap.ld, msg, "objectGUID",
    3314             :                                         &blob)) {
    3315           0 :                 return false;
    3316             :         }
    3317             : 
    3318           0 :         status = GUID_from_ndr_blob(&blob, guid);
    3319           0 :         talloc_free(blob.data);
    3320           0 :         return NT_STATUS_IS_OK(status);
    3321             : }
    3322             : 
    3323             : 
    3324             : /**
    3325             :  * pull a single struct dom_sid from a ADS result
    3326             :  * @param ads connection to ads server
    3327             :  * @param msg Results of search
    3328             :  * @param field Attribute to retrieve
    3329             :  * @param sid Pointer to sid to store result
    3330             :  * @return boolean indicating success
    3331             : */
    3332         178 :  bool ads_pull_sid(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
    3333             :                    struct dom_sid *sid)
    3334             : {
    3335         178 :         return smbldap_pull_sid(ads->ldap.ld, msg, field, sid);
    3336             : }
    3337             : 
    3338             : /**
    3339             :  * pull an array of struct dom_sids from a ADS result
    3340             :  * @param ads connection to ads server
    3341             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    3342             :  * @param msg Results of search
    3343             :  * @param field Attribute to retrieve
    3344             :  * @param sids pointer to sid array to allocate
    3345             :  * @return the count of SIDs pulled
    3346             :  **/
    3347           2 :  int ads_pull_sids(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3348             :                    LDAPMessage *msg, const char *field, struct dom_sid **sids)
    3349             : {
    3350           0 :         struct berval **values;
    3351           0 :         int count, i;
    3352             : 
    3353           2 :         values = ldap_get_values_len(ads->ldap.ld, msg, field);
    3354             : 
    3355           2 :         if (!values)
    3356           0 :                 return 0;
    3357             : 
    3358           6 :         for (i=0; values[i]; i++)
    3359             :                 /* nop */ ;
    3360             : 
    3361           2 :         if (i) {
    3362           2 :                 (*sids) = talloc_array(mem_ctx, struct dom_sid, i);
    3363           2 :                 if (!(*sids)) {
    3364           0 :                         ldap_value_free_len(values);
    3365           0 :                         return 0;
    3366             :                 }
    3367             :         } else {
    3368           0 :                 (*sids) = NULL;
    3369             :         }
    3370             : 
    3371           2 :         count = 0;
    3372           6 :         for (i=0; values[i]; i++) {
    3373           0 :                 ssize_t ret;
    3374           4 :                 ret = sid_parse((const uint8_t *)values[i]->bv_val,
    3375           4 :                                 values[i]->bv_len, &(*sids)[count]);
    3376           4 :                 if (ret != -1) {
    3377           0 :                         struct dom_sid_buf buf;
    3378           4 :                         DBG_DEBUG("pulling SID: %s\n",
    3379             :                                   dom_sid_str_buf(&(*sids)[count], &buf));
    3380           4 :                         count++;
    3381             :                 }
    3382             :         }
    3383             : 
    3384           2 :         ldap_value_free_len(values);
    3385           2 :         return count;
    3386             : }
    3387             : 
    3388             : /**
    3389             :  * pull a struct security_descriptor from a ADS result
    3390             :  * @param ads connection to ads server
    3391             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    3392             :  * @param msg Results of search
    3393             :  * @param field Attribute to retrieve
    3394             :  * @param sd Pointer to *struct security_descriptor to store result (talloc()ed)
    3395             :  * @return boolean indicating success
    3396             : */
    3397           4 :  bool ads_pull_sd(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3398             :                   LDAPMessage *msg, const char *field,
    3399             :                   struct security_descriptor **sd)
    3400             : {
    3401           0 :         struct berval **values;
    3402           4 :         bool ret = true;
    3403             : 
    3404           4 :         values = ldap_get_values_len(ads->ldap.ld, msg, field);
    3405             : 
    3406           4 :         if (!values) return false;
    3407             : 
    3408           4 :         if (values[0]) {
    3409           0 :                 NTSTATUS status;
    3410           4 :                 status = unmarshall_sec_desc(mem_ctx,
    3411           4 :                                              (uint8_t *)values[0]->bv_val,
    3412           4 :                                              values[0]->bv_len, sd);
    3413           4 :                 if (!NT_STATUS_IS_OK(status)) {
    3414           0 :                         DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
    3415             :                                   nt_errstr(status)));
    3416           0 :                         ret = false;
    3417             :                 }
    3418             :         }
    3419             : 
    3420           4 :         ldap_value_free_len(values);
    3421           4 :         return ret;
    3422             : }
    3423             : 
    3424             : /*
    3425             :  * in order to support usernames longer than 21 characters we need to
    3426             :  * use both the sAMAccountName and the userPrincipalName attributes
    3427             :  * It seems that not all users have the userPrincipalName attribute set
    3428             :  *
    3429             :  * @param ads connection to ads server
    3430             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    3431             :  * @param msg Results of search
    3432             :  * @return the username
    3433             :  */
    3434           0 :  char *ads_pull_username(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3435             :                          LDAPMessage *msg)
    3436             : {
    3437             : #if 0   /* JERRY */
    3438             :         char *ret, *p;
    3439             : 
    3440             :         /* lookup_name() only works on the sAMAccountName to
    3441             :            returning the username portion of userPrincipalName
    3442             :            breaks winbindd_getpwnam() */
    3443             : 
    3444             :         ret = ads_pull_string(ads, mem_ctx, msg, "userPrincipalName");
    3445             :         if (ret && (p = strchr_m(ret, '@'))) {
    3446             :                 *p = 0;
    3447             :                 return ret;
    3448             :         }
    3449             : #endif
    3450           0 :         return ads_pull_string(ads, mem_ctx, msg, "sAMAccountName");
    3451             : }
    3452             : 
    3453             : 
    3454             : /**
    3455             :  * find the update serial number - this is the core of the ldap cache
    3456             :  * @param ads connection to ads server
    3457             :  * @param ads connection to ADS server
    3458             :  * @param usn Pointer to retrieved update serial number
    3459             :  * @return status of search
    3460             :  **/
    3461           0 : ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32_t *usn)
    3462             : {
    3463           0 :         const char *attrs[] = {"highestCommittedUSN", NULL};
    3464           0 :         ADS_STATUS status;
    3465           0 :         LDAPMessage *res;
    3466             : 
    3467           0 :         status = ads_do_search_retry(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3468           0 :         if (!ADS_ERR_OK(status))
    3469           0 :                 return status;
    3470             : 
    3471           0 :         if (ads_count_replies(ads, res) != 1) {
    3472           0 :                 ads_msgfree(ads, res);
    3473           0 :                 return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3474             :         }
    3475             : 
    3476           0 :         if (!ads_pull_uint32(ads, res, "highestCommittedUSN", usn)) {
    3477           0 :                 ads_msgfree(ads, res);
    3478           0 :                 return ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
    3479             :         }
    3480             : 
    3481           0 :         ads_msgfree(ads, res);
    3482           0 :         return ADS_SUCCESS;
    3483             : }
    3484             : 
    3485             : /* parse a ADS timestring - typical string is
    3486             :    '20020917091222.0Z0' which means 09:12.22 17th September
    3487             :    2002, timezone 0 */
    3488         357 : static time_t ads_parse_time(const char *str)
    3489             : {
    3490           0 :         struct tm tm;
    3491             : 
    3492         357 :         ZERO_STRUCT(tm);
    3493             : 
    3494         357 :         if (sscanf(str, "%4d%2d%2d%2d%2d%2d",
    3495             :                    &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
    3496             :                    &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
    3497           0 :                 return 0;
    3498             :         }
    3499         357 :         tm.tm_year -= 1900;
    3500         357 :         tm.tm_mon -= 1;
    3501             : 
    3502         357 :         return timegm(&tm);
    3503             : }
    3504             : 
    3505             : /********************************************************************
    3506             : ********************************************************************/
    3507             : 
    3508         357 : ADS_STATUS ads_current_time(ADS_STRUCT *ads)
    3509             : {
    3510         357 :         const char *attrs[] = {"currentTime", NULL};
    3511           0 :         ADS_STATUS status;
    3512           0 :         LDAPMessage *res;
    3513           0 :         char *timestr;
    3514         357 :         TALLOC_CTX *tmp_ctx = talloc_stackframe();
    3515         357 :         ADS_STRUCT *ads_s = ads;
    3516             : 
    3517             :         /* establish a new ldap tcp session if necessary */
    3518             : 
    3519         357 :         if ( !ads->ldap.ld ) {
    3520             :                 /*
    3521             :                  * ADS_STRUCT may be being reused after a
    3522             :                  * DC lookup, so ads->ldap.ss may already have a
    3523             :                  * good address. If not, re-initialize the passed-in
    3524             :                  * ADS_STRUCT with the given server.XXXX parameters.
    3525             :                  *
    3526             :                  * Note that this doesn't depend on
    3527             :                  * ads->server.ldap_server != NULL,
    3528             :                  * as the case where ads->server.ldap_server==NULL and
    3529             :                  * ads->ldap.ss != zero_address is precisely the DC
    3530             :                  * lookup case where ads->ldap.ss was found by going
    3531             :                  * through ads_find_dc() again we want to avoid repeating.
    3532             :                  */
    3533          15 :                 if (is_zero_addr(&ads->ldap.ss)) {
    3534           0 :                         ads_s = ads_init(tmp_ctx,
    3535             :                                          ads->server.realm,
    3536             :                                          ads->server.workgroup,
    3537             :                                          ads->server.ldap_server,
    3538             :                                          ADS_SASL_PLAIN );
    3539           0 :                         if (ads_s == NULL) {
    3540           0 :                                 status = ADS_ERROR(LDAP_NO_MEMORY);
    3541           0 :                                 goto done;
    3542             :                         }
    3543             :                 }
    3544             : 
    3545             :                 /*
    3546             :                  * Reset ads->config.flags as it can contain the flags
    3547             :                  * returned by the previous CLDAP ping when reusing the struct.
    3548             :                  */
    3549          15 :                 ads_s->config.flags = 0;
    3550             : 
    3551          15 :                 ads_s->auth.flags = ADS_AUTH_ANON_BIND;
    3552          15 :                 status = ads_connect( ads_s );
    3553          15 :                 if ( !ADS_ERR_OK(status))
    3554           0 :                         goto done;
    3555             :         }
    3556             : 
    3557         357 :         status = ads_do_search(ads_s, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3558         357 :         if (!ADS_ERR_OK(status)) {
    3559           0 :                 goto done;
    3560             :         }
    3561             : 
    3562         357 :         timestr = ads_pull_string(ads_s, tmp_ctx, res, "currentTime");
    3563         357 :         if (!timestr) {
    3564           0 :                 ads_msgfree(ads_s, res);
    3565           0 :                 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3566           0 :                 goto done;
    3567             :         }
    3568             : 
    3569             :         /* but save the time and offset in the original ADS_STRUCT */
    3570             : 
    3571         357 :         ads->config.current_time = ads_parse_time(timestr);
    3572             : 
    3573         357 :         if (ads->config.current_time != 0) {
    3574         357 :                 ads->auth.time_offset = ads->config.current_time - time(NULL);
    3575         357 :                 DEBUG(4,("KDC time offset is %d seconds\n", ads->auth.time_offset));
    3576             :         }
    3577             : 
    3578         357 :         ads_msgfree(ads, res);
    3579             : 
    3580         357 :         status = ADS_SUCCESS;
    3581             : 
    3582         357 : done:
    3583         357 :         TALLOC_FREE(tmp_ctx);
    3584             : 
    3585         357 :         return status;
    3586             : }
    3587             : 
    3588             : /********************************************************************
    3589             : ********************************************************************/
    3590             : 
    3591         116 : ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
    3592             : {
    3593         116 :         TALLOC_CTX *tmp_ctx = talloc_stackframe();
    3594         116 :         const char *attrs[] = {"domainFunctionality", NULL};
    3595           0 :         ADS_STATUS status;
    3596           0 :         LDAPMessage *res;
    3597         116 :         ADS_STRUCT *ads_s = ads;
    3598             : 
    3599         116 :         *val = DS_DOMAIN_FUNCTION_2000;
    3600             : 
    3601             :         /* establish a new ldap tcp session if necessary */
    3602             : 
    3603         116 :         if ( !ads->ldap.ld ) {
    3604             :                 /*
    3605             :                  * ADS_STRUCT may be being reused after a
    3606             :                  * DC lookup, so ads->ldap.ss may already have a
    3607             :                  * good address. If not, re-initialize the passed-in
    3608             :                  * ADS_STRUCT with the given server.XXXX parameters.
    3609             :                  *
    3610             :                  * Note that this doesn't depend on
    3611             :                  * ads->server.ldap_server != NULL,
    3612             :                  * as the case where ads->server.ldap_server==NULL and
    3613             :                  * ads->ldap.ss != zero_address is precisely the DC
    3614             :                  * lookup case where ads->ldap.ss was found by going
    3615             :                  * through ads_find_dc() again we want to avoid repeating.
    3616             :                  */
    3617           0 :                 if (is_zero_addr(&ads->ldap.ss)) {
    3618           0 :                         ads_s = ads_init(tmp_ctx,
    3619             :                                          ads->server.realm,
    3620             :                                          ads->server.workgroup,
    3621             :                                          ads->server.ldap_server,
    3622             :                                          ADS_SASL_PLAIN );
    3623           0 :                         if (ads_s == NULL ) {
    3624           0 :                                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    3625           0 :                                 goto done;
    3626             :                         }
    3627             :                 }
    3628             : 
    3629             :                 /*
    3630             :                  * Reset ads->config.flags as it can contain the flags
    3631             :                  * returned by the previous CLDAP ping when reusing the struct.
    3632             :                  */
    3633           0 :                 ads_s->config.flags = 0;
    3634             : 
    3635           0 :                 ads_s->auth.flags = ADS_AUTH_ANON_BIND;
    3636           0 :                 status = ads_connect( ads_s );
    3637           0 :                 if ( !ADS_ERR_OK(status))
    3638           0 :                         goto done;
    3639             :         }
    3640             : 
    3641             :         /* If the attribute does not exist assume it is a Windows 2000
    3642             :            functional domain */
    3643             : 
    3644         116 :         status = ads_do_search(ads_s, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3645         116 :         if (!ADS_ERR_OK(status)) {
    3646           0 :                 if ( status.err.rc == LDAP_NO_SUCH_ATTRIBUTE ) {
    3647           0 :                         status = ADS_SUCCESS;
    3648             :                 }
    3649           0 :                 goto done;
    3650             :         }
    3651             : 
    3652         116 :         if ( !ads_pull_uint32(ads_s, res, "domainFunctionality", val) ) {
    3653           0 :                 DEBUG(5,("ads_domain_func_level: Failed to pull the domainFunctionality attribute.\n"));
    3654             :         }
    3655         116 :         DEBUG(3,("ads_domain_func_level: %d\n", *val));
    3656             : 
    3657             : 
    3658         116 :         ads_msgfree(ads_s, res);
    3659             : 
    3660         116 : done:
    3661         116 :         TALLOC_FREE(tmp_ctx);
    3662             : 
    3663         116 :         return status;
    3664             : }
    3665             : 
    3666             : /**
    3667             :  * find the domain sid for our domain
    3668             :  * @param ads connection to ads server
    3669             :  * @param sid Pointer to domain sid
    3670             :  * @return status of search
    3671             :  **/
    3672           0 : ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
    3673             : {
    3674           0 :         const char *attrs[] = {"objectSid", NULL};
    3675           0 :         LDAPMessage *res;
    3676           0 :         ADS_STATUS rc;
    3677             : 
    3678           0 :         rc = ads_do_search_retry(ads, ads->config.bind_path, LDAP_SCOPE_BASE, "(objectclass=*)",
    3679             :                            attrs, &res);
    3680           0 :         if (!ADS_ERR_OK(rc)) return rc;
    3681           0 :         if (!ads_pull_sid(ads, res, "objectSid", sid)) {
    3682           0 :                 ads_msgfree(ads, res);
    3683           0 :                 return ADS_ERROR_SYSTEM(ENOENT);
    3684             :         }
    3685           0 :         ads_msgfree(ads, res);
    3686             : 
    3687           0 :         return ADS_SUCCESS;
    3688             : }
    3689             : 
    3690             : /**
    3691             :  * find our site name
    3692             :  * @param ads connection to ads server
    3693             :  * @param mem_ctx Pointer to talloc context
    3694             :  * @param site_name Pointer to the sitename
    3695             :  * @return status of search
    3696             :  **/
    3697           2 : ADS_STATUS ads_site_dn(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char **site_name)
    3698             : {
    3699           0 :         ADS_STATUS status;
    3700           0 :         LDAPMessage *res;
    3701           0 :         const char *dn, *service_name;
    3702           2 :         const char *attrs[] = { "dsServiceName", NULL };
    3703             : 
    3704           2 :         status = ads_do_search(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3705           2 :         if (!ADS_ERR_OK(status)) {
    3706           0 :                 return status;
    3707             :         }
    3708             : 
    3709           2 :         service_name = ads_pull_string(ads, mem_ctx, res, "dsServiceName");
    3710           2 :         if (service_name == NULL) {
    3711           0 :                 ads_msgfree(ads, res);
    3712           0 :                 return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3713             :         }
    3714             : 
    3715           2 :         ads_msgfree(ads, res);
    3716             : 
    3717             :         /* go up three levels */
    3718           2 :         dn = ads_parent_dn(ads_parent_dn(ads_parent_dn(service_name)));
    3719           2 :         if (dn == NULL) {
    3720           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3721             :         }
    3722             : 
    3723           2 :         *site_name = talloc_strdup(mem_ctx, dn);
    3724           2 :         if (*site_name == NULL) {
    3725           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3726             :         }
    3727             : 
    3728           2 :         return status;
    3729             :         /*
    3730             :         dsServiceName: CN=NTDS Settings,CN=W2K3DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ber,DC=suse,DC=de
    3731             :         */
    3732             : }
    3733             : 
    3734             : /**
    3735             :  * find the site dn where a machine resides
    3736             :  * @param ads connection to ads server
    3737             :  * @param mem_ctx Pointer to talloc context
    3738             :  * @param computer_name name of the machine
    3739             :  * @param site_name Pointer to the sitename
    3740             :  * @return status of search
    3741             :  **/
    3742           2 : ADS_STATUS ads_site_dn_for_machine(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char *computer_name, const char **site_dn)
    3743             : {
    3744           0 :         ADS_STATUS status;
    3745           0 :         LDAPMessage *res;
    3746           0 :         const char *parent, *filter;
    3747           2 :         char *config_context = NULL;
    3748           0 :         char *dn;
    3749             : 
    3750             :         /* shortcut a query */
    3751           2 :         if (strequal(computer_name, ads->config.ldap_server_name)) {
    3752           2 :                 return ads_site_dn(ads, mem_ctx, site_dn);
    3753             :         }
    3754             : 
    3755           0 :         status = ads_config_path(ads, mem_ctx, &config_context);
    3756           0 :         if (!ADS_ERR_OK(status)) {
    3757           0 :                 return status;
    3758             :         }
    3759             : 
    3760           0 :         filter = talloc_asprintf(mem_ctx, "(cn=%s)", computer_name);
    3761           0 :         if (filter == NULL) {
    3762           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3763             :         }
    3764             : 
    3765           0 :         status = ads_do_search(ads, config_context, LDAP_SCOPE_SUBTREE,
    3766             :                                filter, NULL, &res);
    3767           0 :         if (!ADS_ERR_OK(status)) {
    3768           0 :                 return status;
    3769             :         }
    3770             : 
    3771           0 :         if (ads_count_replies(ads, res) != 1) {
    3772           0 :                 ads_msgfree(ads, res);
    3773           0 :                 return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    3774             :         }
    3775             : 
    3776           0 :         dn = ads_get_dn(ads, mem_ctx, res);
    3777           0 :         if (dn == NULL) {
    3778           0 :                 ads_msgfree(ads, res);
    3779           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3780             :         }
    3781             : 
    3782             :         /* go up three levels */
    3783           0 :         parent = ads_parent_dn(ads_parent_dn(ads_parent_dn(dn)));
    3784           0 :         if (parent == NULL) {
    3785           0 :                 ads_msgfree(ads, res);
    3786           0 :                 TALLOC_FREE(dn);
    3787           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3788             :         }
    3789             : 
    3790           0 :         *site_dn = talloc_strdup(mem_ctx, parent);
    3791           0 :         if (*site_dn == NULL) {
    3792           0 :                 ads_msgfree(ads, res);
    3793           0 :                 TALLOC_FREE(dn);
    3794           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3795             :         }
    3796             : 
    3797           0 :         TALLOC_FREE(dn);
    3798           0 :         ads_msgfree(ads, res);
    3799             : 
    3800           0 :         return status;
    3801             : }
    3802             : 
    3803             : /**
    3804             :  * get the upn suffixes for a domain
    3805             :  * @param ads connection to ads server
    3806             :  * @param mem_ctx Pointer to talloc context
    3807             :  * @param suffixes Pointer to an array of suffixes
    3808             :  * @param num_suffixes Pointer to the number of suffixes
    3809             :  * @return status of search
    3810             :  **/
    3811           0 : ADS_STATUS ads_upn_suffixes(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, char ***suffixes, size_t *num_suffixes)
    3812             : {
    3813           0 :         ADS_STATUS status;
    3814           0 :         LDAPMessage *res;
    3815           0 :         const char *base;
    3816           0 :         char *config_context = NULL;
    3817           0 :         const char *attrs[] = { "uPNSuffixes", NULL };
    3818             : 
    3819           0 :         status = ads_config_path(ads, mem_ctx, &config_context);
    3820           0 :         if (!ADS_ERR_OK(status)) {
    3821           0 :                 return status;
    3822             :         }
    3823             : 
    3824           0 :         base = talloc_asprintf(mem_ctx, "cn=Partitions,%s", config_context);
    3825           0 :         if (base == NULL) {
    3826           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3827             :         }
    3828             : 
    3829           0 :         status = ads_search_dn(ads, &res, base, attrs);
    3830           0 :         if (!ADS_ERR_OK(status)) {
    3831           0 :                 return status;
    3832             :         }
    3833             : 
    3834           0 :         if (ads_count_replies(ads, res) != 1) {
    3835           0 :                 ads_msgfree(ads, res);
    3836           0 :                 return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    3837             :         }
    3838             : 
    3839           0 :         (*suffixes) = ads_pull_strings(ads, mem_ctx, res, "uPNSuffixes", num_suffixes);
    3840           0 :         if ((*suffixes) == NULL) {
    3841           0 :                 ads_msgfree(ads, res);
    3842           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3843             :         }
    3844             : 
    3845           0 :         ads_msgfree(ads, res);
    3846             : 
    3847           0 :         return status;
    3848             : }
    3849             : 
    3850             : /**
    3851             :  * get the joinable ous for a domain
    3852             :  * @param ads connection to ads server
    3853             :  * @param mem_ctx Pointer to talloc context
    3854             :  * @param ous Pointer to an array of ous
    3855             :  * @param num_ous Pointer to the number of ous
    3856             :  * @return status of search
    3857             :  **/
    3858           0 : ADS_STATUS ads_get_joinable_ous(ADS_STRUCT *ads,
    3859             :                                 TALLOC_CTX *mem_ctx,
    3860             :                                 char ***ous,
    3861             :                                 size_t *num_ous)
    3862             : {
    3863           0 :         ADS_STATUS status;
    3864           0 :         LDAPMessage *res = NULL;
    3865           0 :         LDAPMessage *msg = NULL;
    3866           0 :         const char *attrs[] = { "dn", NULL };
    3867           0 :         int count = 0;
    3868             : 
    3869           0 :         status = ads_search(ads, &res,
    3870             :                             "(|(objectClass=domain)(objectclass=organizationalUnit))",
    3871             :                             attrs);
    3872           0 :         if (!ADS_ERR_OK(status)) {
    3873           0 :                 return status;
    3874             :         }
    3875             : 
    3876           0 :         count = ads_count_replies(ads, res);
    3877           0 :         if (count < 1) {
    3878           0 :                 ads_msgfree(ads, res);
    3879           0 :                 return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3880             :         }
    3881             : 
    3882           0 :         for (msg = ads_first_entry(ads, res); msg;
    3883           0 :              msg = ads_next_entry(ads, msg)) {
    3884           0 :                 const char **p = discard_const_p(const char *, *ous);
    3885           0 :                 char *dn = NULL;
    3886             : 
    3887           0 :                 dn = ads_get_dn(ads, talloc_tos(), msg);
    3888           0 :                 if (!dn) {
    3889           0 :                         ads_msgfree(ads, res);
    3890           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    3891             :                 }
    3892             : 
    3893           0 :                 if (!add_string_to_array(mem_ctx, dn, &p, num_ous)) {
    3894           0 :                         TALLOC_FREE(dn);
    3895           0 :                         ads_msgfree(ads, res);
    3896           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    3897             :                 }
    3898             : 
    3899           0 :                 TALLOC_FREE(dn);
    3900           0 :                 *ous = discard_const_p(char *, p);
    3901             :         }
    3902             : 
    3903           0 :         ads_msgfree(ads, res);
    3904             : 
    3905           0 :         return status;
    3906             : }
    3907             : 
    3908             : 
    3909             : /**
    3910             :  * pull a struct dom_sid from an extended dn string
    3911             :  * @param mem_ctx TALLOC_CTX
    3912             :  * @param extended_dn string
    3913             :  * @param flags string type of extended_dn
    3914             :  * @param sid pointer to a struct dom_sid
    3915             :  * @return NT_STATUS_OK on success,
    3916             :  *         NT_INVALID_PARAMETER on error,
    3917             :  *         NT_STATUS_NOT_FOUND if no SID present
    3918             :  **/
    3919           0 : ADS_STATUS ads_get_sid_from_extended_dn(TALLOC_CTX *mem_ctx,
    3920             :                                         const char *extended_dn,
    3921             :                                         enum ads_extended_dn_flags flags,
    3922             :                                         struct dom_sid *sid)
    3923             : {
    3924           0 :         char *p, *q, *dn;
    3925             : 
    3926           0 :         if (!extended_dn) {
    3927           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3928             :         }
    3929             : 
    3930             :         /* otherwise extended_dn gets stripped off */
    3931           0 :         if ((dn = talloc_strdup(mem_ctx, extended_dn)) == NULL) {
    3932           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3933             :         }
    3934             :         /*
    3935             :          * ADS_EXTENDED_DN_HEX_STRING:
    3936             :          * <GUID=238e1963cb390f4bb032ba0105525a29>;<SID=010500000000000515000000bb68c8fd6b61b427572eb04556040000>;CN=gd,OU=berlin,OU=suse,DC=ber,DC=suse,DC=de
    3937             :          *
    3938             :          * ADS_EXTENDED_DN_STRING (only with w2k3):
    3939             :          * <GUID=63198e23-39cb-4b0f-b032-ba0105525a29>;<SID=S-1-5-21-4257769659-666132843-1169174103-1110>;CN=gd,OU=berlin,OU=suse,DC=ber,DC=suse,DC=de
    3940             :          *
    3941             :          * Object with no SID, such as an Exchange Public Folder
    3942             :          * <GUID=28907fb4bdf6854993e7f0a10b504e7c>;CN=public,CN=Microsoft Exchange System Objects,DC=sd2k3ms,DC=west,DC=isilon,DC=com
    3943             :          */
    3944             : 
    3945           0 :         p = strchr(dn, ';');
    3946           0 :         if (!p) {
    3947           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3948             :         }
    3949             : 
    3950           0 :         if (strncmp(p, ";<SID=", strlen(";<SID=")) != 0) {
    3951           0 :                 DEBUG(5,("No SID present in extended dn\n"));
    3952           0 :                 return ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
    3953             :         }
    3954             : 
    3955           0 :         p += strlen(";<SID=");
    3956             : 
    3957           0 :         q = strchr(p, '>');
    3958           0 :         if (!q) {
    3959           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3960             :         }
    3961             : 
    3962           0 :         *q = '\0';
    3963             : 
    3964           0 :         DEBUG(100,("ads_get_sid_from_extended_dn: sid string is %s\n", p));
    3965             : 
    3966           0 :         switch (flags) {
    3967             : 
    3968           0 :         case ADS_EXTENDED_DN_STRING:
    3969           0 :                 if (!string_to_sid(sid, p)) {
    3970           0 :                         return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3971             :                 }
    3972           0 :                 break;
    3973           0 :         case ADS_EXTENDED_DN_HEX_STRING: {
    3974           0 :                 ssize_t ret;
    3975           0 :                 fstring buf;
    3976           0 :                 size_t buf_len;
    3977             : 
    3978           0 :                 buf_len = strhex_to_str(buf, sizeof(buf), p, strlen(p));
    3979           0 :                 if (buf_len == 0) {
    3980           0 :                         return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3981             :                 }
    3982             : 
    3983           0 :                 ret = sid_parse((const uint8_t *)buf, buf_len, sid);
    3984           0 :                 if (ret == -1) {
    3985           0 :                         DEBUG(10,("failed to parse sid\n"));
    3986           0 :                         return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3987             :                 }
    3988           0 :                 break;
    3989             :                 }
    3990           0 :         default:
    3991           0 :                 DEBUG(10,("unknown extended dn format\n"));
    3992           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3993             :         }
    3994             : 
    3995           0 :         return ADS_ERROR_NT(NT_STATUS_OK);
    3996             : }
    3997             : 
    3998             : /********************************************************************
    3999             : ********************************************************************/
    4000             : 
    4001          70 : char* ads_get_dnshostname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
    4002             : {
    4003          70 :         LDAPMessage *res = NULL;
    4004           0 :         ADS_STATUS status;
    4005          70 :         int count = 0;
    4006          70 :         char *name = NULL;
    4007             : 
    4008          70 :         status = ads_find_machine_acct(ads, &res, machine_name);
    4009          70 :         if (!ADS_ERR_OK(status)) {
    4010           0 :                 DEBUG(0,("ads_get_dnshostname: Failed to find account for %s\n",
    4011             :                         lp_netbios_name()));
    4012           0 :                 goto out;
    4013             :         }
    4014             : 
    4015          70 :         if ( (count = ads_count_replies(ads, res)) != 1 ) {
    4016           0 :                 DEBUG(1,("ads_get_dnshostname: %d entries returned!\n", count));
    4017           0 :                 goto out;
    4018             :         }
    4019             : 
    4020          70 :         if ( (name = ads_pull_string(ads, ctx, res, "dNSHostName")) == NULL ) {
    4021           0 :                 DEBUG(0,("ads_get_dnshostname: No dNSHostName attribute!\n"));
    4022             :         }
    4023             : 
    4024          70 : out:
    4025          70 :         ads_msgfree(ads, res);
    4026             : 
    4027          70 :         return name;
    4028             : }
    4029             : 
    4030             : /********************************************************************
    4031             : ********************************************************************/
    4032             : 
    4033         124 : static char **get_addl_hosts(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    4034             :                               LDAPMessage *msg, size_t *num_values)
    4035             : {
    4036         124 :         const char *field = "msDS-AdditionalDnsHostName";
    4037         124 :         struct berval **values = NULL;
    4038         124 :         char **ret = NULL;
    4039           0 :         size_t i, converted_size;
    4040             : 
    4041             :         /*
    4042             :          * Windows DC implicitly adds a short name for each FQDN added to
    4043             :          * msDS-AdditionalDnsHostName, but it comes with a strange binary
    4044             :          * suffix "\0$" which we should ignore (see bug #14406).
    4045             :          */
    4046             : 
    4047         124 :         values = ldap_get_values_len(ads->ldap.ld, msg, field);
    4048         124 :         if (values == NULL) {
    4049          96 :                 return NULL;
    4050             :         }
    4051             : 
    4052          28 :         *num_values = ldap_count_values_len(values);
    4053             : 
    4054          28 :         ret = talloc_array(mem_ctx, char *, *num_values + 1);
    4055          28 :         if (ret == NULL) {
    4056           0 :                 ldap_value_free_len(values);
    4057           0 :                 return NULL;
    4058             :         }
    4059             : 
    4060         112 :         for (i = 0; i < *num_values; i++) {
    4061          84 :                 ret[i] = NULL;
    4062          84 :                 if (!convert_string_talloc(mem_ctx, CH_UTF8, CH_UNIX,
    4063          84 :                                            values[i]->bv_val,
    4064          84 :                                            strnlen(values[i]->bv_val,
    4065          84 :                                                    values[i]->bv_len),
    4066          84 :                                            &ret[i], &converted_size)) {
    4067           0 :                         ldap_value_free_len(values);
    4068           0 :                         return NULL;
    4069             :                 }
    4070             :         }
    4071          28 :         ret[i] = NULL;
    4072             : 
    4073          28 :         ldap_value_free_len(values);
    4074          28 :         return ret;
    4075             : }
    4076             : 
    4077         124 : ADS_STATUS ads_get_additional_dns_hostnames(TALLOC_CTX *mem_ctx,
    4078             :                                             ADS_STRUCT *ads,
    4079             :                                             const char *machine_name,
    4080             :                                             char ***hostnames_array,
    4081             :                                             size_t *num_hostnames)
    4082             : {
    4083           0 :         ADS_STATUS status;
    4084         124 :         LDAPMessage *res = NULL;
    4085           0 :         int count;
    4086             : 
    4087         124 :         status = ads_find_machine_acct(ads,
    4088             :                                        &res,
    4089             :                                        machine_name);
    4090         124 :         if (!ADS_ERR_OK(status)) {
    4091           0 :                 DEBUG(1,("Host Account for %s not found... skipping operation.\n",
    4092             :                          machine_name));
    4093           0 :                 return status;
    4094             :         }
    4095             : 
    4096         124 :         count = ads_count_replies(ads, res);
    4097         124 :         if (count != 1) {
    4098           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    4099           0 :                 goto done;
    4100             :         }
    4101             : 
    4102         124 :         *hostnames_array = get_addl_hosts(ads, mem_ctx, res, num_hostnames);
    4103         124 :         if (*hostnames_array == NULL) {
    4104          96 :                 DEBUG(1, ("Host account for %s does not have msDS-AdditionalDnsHostName.\n",
    4105             :                           machine_name));
    4106          96 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    4107          96 :                 goto done;
    4108             :         }
    4109             : 
    4110          28 : done:
    4111         124 :         ads_msgfree(ads, res);
    4112             : 
    4113         124 :         return status;
    4114             : }
    4115             : 
    4116             : /********************************************************************
    4117             : ********************************************************************/
    4118             : 
    4119          10 : char* ads_get_upn( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
    4120             : {
    4121          10 :         LDAPMessage *res = NULL;
    4122           0 :         ADS_STATUS status;
    4123          10 :         int count = 0;
    4124          10 :         char *name = NULL;
    4125             : 
    4126          10 :         status = ads_find_machine_acct(ads, &res, machine_name);
    4127          10 :         if (!ADS_ERR_OK(status)) {
    4128           0 :                 DEBUG(0,("ads_get_upn: Failed to find account for %s\n",
    4129             :                         lp_netbios_name()));
    4130           0 :                 goto out;
    4131             :         }
    4132             : 
    4133          10 :         if ( (count = ads_count_replies(ads, res)) != 1 ) {
    4134           0 :                 DEBUG(1,("ads_get_upn: %d entries returned!\n", count));
    4135           0 :                 goto out;
    4136             :         }
    4137             : 
    4138          10 :         if ( (name = ads_pull_string(ads, ctx, res, "userPrincipalName")) == NULL ) {
    4139           8 :                 DEBUG(2,("ads_get_upn: No userPrincipalName attribute!\n"));
    4140             :         }
    4141             : 
    4142           2 : out:
    4143          10 :         ads_msgfree(ads, res);
    4144             : 
    4145          10 :         return name;
    4146             : }
    4147             : 
    4148             : /********************************************************************
    4149             : ********************************************************************/
    4150             : 
    4151          74 : bool ads_has_samaccountname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
    4152             : {
    4153          74 :         LDAPMessage *res = NULL;
    4154           0 :         ADS_STATUS status;
    4155          74 :         int count = 0;
    4156          74 :         char *name = NULL;
    4157          74 :         bool ok = false;
    4158             : 
    4159          74 :         status = ads_find_machine_acct(ads, &res, machine_name);
    4160          74 :         if (!ADS_ERR_OK(status)) {
    4161           0 :                 DEBUG(0,("ads_has_samaccountname: Failed to find account for %s\n",
    4162             :                         lp_netbios_name()));
    4163           0 :                 goto out;
    4164             :         }
    4165             : 
    4166          74 :         if ( (count = ads_count_replies(ads, res)) != 1 ) {
    4167           0 :                 DEBUG(1,("ads_has_samaccountname: %d entries returned!\n", count));
    4168           0 :                 goto out;
    4169             :         }
    4170             : 
    4171          74 :         if ( (name = ads_pull_string(ads, ctx, res, "sAMAccountName")) == NULL ) {
    4172           0 :                 DEBUG(0,("ads_has_samaccountname: No sAMAccountName attribute!\n"));
    4173             :         }
    4174             : 
    4175          74 : out:
    4176          74 :         ads_msgfree(ads, res);
    4177          74 :         if (name != NULL) {
    4178          74 :                 ok = (strlen(name) > 0);
    4179             :         }
    4180          74 :         TALLOC_FREE(name);
    4181          74 :         return ok;
    4182             : }
    4183             : 
    4184             : #if 0
    4185             : 
    4186             :    SAVED CODE - we used to join via ldap - remember how we did this. JRA.
    4187             : 
    4188             : /**
    4189             :  * Join a machine to a realm
    4190             :  *  Creates the machine account and sets the machine password
    4191             :  * @param ads connection to ads server
    4192             :  * @param machine name of host to add
    4193             :  * @param org_unit Organizational unit to place machine in
    4194             :  * @return status of join
    4195             :  **/
    4196             : ADS_STATUS ads_join_realm(ADS_STRUCT *ads, const char *machine_name,
    4197             :                         uint32_t account_type, const char *org_unit)
    4198             : {
    4199             :         ADS_STATUS status;
    4200             :         LDAPMessage *res = NULL;
    4201             :         char *machine;
    4202             : 
    4203             :         /* machine name must be lowercase */
    4204             :         machine = SMB_STRDUP(machine_name);
    4205             :         strlower_m(machine);
    4206             : 
    4207             :         /*
    4208             :         status = ads_find_machine_acct(ads, (void **)&res, machine);
    4209             :         if (ADS_ERR_OK(status) && ads_count_replies(ads, res) == 1) {
    4210             :                 DEBUG(0, ("Host account for %s already exists - deleting old account\n", machine));
    4211             :                 status = ads_leave_realm(ads, machine);
    4212             :                 if (!ADS_ERR_OK(status)) {
    4213             :                         DEBUG(0, ("Failed to delete host '%s' from the '%s' realm.\n",
    4214             :                                 machine, ads->config.realm));
    4215             :                         return status;
    4216             :                 }
    4217             :         }
    4218             :         */
    4219             :         status = ads_add_machine_acct(ads, machine, account_type, org_unit);
    4220             :         if (!ADS_ERR_OK(status)) {
    4221             :                 DEBUG(0, ("ads_join_realm: ads_add_machine_acct failed (%s): %s\n", machine, ads_errstr(status)));
    4222             :                 SAFE_FREE(machine);
    4223             :                 return status;
    4224             :         }
    4225             : 
    4226             :         status = ads_find_machine_acct(ads, (void **)(void *)&res, machine);
    4227             :         if (!ADS_ERR_OK(status)) {
    4228             :                 DEBUG(0, ("ads_join_realm: Host account test failed for machine %s\n", machine));
    4229             :                 SAFE_FREE(machine);
    4230             :                 return status;
    4231             :         }
    4232             : 
    4233             :         SAFE_FREE(machine);
    4234             :         ads_msgfree(ads, res);
    4235             : 
    4236             :         return status;
    4237             : }
    4238             : #endif
    4239             : 
    4240             : /**
    4241             :  * Delete a machine from the realm
    4242             :  * @param ads connection to ads server
    4243             :  * @param hostname Machine to remove
    4244             :  * @return status of delete
    4245             :  **/
    4246          32 : ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
    4247             : {
    4248           0 :         ADS_STATUS status;
    4249           0 :         void *msg;
    4250           0 :         LDAPMessage *res;
    4251           0 :         char *hostnameDN, *host;
    4252           0 :         int rc;
    4253           0 :         LDAPControl ldap_control;
    4254          32 :         LDAPControl  * pldap_control[2] = {NULL, NULL};
    4255             : 
    4256          32 :         pldap_control[0] = &ldap_control;
    4257          32 :         memset(&ldap_control, 0, sizeof(LDAPControl));
    4258          32 :         ldap_control.ldctl_oid = discard_const_p(char, LDAP_SERVER_TREE_DELETE_OID);
    4259             : 
    4260             :         /* hostname must be lowercase */
    4261          32 :         host = SMB_STRDUP(hostname);
    4262          32 :         if (!strlower_m(host)) {
    4263           0 :                 SAFE_FREE(host);
    4264           0 :                 return ADS_ERROR_SYSTEM(EINVAL);
    4265             :         }
    4266             : 
    4267          32 :         status = ads_find_machine_acct(ads, &res, host);
    4268          32 :         if (!ADS_ERR_OK(status)) {
    4269           0 :                 DEBUG(0, ("Host account for %s does not exist.\n", host));
    4270           0 :                 SAFE_FREE(host);
    4271           0 :                 return status;
    4272             :         }
    4273             : 
    4274          32 :         msg = ads_first_entry(ads, res);
    4275          32 :         if (!msg) {
    4276           0 :                 SAFE_FREE(host);
    4277           0 :                 return ADS_ERROR_SYSTEM(ENOENT);
    4278             :         }
    4279             : 
    4280          32 :         hostnameDN = ads_get_dn(ads, talloc_tos(), (LDAPMessage *)msg);
    4281          32 :         if (hostnameDN == NULL) {
    4282           0 :                 SAFE_FREE(host);
    4283           0 :                 return ADS_ERROR_SYSTEM(ENOENT);
    4284             :         }
    4285             : 
    4286          32 :         rc = ldap_delete_ext_s(ads->ldap.ld, hostnameDN, pldap_control, NULL);
    4287          32 :         if (rc) {
    4288           0 :                 DEBUG(3,("ldap_delete_ext_s failed with error code %d\n", rc));
    4289             :         }else {
    4290          32 :                 DEBUG(3,("ldap_delete_ext_s succeeded with error code %d\n", rc));
    4291             :         }
    4292             : 
    4293          32 :         if (rc != LDAP_SUCCESS) {
    4294           0 :                 const char *attrs[] = { "cn", NULL };
    4295           0 :                 LDAPMessage *msg_sub;
    4296             : 
    4297             :                 /* we only search with scope ONE, we do not expect any further
    4298             :                  * objects to be created deeper */
    4299             : 
    4300           0 :                 status = ads_do_search_retry(ads, hostnameDN,
    4301             :                                              LDAP_SCOPE_ONELEVEL,
    4302             :                                              "(objectclass=*)", attrs, &res);
    4303             : 
    4304           0 :                 if (!ADS_ERR_OK(status)) {
    4305           0 :                         SAFE_FREE(host);
    4306           0 :                         TALLOC_FREE(hostnameDN);
    4307           0 :                         return status;
    4308             :                 }
    4309             : 
    4310           0 :                 for (msg_sub = ads_first_entry(ads, res); msg_sub;
    4311           0 :                         msg_sub = ads_next_entry(ads, msg_sub)) {
    4312             : 
    4313           0 :                         char *dn = NULL;
    4314             : 
    4315           0 :                         if ((dn = ads_get_dn(ads, talloc_tos(), msg_sub)) == NULL) {
    4316           0 :                                 SAFE_FREE(host);
    4317           0 :                                 TALLOC_FREE(hostnameDN);
    4318           0 :                                 return ADS_ERROR(LDAP_NO_MEMORY);
    4319             :                         }
    4320             : 
    4321           0 :                         status = ads_del_dn(ads, dn);
    4322           0 :                         if (!ADS_ERR_OK(status)) {
    4323           0 :                                 DEBUG(3,("failed to delete dn %s: %s\n", dn, ads_errstr(status)));
    4324           0 :                                 SAFE_FREE(host);
    4325           0 :                                 TALLOC_FREE(dn);
    4326           0 :                                 TALLOC_FREE(hostnameDN);
    4327           0 :                                 return status;
    4328             :                         }
    4329             : 
    4330           0 :                         TALLOC_FREE(dn);
    4331             :                 }
    4332             : 
    4333             :                 /* there should be no subordinate objects anymore */
    4334           0 :                 status = ads_do_search_retry(ads, hostnameDN,
    4335             :                                              LDAP_SCOPE_ONELEVEL,
    4336             :                                              "(objectclass=*)", attrs, &res);
    4337             : 
    4338           0 :                 if (!ADS_ERR_OK(status) || ( (ads_count_replies(ads, res)) > 0 ) ) {
    4339           0 :                         SAFE_FREE(host);
    4340           0 :                         TALLOC_FREE(hostnameDN);
    4341           0 :                         return status;
    4342             :                 }
    4343             : 
    4344             :                 /* delete hostnameDN now */
    4345           0 :                 status = ads_del_dn(ads, hostnameDN);
    4346           0 :                 if (!ADS_ERR_OK(status)) {
    4347           0 :                         SAFE_FREE(host);
    4348           0 :                         DEBUG(3,("failed to delete dn %s: %s\n", hostnameDN, ads_errstr(status)));
    4349           0 :                         TALLOC_FREE(hostnameDN);
    4350           0 :                         return status;
    4351             :                 }
    4352             :         }
    4353             : 
    4354          32 :         TALLOC_FREE(hostnameDN);
    4355             : 
    4356          32 :         status = ads_find_machine_acct(ads, &res, host);
    4357          32 :         if ((status.error_type == ENUM_ADS_ERROR_LDAP) &&
    4358          32 :             (status.err.rc != LDAP_NO_SUCH_OBJECT)) {
    4359           0 :                 DEBUG(3, ("Failed to remove host account.\n"));
    4360           0 :                 SAFE_FREE(host);
    4361           0 :                 return status;
    4362             :         }
    4363             : 
    4364          32 :         SAFE_FREE(host);
    4365          32 :         return ADS_SUCCESS;
    4366             : }
    4367             : 
    4368             : /**
    4369             :  * pull all token-sids from an LDAP dn
    4370             :  * @param ads connection to ads server
    4371             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    4372             :  * @param dn of LDAP object
    4373             :  * @param user_sid pointer to struct dom_sid (objectSid)
    4374             :  * @param primary_group_sid pointer to struct dom_sid (self composed)
    4375             :  * @param sids pointer to sid array to allocate
    4376             :  * @param num_sids counter of SIDs pulled
    4377             :  * @return status of token query
    4378             :  **/
    4379           2 :  ADS_STATUS ads_get_tokensids(ADS_STRUCT *ads,
    4380             :                               TALLOC_CTX *mem_ctx,
    4381             :                               const char *dn,
    4382             :                               struct dom_sid *user_sid,
    4383             :                               struct dom_sid *primary_group_sid,
    4384             :                               struct dom_sid **sids,
    4385             :                               size_t *num_sids)
    4386             : {
    4387           0 :         ADS_STATUS status;
    4388           2 :         LDAPMessage *res = NULL;
    4389           2 :         int count = 0;
    4390           0 :         size_t tmp_num_sids;
    4391           0 :         struct dom_sid *tmp_sids;
    4392           0 :         struct dom_sid tmp_user_sid;
    4393           0 :         struct dom_sid tmp_primary_group_sid;
    4394           0 :         uint32_t pgid;
    4395           2 :         const char *attrs[] = {
    4396             :                 "objectSid",
    4397             :                 "tokenGroups",
    4398             :                 "primaryGroupID",
    4399             :                 NULL
    4400             :         };
    4401             : 
    4402           2 :         status = ads_search_retry_dn(ads, &res, dn, attrs);
    4403           2 :         if (!ADS_ERR_OK(status)) {
    4404           0 :                 return status;
    4405             :         }
    4406             : 
    4407           2 :         count = ads_count_replies(ads, res);
    4408           2 :         if (count != 1) {
    4409           0 :                 ads_msgfree(ads, res);
    4410           0 :                 return ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
    4411             :         }
    4412             : 
    4413           2 :         if (!ads_pull_sid(ads, res, "objectSid", &tmp_user_sid)) {
    4414           0 :                 ads_msgfree(ads, res);
    4415           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4416             :         }
    4417             : 
    4418           2 :         if (!ads_pull_uint32(ads, res, "primaryGroupID", &pgid)) {
    4419           0 :                 ads_msgfree(ads, res);
    4420           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4421             :         }
    4422             : 
    4423             :         {
    4424             :                 /* hack to compose the primary group sid without knowing the
    4425             :                  * domsid */
    4426             : 
    4427           0 :                 struct dom_sid domsid;
    4428             : 
    4429           2 :                 sid_copy(&domsid, &tmp_user_sid);
    4430             : 
    4431           2 :                 if (!sid_split_rid(&domsid, NULL)) {
    4432           0 :                         ads_msgfree(ads, res);
    4433           0 :                         return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4434             :                 }
    4435             : 
    4436           2 :                 if (!sid_compose(&tmp_primary_group_sid, &domsid, pgid)) {
    4437           0 :                         ads_msgfree(ads, res);
    4438           0 :                         return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4439             :                 }
    4440             :         }
    4441             : 
    4442           2 :         tmp_num_sids = ads_pull_sids(ads, mem_ctx, res, "tokenGroups", &tmp_sids);
    4443             : 
    4444           2 :         if (tmp_num_sids == 0 || !tmp_sids) {
    4445           0 :                 ads_msgfree(ads, res);
    4446           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4447             :         }
    4448             : 
    4449           2 :         if (num_sids) {
    4450           2 :                 *num_sids = tmp_num_sids;
    4451             :         }
    4452             : 
    4453           2 :         if (sids) {
    4454           2 :                 *sids = tmp_sids;
    4455             :         }
    4456             : 
    4457           2 :         if (user_sid) {
    4458           2 :                 *user_sid = tmp_user_sid;
    4459             :         }
    4460             : 
    4461           2 :         if (primary_group_sid) {
    4462           2 :                 *primary_group_sid = tmp_primary_group_sid;
    4463             :         }
    4464             : 
    4465           2 :         DEBUG(10,("ads_get_tokensids: returned %d sids\n", (int)tmp_num_sids + 2));
    4466             : 
    4467           2 :         ads_msgfree(ads, res);
    4468           2 :         return ADS_ERROR_LDAP(LDAP_SUCCESS);
    4469             : }
    4470             : 
    4471             : /**
    4472             :  * Find a sAMAccountName in LDAP
    4473             :  * @param ads connection to ads server
    4474             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    4475             :  * @param samaccountname to search
    4476             :  * @param uac_ret uint32_t pointer userAccountControl attribute value
    4477             :  * @param dn_ret pointer to dn
    4478             :  * @return status of token query
    4479             :  **/
    4480           0 : ADS_STATUS ads_find_samaccount(ADS_STRUCT *ads,
    4481             :                                TALLOC_CTX *mem_ctx,
    4482             :                                const char *samaccountname,
    4483             :                                uint32_t *uac_ret,
    4484             :                                const char **dn_ret)
    4485             : {
    4486           0 :         ADS_STATUS status;
    4487           0 :         const char *attrs[] = { "userAccountControl", NULL };
    4488           0 :         const char *filter;
    4489           0 :         LDAPMessage *res = NULL;
    4490           0 :         char *dn = NULL;
    4491           0 :         uint32_t uac = 0;
    4492             : 
    4493           0 :         filter = talloc_asprintf(mem_ctx, "(&(objectclass=user)(sAMAccountName=%s))",
    4494             :                 samaccountname);
    4495           0 :         if (filter == NULL) {
    4496           0 :                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    4497           0 :                 goto out;
    4498             :         }
    4499             : 
    4500           0 :         status = ads_do_search_all(ads, ads->config.bind_path,
    4501             :                                    LDAP_SCOPE_SUBTREE,
    4502             :                                    filter, attrs, &res);
    4503             : 
    4504           0 :         if (!ADS_ERR_OK(status)) {
    4505           0 :                 goto out;
    4506             :         }
    4507             : 
    4508           0 :         if (ads_count_replies(ads, res) != 1) {
    4509           0 :                 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    4510           0 :                 goto out;
    4511             :         }
    4512             : 
    4513           0 :         dn = ads_get_dn(ads, talloc_tos(), res);
    4514           0 :         if (dn == NULL) {
    4515           0 :                 status = ADS_ERROR(LDAP_NO_MEMORY);
    4516           0 :                 goto out;
    4517             :         }
    4518             : 
    4519           0 :         if (!ads_pull_uint32(ads, res, "userAccountControl", &uac)) {
    4520           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
    4521           0 :                 goto out;
    4522             :         }
    4523             : 
    4524           0 :         if (uac_ret) {
    4525           0 :                 *uac_ret = uac;
    4526             :         }
    4527             : 
    4528           0 :         if (dn_ret) {
    4529           0 :                 *dn_ret = talloc_strdup(mem_ctx, dn);
    4530           0 :                 if (!*dn_ret) {
    4531           0 :                         status = ADS_ERROR(LDAP_NO_MEMORY);
    4532           0 :                         goto out;
    4533             :                 }
    4534             :         }
    4535           0 :  out:
    4536           0 :         TALLOC_FREE(dn);
    4537           0 :         ads_msgfree(ads, res);
    4538             : 
    4539           0 :         return status;
    4540             : }
    4541             : 
    4542             : /**
    4543             :  * find our configuration path
    4544             :  * @param ads connection to ads server
    4545             :  * @param mem_ctx Pointer to talloc context
    4546             :  * @param config_path Pointer to the config path
    4547             :  * @return status of search
    4548             :  **/
    4549           0 : ADS_STATUS ads_config_path(ADS_STRUCT *ads,
    4550             :                            TALLOC_CTX *mem_ctx,
    4551             :                            char **config_path)
    4552             : {
    4553           0 :         ADS_STATUS status;
    4554           0 :         LDAPMessage *res = NULL;
    4555           0 :         const char *config_context = NULL;
    4556           0 :         const char *attrs[] = { "configurationNamingContext", NULL };
    4557             : 
    4558           0 :         status = ads_do_search(ads, "", LDAP_SCOPE_BASE,
    4559             :                                "(objectclass=*)", attrs, &res);
    4560           0 :         if (!ADS_ERR_OK(status)) {
    4561           0 :                 return status;
    4562             :         }
    4563             : 
    4564           0 :         config_context = ads_pull_string(ads, mem_ctx, res,
    4565             :                                          "configurationNamingContext");
    4566           0 :         ads_msgfree(ads, res);
    4567           0 :         if (!config_context) {
    4568           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    4569             :         }
    4570             : 
    4571           0 :         if (config_path) {
    4572           0 :                 *config_path = talloc_strdup(mem_ctx, config_context);
    4573           0 :                 if (!*config_path) {
    4574           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    4575             :                 }
    4576             :         }
    4577             : 
    4578           0 :         return ADS_ERROR(LDAP_SUCCESS);
    4579             : }
    4580             : 
    4581             : /**
    4582             :  * find the displayName of an extended right
    4583             :  * @param ads connection to ads server
    4584             :  * @param config_path The config path
    4585             :  * @param mem_ctx Pointer to talloc context
    4586             :  * @param GUID struct of the rightsGUID
    4587             :  * @return status of search
    4588             :  **/
    4589           0 : const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
    4590             :                                                 const char *config_path,
    4591             :                                                 TALLOC_CTX *mem_ctx,
    4592             :                                                 const struct GUID *rights_guid)
    4593             : {
    4594           0 :         ADS_STATUS rc;
    4595           0 :         LDAPMessage *res = NULL;
    4596           0 :         char *expr = NULL;
    4597           0 :         const char *attrs[] = { "displayName", NULL };
    4598           0 :         const char *result = NULL;
    4599           0 :         const char *path;
    4600             : 
    4601           0 :         if (!ads || !mem_ctx || !rights_guid) {
    4602           0 :                 goto done;
    4603             :         }
    4604             : 
    4605           0 :         expr = talloc_asprintf(mem_ctx, "(rightsGuid=%s)",
    4606             :                                GUID_string(mem_ctx, rights_guid));
    4607           0 :         if (!expr) {
    4608           0 :                 goto done;
    4609             :         }
    4610             : 
    4611           0 :         path = talloc_asprintf(mem_ctx, "cn=Extended-Rights,%s", config_path);
    4612           0 :         if (!path) {
    4613           0 :                 goto done;
    4614             :         }
    4615             : 
    4616           0 :         rc = ads_do_search_retry(ads, path, LDAP_SCOPE_SUBTREE,
    4617             :                                  expr, attrs, &res);
    4618           0 :         if (!ADS_ERR_OK(rc)) {
    4619           0 :                 goto done;
    4620             :         }
    4621             : 
    4622           0 :         if (ads_count_replies(ads, res) != 1) {
    4623           0 :                 goto done;
    4624             :         }
    4625             : 
    4626           0 :         result = ads_pull_string(ads, mem_ctx, res, "displayName");
    4627             : 
    4628           0 :  done:
    4629           0 :         ads_msgfree(ads, res);
    4630           0 :         return result;
    4631             : }
    4632             : 
    4633             : /**
    4634             :  * verify or build and verify an account ou
    4635             :  * @param mem_ctx Pointer to talloc context
    4636             :  * @param ads connection to ads server
    4637             :  * @param account_ou
    4638             :  * @return status of search
    4639             :  **/
    4640             : 
    4641          60 : ADS_STATUS ads_check_ou_dn(TALLOC_CTX *mem_ctx,
    4642             :                            ADS_STRUCT *ads,
    4643             :                            const char **account_ou)
    4644             : {
    4645           0 :         char **exploded_dn;
    4646           0 :         const char *name;
    4647           0 :         char *ou_string;
    4648             : 
    4649          60 :         if (account_ou == NULL) {
    4650           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    4651             :         }
    4652             : 
    4653          60 :         if (*account_ou != NULL) {
    4654           2 :                 exploded_dn = ldap_explode_dn(*account_ou, 0);
    4655           2 :                 if (exploded_dn) {
    4656           0 :                         ldap_value_free(exploded_dn);
    4657           0 :                         return ADS_SUCCESS;
    4658             :                 }
    4659             :         }
    4660             : 
    4661          60 :         ou_string = ads_ou_string(ads, *account_ou);
    4662          60 :         if (!ou_string) {
    4663           0 :                 return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
    4664             :         }
    4665             : 
    4666          60 :         name = talloc_asprintf(mem_ctx, "%s,%s", ou_string,
    4667             :                                ads->config.bind_path);
    4668          60 :         SAFE_FREE(ou_string);
    4669             : 
    4670          60 :         if (!name) {
    4671           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4672             :         }
    4673             : 
    4674          60 :         exploded_dn = ldap_explode_dn(name, 0);
    4675          60 :         if (!exploded_dn) {
    4676           0 :                 return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
    4677             :         }
    4678          60 :         ldap_value_free(exploded_dn);
    4679             : 
    4680          60 :         *account_ou = name;
    4681          60 :         return ADS_SUCCESS;
    4682             : }
    4683             : 
    4684             : #endif

Generated by: LCOV version 1.14