LCOV - code coverage report
Current view: top level - source3/libads - ldap.c (source / functions) Hit Total Coverage
Test: coverage report for master 2b515b7d Lines: 1029 2102 49.0 %
Date: 2024-02-28 12:06:22 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         682 : bool ads_closest_dc(ADS_STRUCT *ads)
     231             : {
     232         682 :         if (ads->config.flags & NBT_SERVER_CLOSEST) {
     233         682 :                 DEBUG(10,("ads_closest_dc: NBT_SERVER_CLOSEST flag set\n"));
     234         682 :                 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         573 : 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         573 :         TALLOC_CTX *frame = talloc_stackframe();
     260         573 :         bool ret = false;
     261           0 :         char addr[INET6_ADDRSTRLEN];
     262           0 :         ADS_STATUS status;
     263           0 :         char *dn;
     264             : 
     265         573 :         print_sockaddr(addr, sizeof(addr), ss);
     266             : 
     267             :         /* Check the CLDAP reply flags */
     268             : 
     269         573 :         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         573 :         ADS_TALLOC_CONST_FREE(ads->config.realm);
     279         573 :         ADS_TALLOC_CONST_FREE(ads->config.bind_path);
     280         573 :         ADS_TALLOC_CONST_FREE(ads->config.ldap_server_name);
     281         573 :         ADS_TALLOC_CONST_FREE(ads->config.server_site_name);
     282         573 :         ADS_TALLOC_CONST_FREE(ads->config.client_site_name);
     283         573 :         ADS_TALLOC_CONST_FREE(ads->server.workgroup);
     284             : 
     285         573 :         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        1146 :         ads->config.ldap_server_name = talloc_strdup(ads,
     292         573 :                                                      cldap_reply->pdc_dns_name);
     293         573 :         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        1146 :         ads->config.realm = talloc_asprintf_strupper_m(ads,
     300             :                                                        "%s",
     301         573 :                                                        cldap_reply->dns_domain);
     302         573 :         if (ads->config.realm == NULL) {
     303           0 :                 DBG_WARNING("Out of memory\n");
     304           0 :                 ret = false;
     305           0 :                 goto out;
     306             :         }
     307             : 
     308         573 :         status = ads_build_dn(ads->config.realm, ads, &dn);
     309         573 :         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         573 :         ads->config.bind_path = dn;
     316             : 
     317         573 :         if (*cldap_reply->server_site) {
     318         573 :                 ads->config.server_site_name =
     319         573 :                         talloc_strdup(ads, cldap_reply->server_site);
     320         573 :                 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         573 :         if (*cldap_reply->client_site) {
     328         573 :                 ads->config.client_site_name =
     329         573 :                         talloc_strdup(ads, cldap_reply->client_site);
     330         573 :                 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         573 :         ads->server.workgroup = talloc_strdup(ads, cldap_reply->domain_name);
     338         573 :         if (ads->server.workgroup == NULL) {
     339           0 :                 DBG_WARNING("Out of memory\n");
     340           0 :                 ret = false;
     341           0 :                 goto out;
     342             :         }
     343             : 
     344         573 :         ads->ldap.port = gc ? LDAP_GC_PORT : LDAP_PORT;
     345         573 :         ads->ldap.ss = *ss;
     346             : 
     347             :         /* Store our site name. */
     348         573 :         sitename_store(cldap_reply->domain_name, cldap_reply->client_site);
     349         573 :         sitename_store(cldap_reply->dns_domain, cldap_reply->client_site);
     350             : 
     351             :         /* Leave this until last so that the flags are not clobbered */
     352         573 :         ads->config.flags = cldap_reply->server_type;
     353             : 
     354         573 :         ret = true;
     355             : 
     356         573 :  out:
     357             : 
     358         573 :         TALLOC_FREE(frame);
     359         573 :         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         327 : static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
     367             :                             struct sockaddr_storage *ss)
     368             : {
     369         327 :         struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply = {};
     370         327 :         TALLOC_CTX *frame = talloc_stackframe();
     371           0 :         bool ok;
     372         327 :         char addr[INET6_ADDRSTRLEN] = { 0, };
     373             : 
     374         327 :         if (ss == NULL) {
     375           0 :                 TALLOC_FREE(frame);
     376           0 :                 return false;
     377             :         }
     378             : 
     379         327 :         print_sockaddr(addr, sizeof(addr), ss);
     380             : 
     381         327 :         DBG_INFO("ads_try_connect: sending CLDAP request to %s (realm: %s)\n",
     382             :                  addr, ads->server.realm);
     383             : 
     384         327 :         ok = ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply);
     385         327 :         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         327 :         ok = ads_fill_cldap_reply(ads, gc, ss, &cldap_reply);
     393         327 :         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         327 :         TALLOC_FREE(frame);
     401         327 :         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         246 : static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,
     411             :                         const char *domain,
     412             :                         struct samba_sockaddr *sa_list,
     413             :                         size_t count)
     414             : {
     415         246 :         TALLOC_CTX *frame = talloc_stackframe();
     416         246 :         struct timeval endtime = timeval_current_ofs(MAX(3,lp_ldap_timeout()/2), 0);
     417         246 :         uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX;
     418         246 :         struct tsocket_address **ts_list = NULL;
     419         246 :         const struct tsocket_address * const *ts_list_const = NULL;
     420         246 :         struct samba_sockaddr **req_sa_list = NULL;
     421         246 :         struct netlogon_samlogon_response **responses = NULL;
     422         246 :         size_t num_requests = 0;
     423           0 :         NTSTATUS status;
     424           0 :         size_t i;
     425         246 :         bool ok = false;
     426           0 :         bool retry;
     427             : 
     428         246 :         ts_list = talloc_zero_array(frame,
     429             :                                     struct tsocket_address *,
     430             :                                     count);
     431         246 :         if (ts_list == NULL) {
     432           0 :                 TALLOC_FREE(frame);
     433           0 :                 return NT_STATUS_NO_MEMORY;
     434             :         }
     435             : 
     436         246 :         req_sa_list = talloc_zero_array(frame,
     437             :                                         struct samba_sockaddr *,
     438             :                                         count);
     439         246 :         if (req_sa_list == NULL) {
     440           0 :                 TALLOC_FREE(frame);
     441           0 :                 return NT_STATUS_NO_MEMORY;
     442             :         }
     443             : 
     444         246 : again:
     445             :         /*
     446             :          * The retry loop is bound by the timeout
     447             :          */
     448         246 :         retry = false;
     449         246 :         num_requests = 0;
     450             : 
     451         682 :         for (i = 0; i < count; i++) {
     452           0 :                 char server[INET6_ADDRSTRLEN];
     453           0 :                 int ret;
     454             : 
     455         436 :                 if (is_zero_addr(&sa_list[i].u.ss)) {
     456           0 :                         continue;
     457             :                 }
     458             : 
     459         436 :                 print_sockaddr(server, sizeof(server), &sa_list[i].u.ss);
     460             : 
     461         436 :                 status = check_negative_conn_cache(domain, server);
     462         436 :                 if (!NT_STATUS_IS_OK(status)) {
     463           0 :                         continue;
     464             :                 }
     465             : 
     466         436 :                 ret = tsocket_address_inet_from_strings(ts_list, "ip",
     467             :                                                         server, LDAP_PORT,
     468             :                                                         &ts_list[num_requests]);
     469         436 :                 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         436 :                 req_sa_list[num_requests] = &sa_list[i];
     478         436 :                 num_requests += 1;
     479             :         }
     480             : 
     481         246 :         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         246 :         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         246 :         ts_list_const = (const struct tsocket_address * const *)ts_list;
     496             : 
     497         246 :         status = cldap_multi_netlogon(frame,
     498             :                                       ts_list_const, num_requests,
     499             :                                       ads->server.realm, NULL,
     500             :                                       nt_version,
     501             :                                       1, endtime, &responses);
     502         246 :         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         246 :         for (i = 0; i < num_requests; i++) {
     513         246 :                 struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply = NULL;
     514           0 :                 char server[INET6_ADDRSTRLEN];
     515             : 
     516         246 :                 if (responses[i] == NULL) {
     517           0 :                         continue;
     518             :                 }
     519             : 
     520         246 :                 print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
     521             : 
     522         246 :                 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         246 :                 cldap_reply = &responses[i]->data.nt5_ex;
     530             : 
     531             :                 /* Returns ok only if it matches the correct server type */
     532         246 :                 ok = ads_fill_cldap_reply(ads,
     533             :                                           false,
     534         246 :                                           &req_sa_list[i]->u.ss,
     535             :                                           cldap_reply);
     536         246 :                 if (ok) {
     537         246 :                         DBG_DEBUG("realm[%s]: selected %s => %s\n",
     538             :                                   ads->server.realm,
     539             :                                   server, cldap_reply->pdc_dns_name);
     540         246 :                         if (CHECK_DEBUGLVL(DBGLVL_DEBUG)) {
     541           1 :                                 NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
     542             :                                                 cldap_reply);
     543             :                         }
     544         246 :                         TALLOC_FREE(frame);
     545         246 :                         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         238 : static NTSTATUS resolve_and_ping_dns(ADS_STRUCT *ads, const char *sitename,
     645             :                                      const char *realm)
     646             : {
     647         238 :         size_t count = 0;
     648         238 :         struct samba_sockaddr *sa_list = NULL;
     649           0 :         NTSTATUS status;
     650             : 
     651         238 :         DEBUG(6, ("resolve_and_ping_dns: (cldap) looking for realm '%s'\n",
     652             :                   realm));
     653             : 
     654         238 :         status = get_sorted_dc_list(talloc_tos(),
     655             :                                 realm,
     656             :                                 sitename,
     657             :                                 &sa_list,
     658             :                                 &count,
     659             :                                 true);
     660         238 :         if (!NT_STATUS_IS_OK(status)) {
     661           0 :                 TALLOC_FREE(sa_list);
     662           0 :                 return status;
     663             :         }
     664             : 
     665         238 :         status = cldap_ping_list(ads, realm, sa_list, count);
     666             : 
     667         238 :         TALLOC_FREE(sa_list);
     668             : 
     669         238 :         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         396 : static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
     679             : {
     680         396 :         const char *c_domain = "";
     681           0 :         const char *c_realm;
     682         396 :         bool use_own_domain = False;
     683         396 :         char *sitename = NULL;
     684         396 :         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
     685         396 :         bool ok = false;
     686             : 
     687             :         /* if the realm and workgroup are both empty, assume they are ours */
     688             : 
     689             :         /* realm */
     690         396 :         c_realm = ads->server.realm;
     691             : 
     692         396 :         if (c_realm == NULL)
     693           8 :                 c_realm = "";
     694             : 
     695         396 :         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         396 :         if (!lp_disable_netbios()) {
     704         396 :                 if (use_own_domain) {
     705           0 :                         c_domain = lp_workgroup();
     706             :                 } else {
     707         396 :                         c_domain = ads->server.workgroup;
     708         396 :                         if (!*c_realm && (!c_domain || !*c_domain)) {
     709           0 :                                 c_domain = lp_workgroup();
     710             :                         }
     711             :                 }
     712             : 
     713         396 :                 if (!c_domain) {
     714           0 :                         c_domain = "";
     715             :                 }
     716             :         }
     717             : 
     718         396 :         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         396 :         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         246 :         if (*c_realm) {
     756         238 :                 sitename = sitename_fetch(talloc_tos(), c_realm);
     757         238 :                 status = resolve_and_ping_dns(ads, sitename, c_realm);
     758             : 
     759         238 :                 if (NT_STATUS_IS_OK(status)) {
     760         238 :                         TALLOC_FREE(sitename);
     761         238 :                         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         575 : ADS_STATUS ads_connect(ADS_STRUCT *ads)
     814             : {
     815         575 :         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         575 :         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         575 :         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         575 :         ads_zero_ldap(ads);
     847         575 :         ZERO_STRUCT(ads->ldap_wrap_data);
     848         575 :         ads->ldap.last_attempt       = time_mono(NULL);
     849         575 :         ads->ldap_wrap_data.wrap_type        = ADS_SASLWRAP_TYPE_PLAIN;
     850             : 
     851             :         /* try with a user specified server */
     852             : 
     853         575 :         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         575 :         if (ads->server.ldap_server) {
     861         164 :                 bool ok = false;
     862           0 :                 struct sockaddr_storage ss;
     863             : 
     864         164 :                 DBG_DEBUG("Resolving name of LDAP server '%s'.\n",
     865             :                           ads->server.ldap_server);
     866         164 :                 ok = resolve_name(ads->server.ldap_server, &ss, 0x20, true);
     867         164 :                 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         162 :                 if (is_zero_addr(&ss)) {
     875           0 :                         status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
     876           0 :                         goto out;
     877             :                 }
     878             : 
     879         162 :                 ok = ads_try_connect(ads, ads->server.gc, &ss);
     880         162 :                 if (ok) {
     881         162 :                         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         411 :         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         396 :         ntstatus = ads_find_dc(ads);
     916         396 :         if (NT_STATUS_IS_OK(ntstatus)) {
     917         396 :                 goto got_connection;
     918             :         }
     919             : 
     920           0 :         status = ADS_ERROR_NT(ntstatus);
     921           0 :         goto out;
     922             : 
     923         573 : got_connection:
     924             : 
     925         573 :         print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
     926         573 :         DEBUG(3,("Successfully contacted LDAP server %s\n", addr));
     927             : 
     928         573 :         if (!ads->auth.user_name) {
     929             :                 /* Must use the userPrincipalName value here or sAMAccountName
     930             :                    and not servicePrincipalName; found by Guenther Deschner */
     931         216 :                 ads->auth.user_name = talloc_asprintf(ads,
     932             :                                                       "%s$",
     933             :                                                       lp_netbios_name());
     934         216 :                 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         573 :         if (ads->auth.realm == NULL) {
     942         302 :                 ads->auth.realm = talloc_strdup(ads, ads->config.realm);
     943         302 :                 if (ads->auth.realm == NULL) {
     944           0 :                         status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
     945           0 :                         goto out;
     946             :                 }
     947             :         }
     948             : 
     949         573 :         if (!ads->auth.kdc_server) {
     950         558 :                 print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
     951         558 :                 ads->auth.kdc_server = talloc_strdup(ads, addr);
     952         558 :                 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         573 :         if (ads->auth.flags & ADS_AUTH_NO_BIND) {
     961         246 :                 status = ADS_SUCCESS;
     962         246 :                 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         575 :  out:
    1012         575 :         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         575 :         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        1787 : void ads_zero_ldap(ADS_STRUCT *ads)
    1045             : {
    1046        1787 :         ZERO_STRUCT(ads->ldap);
    1047             :         /*
    1048             :          * Initialize the sockaddr_storage so we can use
    1049             :          * sockaddr test functions against it.
    1050             :          */
    1051        1787 :         zero_sockaddr(&ads->ldap.ss);
    1052        1787 : }
    1053             : 
    1054             : /**
    1055             :  * Disconnect the LDAP server
    1056             :  * @param ads Pointer to an existing ADS_STRUCT
    1057             :  **/
    1058         606 : void ads_disconnect(ADS_STRUCT *ads)
    1059             : {
    1060         606 :         if (ads->ldap.ld) {
    1061         327 :                 ldap_unbind(ads->ldap.ld);
    1062         327 :                 ads->ldap.ld = NULL;
    1063             :         }
    1064         606 :         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         606 :         if (ads->ldap_wrap_data.mem_ctx) {
    1069         327 :                 talloc_free(ads->ldap_wrap_data.mem_ctx);
    1070             :         }
    1071         606 :         ads_zero_ldap(ads);
    1072         606 :         ZERO_STRUCT(ads->ldap_wrap_data);
    1073         606 : }
    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             : 
    1691             :                 /* Additional attributes Samba checks */
    1692             :                 "msDS-AdditionalDnsHostName",
    1693             :                 "msDS-SupportedEncryptionTypes",
    1694             :                 "nTSecurityDescriptor",
    1695             :                 "objectSid",
    1696             : 
    1697             :                 NULL
    1698             :         };
    1699         674 :         TALLOC_CTX *frame = talloc_stackframe();
    1700             : 
    1701         674 :         *res = NULL;
    1702             : 
    1703             :         /* the easiest way to find a machine account anywhere in the tree
    1704             :            is to look for hostname$ */
    1705         674 :         expr = talloc_asprintf(frame, "(samAccountName=%s$)", machine);
    1706         674 :         if (expr == NULL) {
    1707           0 :                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1708           0 :                 goto done;
    1709             :         }
    1710             : 
    1711         674 :         status = ads_search(ads, res, expr, attrs);
    1712         674 :         if (ADS_ERR_OK(status)) {
    1713         674 :                 if (ads_count_replies(ads, *res) != 1) {
    1714          88 :                         status = ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
    1715             :                 }
    1716             :         }
    1717             : 
    1718         586 : done:
    1719         674 :         TALLOC_FREE(frame);
    1720         674 :         return status;
    1721             : }
    1722             : 
    1723             : /**
    1724             :  * Initialize a list of mods to be used in a modify request
    1725             :  * @param ctx An initialized TALLOC_CTX
    1726             :  * @return allocated ADS_MODLIST
    1727             :  **/
    1728         194 : ADS_MODLIST ads_init_mods(TALLOC_CTX *ctx)
    1729             : {
    1730             : #define ADS_MODLIST_ALLOC_SIZE 10
    1731           0 :         LDAPMod **mods;
    1732             : 
    1733         194 :         if ((mods = talloc_zero_array(ctx, LDAPMod *, ADS_MODLIST_ALLOC_SIZE + 1)))
    1734             :                 /* -1 is safety to make sure we don't go over the end.
    1735             :                    need to reset it to NULL before doing ldap modify */
    1736         194 :                 mods[ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
    1737             : 
    1738         194 :         return (ADS_MODLIST)mods;
    1739             : }
    1740             : 
    1741             : 
    1742             : /*
    1743             :   add an attribute to the list, with values list already constructed
    1744             : */
    1745         560 : static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1746             :                                   int mod_op, const char *name,
    1747             :                                   const void *_invals)
    1748             : {
    1749           0 :         int curmod;
    1750         560 :         LDAPMod **modlist = (LDAPMod **) *mods;
    1751         560 :         struct berval **ber_values = NULL;
    1752         560 :         char **char_values = NULL;
    1753             : 
    1754         560 :         if (!_invals) {
    1755           0 :                 mod_op = LDAP_MOD_DELETE;
    1756             :         } else {
    1757         560 :                 if (mod_op & LDAP_MOD_BVALUES) {
    1758           0 :                         const struct berval **b;
    1759          60 :                         b = discard_const_p(const struct berval *, _invals);
    1760          60 :                         ber_values = ads_dup_values(ctx, b);
    1761             :                 } else {
    1762           0 :                         const char **c;
    1763         500 :                         c = discard_const_p(const char *, _invals);
    1764         500 :                         char_values = ads_push_strvals(ctx, c);
    1765             :                 }
    1766             :         }
    1767             : 
    1768             :         /* find the first empty slot */
    1769        1548 :         for (curmod=0; modlist[curmod] && modlist[curmod] != (LDAPMod *) -1;
    1770         988 :              curmod++);
    1771         560 :         if (modlist[curmod] == (LDAPMod *) -1) {
    1772           0 :                 if (!(modlist = talloc_realloc(ctx, modlist, LDAPMod *,
    1773             :                                 curmod+ADS_MODLIST_ALLOC_SIZE+1)))
    1774           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    1775           0 :                 memset(&modlist[curmod], 0,
    1776             :                        ADS_MODLIST_ALLOC_SIZE*sizeof(LDAPMod *));
    1777           0 :                 modlist[curmod+ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
    1778           0 :                 *mods = (ADS_MODLIST)modlist;
    1779             :         }
    1780             : 
    1781         560 :         if (!(modlist[curmod] = talloc_zero(ctx, LDAPMod)))
    1782           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    1783         560 :         modlist[curmod]->mod_type = talloc_strdup(ctx, name);
    1784         560 :         if (mod_op & LDAP_MOD_BVALUES) {
    1785          60 :                 modlist[curmod]->mod_bvalues = ber_values;
    1786         500 :         } else if (mod_op & LDAP_MOD_DELETE) {
    1787           0 :                 modlist[curmod]->mod_values = NULL;
    1788             :         } else {
    1789         500 :                 modlist[curmod]->mod_values = char_values;
    1790             :         }
    1791             : 
    1792         560 :         modlist[curmod]->mod_op = mod_op;
    1793         560 :         return ADS_ERROR(LDAP_SUCCESS);
    1794             : }
    1795             : 
    1796             : /**
    1797             :  * Add a single string value to a mod list
    1798             :  * @param ctx An initialized TALLOC_CTX
    1799             :  * @param mods An initialized ADS_MODLIST
    1800             :  * @param name The attribute name to add
    1801             :  * @param val The value to add - NULL means DELETE
    1802             :  * @return ADS STATUS indicating success of add
    1803             :  **/
    1804         372 : ADS_STATUS ads_mod_str(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1805             :                        const char *name, const char *val)
    1806             : {
    1807           0 :         const char *values[2];
    1808             : 
    1809         372 :         values[0] = val;
    1810         372 :         values[1] = NULL;
    1811             : 
    1812         372 :         if (!val)
    1813           0 :                 return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
    1814         372 :         return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE, name, values);
    1815             : }
    1816             : 
    1817             : /**
    1818             :  * Add an array of string values to a mod list
    1819             :  * @param ctx An initialized TALLOC_CTX
    1820             :  * @param mods An initialized ADS_MODLIST
    1821             :  * @param name The attribute name to add
    1822             :  * @param vals The array of string values to add - NULL means DELETE
    1823             :  * @return ADS STATUS indicating success of add
    1824             :  **/
    1825         124 : ADS_STATUS ads_mod_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1826             :                            const char *name, const char **vals)
    1827             : {
    1828         124 :         if (!vals)
    1829           0 :                 return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
    1830         124 :         return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE,
    1831             :                                name, (const void **) vals);
    1832             : }
    1833             : 
    1834             : /**
    1835             :  * Add a single ber-encoded value to a mod list
    1836             :  * @param ctx An initialized TALLOC_CTX
    1837             :  * @param mods An initialized ADS_MODLIST
    1838             :  * @param name The attribute name to add
    1839             :  * @param val The value to add - NULL means DELETE
    1840             :  * @return ADS STATUS indicating success of add
    1841             :  **/
    1842          60 : static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    1843             :                               const char *name, const struct berval *val)
    1844             : {
    1845           0 :         const struct berval *values[2];
    1846             : 
    1847          60 :         values[0] = val;
    1848          60 :         values[1] = NULL;
    1849          60 :         if (!val)
    1850           0 :                 return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
    1851          60 :         return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE|LDAP_MOD_BVALUES,
    1852             :                                name, (const void **) values);
    1853             : }
    1854             : 
    1855         198 : static void ads_print_error(int ret, LDAP *ld)
    1856             : {
    1857         198 :         if (ret != 0) {
    1858           0 :                 char *ld_error = NULL;
    1859           0 :                 ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &ld_error);
    1860           0 :                 DBG_ERR("AD LDAP ERROR: %d (%s): %s\n",
    1861             :                         ret,
    1862             :                         ldap_err2string(ret),
    1863             :                         ld_error);
    1864           0 :                 SAFE_FREE(ld_error);
    1865             :         }
    1866         198 : }
    1867             : 
    1868             : /**
    1869             :  * Perform an ldap modify
    1870             :  * @param ads connection to ads server
    1871             :  * @param mod_dn DistinguishedName to modify
    1872             :  * @param mods list of modifications to perform
    1873             :  * @return status of modify
    1874             :  **/
    1875         134 : ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
    1876             : {
    1877           0 :         int ret,i;
    1878         134 :         char *utf8_dn = NULL;
    1879           0 :         size_t converted_size;
    1880             :         /*
    1881             :            this control is needed to modify that contains a currently
    1882             :            non-existent attribute (but allowable for the object) to run
    1883             :         */
    1884         134 :         LDAPControl PermitModify = {
    1885             :                 discard_const_p(char, ADS_PERMIT_MODIFY_OID),
    1886             :                 {0, NULL},
    1887             :                 (char) 1};
    1888           0 :         LDAPControl *controls[2];
    1889             : 
    1890         134 :         DBG_INFO("AD LDAP: Modifying %s\n", mod_dn);
    1891             : 
    1892         134 :         controls[0] = &PermitModify;
    1893         134 :         controls[1] = NULL;
    1894             : 
    1895         134 :         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, mod_dn, &converted_size)) {
    1896           0 :                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1897             :         }
    1898             : 
    1899             :         /* find the end of the list, marked by NULL or -1 */
    1900         330 :         for(i=0;(mods[i]!=0)&&(mods[i]!=(LDAPMod *) -1);i++);
    1901             :         /* make sure the end of the list is NULL */
    1902         134 :         mods[i] = NULL;
    1903         134 :         ret = ldap_modify_ext_s(ads->ldap.ld, utf8_dn,
    1904             :                                 (LDAPMod **) mods, controls, NULL);
    1905         134 :         ads_print_error(ret, ads->ldap.ld);
    1906         134 :         TALLOC_FREE(utf8_dn);
    1907         134 :         return ADS_ERROR(ret);
    1908             : }
    1909             : 
    1910             : /**
    1911             :  * Perform an ldap add
    1912             :  * @param ads connection to ads server
    1913             :  * @param new_dn DistinguishedName to add
    1914             :  * @param mods list of attributes and values for DN
    1915             :  * @return status of add
    1916             :  **/
    1917          60 : ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
    1918             : {
    1919           0 :         int ret, i;
    1920          60 :         char *utf8_dn = NULL;
    1921           0 :         size_t converted_size;
    1922             : 
    1923          60 :         DBG_INFO("AD LDAP: Adding %s\n", new_dn);
    1924             : 
    1925          60 :         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, new_dn, &converted_size)) {
    1926           0 :                 DEBUG(1, ("ads_gen_add: push_utf8_talloc failed!\n"));
    1927           0 :                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1928             :         }
    1929             : 
    1930             :         /* find the end of the list, marked by NULL or -1 */
    1931         424 :         for(i=0;(mods[i]!=0)&&(mods[i]!=(LDAPMod *) -1);i++);
    1932             :         /* make sure the end of the list is NULL */
    1933          60 :         mods[i] = NULL;
    1934             : 
    1935          60 :         ret = ldap_add_ext_s(ads->ldap.ld, utf8_dn, (LDAPMod**)mods, NULL, NULL);
    1936          60 :         ads_print_error(ret, ads->ldap.ld);
    1937          60 :         TALLOC_FREE(utf8_dn);
    1938          60 :         return ADS_ERROR(ret);
    1939             : }
    1940             : 
    1941             : /**
    1942             :  * Delete a DistinguishedName
    1943             :  * @param ads connection to ads server
    1944             :  * @param new_dn DistinguishedName to delete
    1945             :  * @return status of delete
    1946             :  **/
    1947           4 : ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
    1948             : {
    1949           0 :         int ret;
    1950           4 :         char *utf8_dn = NULL;
    1951           0 :         size_t converted_size;
    1952           4 :         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, del_dn, &converted_size)) {
    1953           0 :                 DEBUG(1, ("ads_del_dn: push_utf8_talloc failed!\n"));
    1954           0 :                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    1955             :         }
    1956             : 
    1957           4 :         DBG_INFO("AD LDAP: Deleting %s\n", del_dn);
    1958             : 
    1959           4 :         ret = ldap_delete_s(ads->ldap.ld, utf8_dn);
    1960           4 :         ads_print_error(ret, ads->ldap.ld);
    1961           4 :         TALLOC_FREE(utf8_dn);
    1962           4 :         return ADS_ERROR(ret);
    1963             : }
    1964             : 
    1965             : /**
    1966             :  * Build an org unit string
    1967             :  *  if org unit is Computers or blank then assume a container, otherwise
    1968             :  *  assume a / separated list of organisational units.
    1969             :  * jmcd: '\' is now used for escapes so certain chars can be in the ou (e.g. #)
    1970             :  * @param ads connection to ads server
    1971             :  * @param org_unit Organizational unit
    1972             :  * @return org unit string - caller must free
    1973             :  **/
    1974          60 : char *ads_ou_string(ADS_STRUCT *ads, const char *org_unit)
    1975             : {
    1976           0 :         ADS_STATUS status;
    1977          60 :         char *ret = NULL;
    1978          60 :         char *dn = NULL;
    1979             : 
    1980          60 :         if (!org_unit || !*org_unit) {
    1981             : 
    1982          58 :                 ret = ads_default_ou_string(ads, DS_GUID_COMPUTERS_CONTAINER);
    1983             : 
    1984             :                 /* samba4 might not yet respond to a wellknownobject-query */
    1985          58 :                 return ret ? ret : SMB_STRDUP("cn=Computers");
    1986             :         }
    1987             : 
    1988           2 :         if (strequal(org_unit, "Computers")) {
    1989           0 :                 return SMB_STRDUP("cn=Computers");
    1990             :         }
    1991             : 
    1992             :         /* jmcd: removed "\\" from the separation chars, because it is
    1993             :            needed as an escape for chars like '#' which are valid in an
    1994             :            OU name */
    1995           2 :         status = ads_build_path(org_unit, "/", "ou=", 1, &dn);
    1996           2 :         if (!ADS_ERR_OK(status)) {
    1997           0 :                 return NULL;
    1998             :         }
    1999             : 
    2000           2 :         return dn;
    2001             : }
    2002             : 
    2003             : /**
    2004             :  * Get a org unit string for a well-known GUID
    2005             :  * @param ads connection to ads server
    2006             :  * @param wknguid Well known GUID
    2007             :  * @return org unit string - caller must free
    2008             :  **/
    2009          62 : char *ads_default_ou_string(ADS_STRUCT *ads, const char *wknguid)
    2010             : {
    2011           0 :         ADS_STATUS status;
    2012          62 :         LDAPMessage *res = NULL;
    2013          62 :         char *base, *wkn_dn = NULL, *ret = NULL, **wkn_dn_exp = NULL,
    2014          62 :                 **bind_dn_exp = NULL;
    2015          62 :         const char *attrs[] = {"distinguishedName", NULL};
    2016           0 :         int new_ln, wkn_ln, bind_ln, i;
    2017             : 
    2018          62 :         if (wknguid == NULL) {
    2019           0 :                 return NULL;
    2020             :         }
    2021             : 
    2022          62 :         if (asprintf(&base, "<WKGUID=%s,%s>", wknguid, ads->config.bind_path ) == -1) {
    2023           0 :                 DEBUG(1, ("asprintf failed!\n"));
    2024           0 :                 return NULL;
    2025             :         }
    2026             : 
    2027          62 :         status = ads_search_dn(ads, &res, base, attrs);
    2028          62 :         if (!ADS_ERR_OK(status)) {
    2029           0 :                 DEBUG(1,("Failed while searching for: %s\n", base));
    2030           0 :                 goto out;
    2031             :         }
    2032             : 
    2033          62 :         if (ads_count_replies(ads, res) != 1) {
    2034           0 :                 goto out;
    2035             :         }
    2036             : 
    2037             :         /* substitute the bind-path from the well-known-guid-search result */
    2038          62 :         wkn_dn = ads_get_dn(ads, talloc_tos(), res);
    2039          62 :         if (!wkn_dn) {
    2040           0 :                 goto out;
    2041             :         }
    2042             : 
    2043          62 :         wkn_dn_exp = ldap_explode_dn(wkn_dn, 0);
    2044          62 :         if (!wkn_dn_exp) {
    2045           0 :                 goto out;
    2046             :         }
    2047             : 
    2048          62 :         bind_dn_exp = ldap_explode_dn(ads->config.bind_path, 0);
    2049          62 :         if (!bind_dn_exp) {
    2050           0 :                 goto out;
    2051             :         }
    2052             : 
    2053         362 :         for (wkn_ln=0; wkn_dn_exp[wkn_ln]; wkn_ln++)
    2054             :                 ;
    2055         300 :         for (bind_ln=0; bind_dn_exp[bind_ln]; bind_ln++)
    2056             :                 ;
    2057             : 
    2058          62 :         new_ln = wkn_ln - bind_ln;
    2059             : 
    2060          62 :         ret = SMB_STRDUP(wkn_dn_exp[0]);
    2061          62 :         if (!ret) {
    2062           0 :                 goto out;
    2063             :         }
    2064             : 
    2065          62 :         for (i=1; i < new_ln; i++) {
    2066           0 :                 char *s = NULL;
    2067             : 
    2068           0 :                 if (asprintf(&s, "%s,%s", ret, wkn_dn_exp[i]) == -1) {
    2069           0 :                         SAFE_FREE(ret);
    2070           0 :                         goto out;
    2071             :                 }
    2072             : 
    2073           0 :                 SAFE_FREE(ret);
    2074           0 :                 ret = SMB_STRDUP(s);
    2075           0 :                 free(s);
    2076           0 :                 if (!ret) {
    2077           0 :                         goto out;
    2078             :                 }
    2079             :         }
    2080             : 
    2081          62 :  out:
    2082          62 :         SAFE_FREE(base);
    2083          62 :         ads_msgfree(ads, res);
    2084          62 :         TALLOC_FREE(wkn_dn);
    2085          62 :         if (wkn_dn_exp) {
    2086          62 :                 ldap_value_free(wkn_dn_exp);
    2087             :         }
    2088          62 :         if (bind_dn_exp) {
    2089          62 :                 ldap_value_free(bind_dn_exp);
    2090             :         }
    2091             : 
    2092          62 :         return ret;
    2093             : }
    2094             : 
    2095             : /**
    2096             :  * Adds (appends) an item to an attribute array, rather then
    2097             :  * replacing the whole list
    2098             :  * @param ctx An initialized TALLOC_CTX
    2099             :  * @param mods An initialized ADS_MODLIST
    2100             :  * @param name name of the ldap attribute to append to
    2101             :  * @param vals an array of values to add
    2102             :  * @return status of addition
    2103             :  **/
    2104             : 
    2105           4 : ADS_STATUS ads_add_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
    2106             :                                 const char *name, const char **vals)
    2107             : {
    2108           4 :         return ads_modlist_add(ctx, mods, LDAP_MOD_ADD, name,
    2109             :                                (const void *) vals);
    2110             : }
    2111             : 
    2112             : /**
    2113             :  * Determines the an account's current KVNO via an LDAP lookup
    2114             :  * @param ads An initialized ADS_STRUCT
    2115             :  * @param account_name the NT samaccountname.
    2116             :  * @return the kvno for the account, or -1 in case of a failure.
    2117             :  **/
    2118             : 
    2119          74 : uint32_t ads_get_kvno(ADS_STRUCT *ads, const char *account_name)
    2120             : {
    2121          74 :         LDAPMessage *res = NULL;
    2122          74 :         uint32_t kvno = (uint32_t)-1;      /* -1 indicates a failure */
    2123           0 :         char *filter;
    2124          74 :         const char *attrs[] = {"msDS-KeyVersionNumber", NULL};
    2125          74 :         char *dn_string = NULL;
    2126           0 :         ADS_STATUS ret;
    2127             : 
    2128          74 :         DEBUG(5,("ads_get_kvno: Searching for account %s\n", account_name));
    2129          74 :         if (asprintf(&filter, "(samAccountName=%s)", account_name) == -1) {
    2130           0 :                 return kvno;
    2131             :         }
    2132          74 :         ret = ads_search(ads, &res, filter, attrs);
    2133          74 :         SAFE_FREE(filter);
    2134          74 :         if (!ADS_ERR_OK(ret) || (ads_count_replies(ads, res) != 1)) {
    2135           0 :                 DEBUG(1,("ads_get_kvno: Account for %s not found.\n", account_name));
    2136           0 :                 ads_msgfree(ads, res);
    2137           0 :                 return kvno;
    2138             :         }
    2139             : 
    2140          74 :         dn_string = ads_get_dn(ads, talloc_tos(), res);
    2141          74 :         if (!dn_string) {
    2142           0 :                 DEBUG(0,("ads_get_kvno: out of memory.\n"));
    2143           0 :                 ads_msgfree(ads, res);
    2144           0 :                 return kvno;
    2145             :         }
    2146          74 :         DEBUG(5,("ads_get_kvno: Using: %s\n", dn_string));
    2147          74 :         TALLOC_FREE(dn_string);
    2148             : 
    2149             :         /* ---------------------------------------------------------
    2150             :          * 0 is returned as a default KVNO from this point on...
    2151             :          * This is done because Windows 2000 does not support key
    2152             :          * version numbers.  Chances are that a failure in the next
    2153             :          * step is simply due to Windows 2000 being used for a
    2154             :          * domain controller. */
    2155          74 :         kvno = 0;
    2156             : 
    2157          74 :         if (!ads_pull_uint32(ads, res, "msDS-KeyVersionNumber", &kvno)) {
    2158           0 :                 DEBUG(3,("ads_get_kvno: Error Determining KVNO!\n"));
    2159           0 :                 DEBUG(3,("ads_get_kvno: Windows 2000 does not support KVNO's, so this may be normal.\n"));
    2160           0 :                 ads_msgfree(ads, res);
    2161           0 :                 return kvno;
    2162             :         }
    2163             : 
    2164             :         /* Success */
    2165          74 :         DEBUG(5,("ads_get_kvno: Looked Up KVNO of: %d\n", kvno));
    2166          74 :         ads_msgfree(ads, res);
    2167          74 :         return kvno;
    2168             : }
    2169             : 
    2170             : /**
    2171             :  * Determines the computer account's current KVNO via an LDAP lookup
    2172             :  * @param ads An initialized ADS_STRUCT
    2173             :  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
    2174             :  * @return the kvno for the computer account, or -1 in case of a failure.
    2175             :  **/
    2176             : 
    2177          74 : uint32_t ads_get_machine_kvno(ADS_STRUCT *ads, const char *machine_name)
    2178             : {
    2179          74 :         char *computer_account = NULL;
    2180          74 :         uint32_t kvno = -1;
    2181             : 
    2182          74 :         if (asprintf(&computer_account, "%s$", machine_name) < 0) {
    2183           0 :                 return kvno;
    2184             :         }
    2185             : 
    2186          74 :         kvno = ads_get_kvno(ads, computer_account);
    2187          74 :         free(computer_account);
    2188             : 
    2189          74 :         return kvno;
    2190             : }
    2191             : 
    2192             : /**
    2193             :  * This clears out all registered spn's for a given hostname
    2194             :  * @param ads An initialized ADS_STRUCT
    2195             :  * @param machine_name the NetBIOS name of the computer.
    2196             :  * @return 0 upon success, non-zero otherwise.
    2197             :  **/
    2198             : 
    2199           0 : ADS_STATUS ads_clear_service_principal_names(ADS_STRUCT *ads, const char *machine_name)
    2200             : {
    2201           0 :         TALLOC_CTX *ctx;
    2202           0 :         LDAPMessage *res = NULL;
    2203           0 :         ADS_MODLIST mods;
    2204           0 :         const char *servicePrincipalName[1] = {NULL};
    2205           0 :         ADS_STATUS ret;
    2206           0 :         char *dn_string = NULL;
    2207             : 
    2208           0 :         ret = ads_find_machine_acct(ads, &res, machine_name);
    2209           0 :         if (!ADS_ERR_OK(ret)) {
    2210           0 :                 DEBUG(5,("ads_clear_service_principal_names: WARNING: Host Account for %s not found... skipping operation.\n", machine_name));
    2211           0 :                 DEBUG(5,("ads_clear_service_principal_names: WARNING: Service Principals for %s have NOT been cleared.\n", machine_name));
    2212           0 :                 ads_msgfree(ads, res);
    2213           0 :                 return ret;
    2214             :         }
    2215             : 
    2216           0 :         DEBUG(5,("ads_clear_service_principal_names: Host account for %s found\n", machine_name));
    2217           0 :         ctx = talloc_init("ads_clear_service_principal_names");
    2218           0 :         if (!ctx) {
    2219           0 :                 ads_msgfree(ads, res);
    2220           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2221             :         }
    2222             : 
    2223           0 :         if (!(mods = ads_init_mods(ctx))) {
    2224           0 :                 talloc_destroy(ctx);
    2225           0 :                 ads_msgfree(ads, res);
    2226           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2227             :         }
    2228           0 :         ret = ads_mod_strlist(ctx, &mods, "servicePrincipalName", servicePrincipalName);
    2229           0 :         if (!ADS_ERR_OK(ret)) {
    2230           0 :                 DEBUG(1,("ads_clear_service_principal_names: Error creating strlist.\n"));
    2231           0 :                 ads_msgfree(ads, res);
    2232           0 :                 talloc_destroy(ctx);
    2233           0 :                 return ret;
    2234             :         }
    2235           0 :         dn_string = ads_get_dn(ads, talloc_tos(), res);
    2236           0 :         if (!dn_string) {
    2237           0 :                 talloc_destroy(ctx);
    2238           0 :                 ads_msgfree(ads, res);
    2239           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2240             :         }
    2241           0 :         ret = ads_gen_mod(ads, dn_string, mods);
    2242           0 :         TALLOC_FREE(dn_string);
    2243           0 :         if (!ADS_ERR_OK(ret)) {
    2244           0 :                 DEBUG(1,("ads_clear_service_principal_names: Error: Updating Service Principals for machine %s in LDAP\n",
    2245             :                         machine_name));
    2246           0 :                 ads_msgfree(ads, res);
    2247           0 :                 talloc_destroy(ctx);
    2248           0 :                 return ret;
    2249             :         }
    2250             : 
    2251           0 :         ads_msgfree(ads, res);
    2252           0 :         talloc_destroy(ctx);
    2253           0 :         return ret;
    2254             : }
    2255             : 
    2256             : /**
    2257             :  * @brief Search for an element in a string array.
    2258             :  *
    2259             :  * @param[in]  el_array  The string array to search.
    2260             :  *
    2261             :  * @param[in]  num_el    The number of elements in the string array.
    2262             :  *
    2263             :  * @param[in]  el        The string to search.
    2264             :  *
    2265             :  * @return               True if found, false if not.
    2266             :  */
    2267         140 : bool ads_element_in_array(const char **el_array, size_t num_el, const char *el)
    2268             : {
    2269           0 :         size_t i;
    2270             : 
    2271         140 :         if (el_array == NULL || num_el == 0 || el == NULL) {
    2272           0 :                 return false;
    2273             :         }
    2274             : 
    2275         394 :         for (i = 0; i < num_el && el_array[i] != NULL; i++) {
    2276           0 :                 int cmp;
    2277             : 
    2278         370 :                 cmp = strcasecmp_m(el_array[i], el);
    2279         370 :                 if (cmp == 0) {
    2280         116 :                         return true;
    2281             :                 }
    2282             :         }
    2283             : 
    2284          24 :         return false;
    2285             : }
    2286             : 
    2287             : /**
    2288             :  * @brief This gets the service principal names of an existing computer account.
    2289             :  *
    2290             :  * @param[in]  mem_ctx      The memory context to use to allocate the spn array.
    2291             :  *
    2292             :  * @param[in]  ads          The ADS context to use.
    2293             :  *
    2294             :  * @param[in]  machine_name The NetBIOS name of the computer, which is used to
    2295             :  *                          identify the computer account.
    2296             :  *
    2297             :  * @param[in]  spn_array    A pointer to store the array for SPNs.
    2298             :  *
    2299             :  * @param[in]  num_spns     The number of principals stored in the array.
    2300             :  *
    2301             :  * @return                  0 on success, or a ADS error if a failure occurred.
    2302             :  */
    2303          90 : ADS_STATUS ads_get_service_principal_names(TALLOC_CTX *mem_ctx,
    2304             :                                            ADS_STRUCT *ads,
    2305             :                                            const char *machine_name,
    2306             :                                            char ***spn_array,
    2307             :                                            size_t *num_spns)
    2308             : {
    2309           0 :         ADS_STATUS status;
    2310          90 :         LDAPMessage *res = NULL;
    2311           0 :         int count;
    2312             : 
    2313          90 :         status = ads_find_machine_acct(ads,
    2314             :                                        &res,
    2315             :                                        machine_name);
    2316          90 :         if (!ADS_ERR_OK(status)) {
    2317           0 :                 DEBUG(1,("Host Account for %s not found... skipping operation.\n",
    2318             :                          machine_name));
    2319           0 :                 return status;
    2320             :         }
    2321             : 
    2322          90 :         count = ads_count_replies(ads, res);
    2323          90 :         if (count != 1) {
    2324           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    2325           0 :                 goto done;
    2326             :         }
    2327             : 
    2328          90 :         *spn_array = ads_pull_strings(ads,
    2329             :                                       mem_ctx,
    2330             :                                       res,
    2331             :                                       "servicePrincipalName",
    2332             :                                       num_spns);
    2333          90 :         if (*spn_array == NULL) {
    2334           0 :                 DEBUG(1, ("Host account for %s does not have service principal "
    2335             :                           "names.\n",
    2336             :                           machine_name));
    2337           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    2338           0 :                 goto done;
    2339             :         }
    2340             : 
    2341          90 : done:
    2342          90 :         ads_msgfree(ads, res);
    2343             : 
    2344          90 :         return status;
    2345             : }
    2346             : 
    2347             : /**
    2348             :  * This adds a service principal name to an existing computer account
    2349             :  * (found by hostname) in AD.
    2350             :  * @param ads An initialized ADS_STRUCT
    2351             :  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
    2352             :  * @param spns An array or strings for the service principals to add,
    2353             :  *        i.e. 'cifs/machine_name', 'http/machine.full.domain.com' etc.
    2354             :  * @return 0 upon success, or non-zero if a failure occurs
    2355             :  **/
    2356             : 
    2357           4 : ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
    2358             :                                            const char *machine_name,
    2359             :                                            const char **spns)
    2360             : {
    2361           0 :         ADS_STATUS ret;
    2362           0 :         TALLOC_CTX *ctx;
    2363           4 :         LDAPMessage *res = NULL;
    2364           0 :         ADS_MODLIST mods;
    2365           4 :         char *dn_string = NULL;
    2366           4 :         const char **servicePrincipalName = spns;
    2367             : 
    2368           4 :         ret = ads_find_machine_acct(ads, &res, machine_name);
    2369           4 :         if (!ADS_ERR_OK(ret)) {
    2370           0 :                 DEBUG(1,("ads_add_service_principal_name: WARNING: Host Account for %s not found... skipping operation.\n",
    2371             :                         machine_name));
    2372           0 :                 DEBUG(1,("ads_add_service_principal_name: WARNING: Service Principals have NOT been added.\n"));
    2373           0 :                 ads_msgfree(ads, res);
    2374           0 :                 return ret;
    2375             :         }
    2376             : 
    2377           4 :         DEBUG(1,("ads_add_service_principal_name: Host account for %s found\n", machine_name));
    2378           4 :         if (!(ctx = talloc_init("ads_add_service_principal_name"))) {
    2379           0 :                 ads_msgfree(ads, res);
    2380           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2381             :         }
    2382             : 
    2383           4 :         DEBUG(5,("ads_add_service_principal_name: INFO: "
    2384             :                 "Adding %s to host %s\n",
    2385             :                 spns[0] ? "N/A" : spns[0], machine_name));
    2386             : 
    2387             : 
    2388           4 :         DEBUG(5,("ads_add_service_principal_name: INFO: "
    2389             :                 "Adding %s to host %s\n",
    2390             :                 spns[1] ? "N/A" : spns[1], machine_name));
    2391             : 
    2392           4 :         if ( (mods = ads_init_mods(ctx)) == NULL ) {
    2393           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2394           0 :                 goto out;
    2395             :         }
    2396             : 
    2397           4 :         ret = ads_add_strlist(ctx,
    2398             :                               &mods,
    2399             :                               "servicePrincipalName",
    2400             :                               servicePrincipalName);
    2401           4 :         if (!ADS_ERR_OK(ret)) {
    2402           0 :                 DEBUG(1,("ads_add_service_principal_name: Error: Updating Service Principals in LDAP\n"));
    2403           0 :                 goto out;
    2404             :         }
    2405             : 
    2406           4 :         if ( (dn_string = ads_get_dn(ads, ctx, res)) == NULL ) {
    2407           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2408           0 :                 goto out;
    2409             :         }
    2410             : 
    2411           4 :         ret = ads_gen_mod(ads, dn_string, mods);
    2412           4 :         if (!ADS_ERR_OK(ret)) {
    2413           0 :                 DEBUG(1,("ads_add_service_principal_name: Error: Updating Service Principals in LDAP\n"));
    2414           0 :                 goto out;
    2415             :         }
    2416             : 
    2417           4 :  out:
    2418           4 :         TALLOC_FREE( ctx );
    2419           4 :         ads_msgfree(ads, res);
    2420           4 :         return ret;
    2421             : }
    2422             : 
    2423           4 : static uint32_t ads_get_acct_ctrl(ADS_STRUCT *ads,
    2424             :                                   LDAPMessage *msg)
    2425             : {
    2426           4 :         uint32_t acct_ctrl = 0;
    2427           0 :         bool ok;
    2428             : 
    2429           4 :         ok = ads_pull_uint32(ads, msg, "userAccountControl", &acct_ctrl);
    2430           4 :         if (!ok) {
    2431           0 :                 return 0;
    2432             :         }
    2433             : 
    2434           4 :         return acct_ctrl;
    2435             : }
    2436             : 
    2437           4 : static ADS_STATUS ads_change_machine_acct(ADS_STRUCT *ads,
    2438             :                                           LDAPMessage *msg,
    2439             :                                           const struct berval *machine_pw_val)
    2440             : {
    2441           0 :         ADS_MODLIST mods;
    2442           0 :         ADS_STATUS ret;
    2443           4 :         TALLOC_CTX *frame = talloc_stackframe();
    2444           0 :         uint32_t acct_control;
    2445           4 :         char *control_str = NULL;
    2446           4 :         const char *attrs[] = {
    2447             :                 "objectSid",
    2448             :                 NULL
    2449             :         };
    2450           4 :         LDAPMessage *res = NULL;
    2451           4 :         char *dn = NULL;
    2452             : 
    2453           4 :         dn = ads_get_dn(ads, frame, msg);
    2454           4 :         if (dn == NULL) {
    2455           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2456           0 :                 goto done;
    2457             :         }
    2458             : 
    2459           4 :         acct_control = ads_get_acct_ctrl(ads, msg);
    2460           4 :         if (acct_control == 0) {
    2461           0 :                 ret = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    2462           0 :                 goto done;
    2463             :         }
    2464             : 
    2465             :         /*
    2466             :          * Changing the password, disables the account. So we need to change the
    2467             :          * userAccountControl flags to enable it again.
    2468             :          */
    2469           4 :         mods = ads_init_mods(frame);
    2470           4 :         if (mods == NULL) {
    2471           0 :                 ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    2472           0 :                 goto done;
    2473             :         }
    2474             : 
    2475           4 :         ads_mod_ber(frame, &mods, "unicodePwd", machine_pw_val);
    2476             : 
    2477           4 :         ret = ads_gen_mod(ads, dn, mods);
    2478           4 :         if (!ADS_ERR_OK(ret)) {
    2479           0 :                 goto done;
    2480             :         }
    2481           4 :         TALLOC_FREE(mods);
    2482             : 
    2483             :         /*
    2484             :          * To activate the account, we need to disable and enable it.
    2485             :          */
    2486           4 :         acct_control |= UF_ACCOUNTDISABLE;
    2487             : 
    2488           4 :         control_str = talloc_asprintf(frame, "%u", acct_control);
    2489           4 :         if (control_str == NULL) {
    2490           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2491           0 :                 goto done;
    2492             :         }
    2493             : 
    2494           4 :         mods = ads_init_mods(frame);
    2495           4 :         if (mods == NULL) {
    2496           0 :                 ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    2497           0 :                 goto done;
    2498             :         }
    2499             : 
    2500           4 :         ads_mod_str(frame, &mods, "userAccountControl", control_str);
    2501             : 
    2502           4 :         ret = ads_gen_mod(ads, dn, mods);
    2503           4 :         if (!ADS_ERR_OK(ret)) {
    2504           0 :                 goto done;
    2505             :         }
    2506           4 :         TALLOC_FREE(mods);
    2507           4 :         TALLOC_FREE(control_str);
    2508             : 
    2509             :         /*
    2510             :          * Enable the account again.
    2511             :          */
    2512           4 :         acct_control &= ~UF_ACCOUNTDISABLE;
    2513             : 
    2514           4 :         control_str = talloc_asprintf(frame, "%u", acct_control);
    2515           4 :         if (control_str == NULL) {
    2516           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2517           0 :                 goto done;
    2518             :         }
    2519             : 
    2520           4 :         mods = ads_init_mods(frame);
    2521           4 :         if (mods == NULL) {
    2522           0 :                 ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    2523           0 :                 goto done;
    2524             :         }
    2525             : 
    2526           4 :         ads_mod_str(frame, &mods, "userAccountControl", control_str);
    2527             : 
    2528           4 :         ret = ads_gen_mod(ads, dn, mods);
    2529           4 :         if (!ADS_ERR_OK(ret)) {
    2530           0 :                 goto done;
    2531             :         }
    2532           4 :         TALLOC_FREE(mods);
    2533           4 :         TALLOC_FREE(control_str);
    2534             : 
    2535           4 :         ret = ads_search_dn(ads, &res, dn, attrs);
    2536           4 :         ads_msgfree(ads, res);
    2537             : 
    2538           4 : done:
    2539           4 :         talloc_free(frame);
    2540             : 
    2541           4 :         return ret;
    2542             : }
    2543             : 
    2544             : /**
    2545             :  * adds a machine account to the ADS server
    2546             :  * @param ads An initialized ADS_STRUCT
    2547             :  * @param machine_name - the NetBIOS machine name of this account.
    2548             :  * @param account_type A number indicating the type of account to create
    2549             :  * @param org_unit The LDAP path in which to place this account
    2550             :  * @return 0 upon success, or non-zero otherwise
    2551             : **/
    2552             : 
    2553          60 : ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads,
    2554             :                                    const char *machine_name,
    2555             :                                    const char *machine_password,
    2556             :                                    const char *org_unit,
    2557             :                                    uint32_t etype_list,
    2558             :                                    const char *dns_domain_name)
    2559             : {
    2560           0 :         ADS_STATUS ret;
    2561          60 :         char *samAccountName = NULL;
    2562          60 :         char *controlstr = NULL;
    2563          60 :         TALLOC_CTX *ctx = NULL;
    2564           0 :         ADS_MODLIST mods;
    2565          60 :         char *machine_escaped = NULL;
    2566          60 :         char *dns_hostname = NULL;
    2567          60 :         char *new_dn = NULL;
    2568          60 :         char *utf8_pw = NULL;
    2569          60 :         size_t utf8_pw_len = 0;
    2570          60 :         char *utf16_pw = NULL;
    2571          60 :         size_t utf16_pw_len = 0;
    2572           0 :         struct berval machine_pw_val;
    2573           0 :         bool ok;
    2574          60 :         const char **spn_array = NULL;
    2575          60 :         size_t num_spns = 0;
    2576          60 :         const char *spn_prefix[] = {
    2577             :                 "HOST",
    2578             :                 "RestrictedKrbHost",
    2579             :         };
    2580           0 :         size_t i;
    2581          60 :         LDAPMessage *res = NULL;
    2582          60 :         uint32_t acct_control = UF_WORKSTATION_TRUST_ACCOUNT;
    2583             : 
    2584          60 :         ctx = talloc_init("ads_add_machine_acct");
    2585          60 :         if (ctx == NULL) {
    2586           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    2587             :         }
    2588             : 
    2589          60 :         machine_escaped = escape_rdn_val_string_alloc(machine_name);
    2590          60 :         if (machine_escaped == NULL) {
    2591           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2592           0 :                 goto done;
    2593             :         }
    2594             : 
    2595          60 :         utf8_pw = talloc_asprintf(ctx, "\"%s\"", machine_password);
    2596          60 :         if (utf8_pw == NULL) {
    2597           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2598           0 :                 goto done;
    2599             :         }
    2600          60 :         utf8_pw_len = strlen(utf8_pw);
    2601             : 
    2602          60 :         ok = convert_string_talloc(ctx,
    2603             :                                    CH_UTF8, CH_UTF16MUNGED,
    2604             :                                    utf8_pw, utf8_pw_len,
    2605             :                                    (void *)&utf16_pw, &utf16_pw_len);
    2606          60 :         if (!ok) {
    2607           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2608           0 :                 goto done;
    2609             :         }
    2610             : 
    2611          60 :         machine_pw_val = (struct berval) {
    2612             :                 .bv_val = utf16_pw,
    2613             :                 .bv_len = utf16_pw_len,
    2614             :         };
    2615             : 
    2616             :         /* Check if the machine account already exists. */
    2617          60 :         ret = ads_find_machine_acct(ads, &res, machine_escaped);
    2618          60 :         if (ADS_ERR_OK(ret)) {
    2619             :                 /* Change the machine account password */
    2620           4 :                 ret = ads_change_machine_acct(ads, res, &machine_pw_val);
    2621           4 :                 ads_msgfree(ads, res);
    2622             : 
    2623           4 :                 goto done;
    2624             :         }
    2625          56 :         ads_msgfree(ads, res);
    2626             : 
    2627          56 :         new_dn = talloc_asprintf(ctx, "cn=%s,%s", machine_escaped, org_unit);
    2628          56 :         if (new_dn == NULL) {
    2629           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2630           0 :                 goto done;
    2631             :         }
    2632             : 
    2633             :         /* Create machine account */
    2634             : 
    2635          56 :         samAccountName = talloc_asprintf(ctx, "%s$", machine_name);
    2636          56 :         if (samAccountName == NULL) {
    2637           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2638           0 :                 goto done;
    2639             :         }
    2640             : 
    2641          56 :         dns_hostname = talloc_asprintf(ctx,
    2642             :                                        "%s.%s",
    2643             :                                        machine_name,
    2644             :                                        dns_domain_name);
    2645          56 :         if (dns_hostname == NULL) {
    2646           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2647           0 :                 goto done;
    2648             :         }
    2649             : 
    2650             :         /* Add dns_hostname SPNs */
    2651         168 :         for (i = 0; i < ARRAY_SIZE(spn_prefix); i++) {
    2652         112 :                 char *spn = talloc_asprintf(ctx,
    2653             :                                             "%s/%s",
    2654             :                                             spn_prefix[i],
    2655             :                                             dns_hostname);
    2656         112 :                 if (spn == NULL) {
    2657           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2658           0 :                         goto done;
    2659             :                 }
    2660             : 
    2661         112 :                 ok = add_string_to_array(ctx,
    2662             :                                          spn,
    2663             :                                          &spn_array,
    2664             :                                          &num_spns);
    2665         112 :                 if (!ok) {
    2666           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2667           0 :                         goto done;
    2668             :                 }
    2669             :         }
    2670             : 
    2671             :         /* Add machine_name SPNs */
    2672         168 :         for (i = 0; i < ARRAY_SIZE(spn_prefix); i++) {
    2673         112 :                 char *spn = talloc_asprintf(ctx,
    2674             :                                             "%s/%s",
    2675             :                                             spn_prefix[i],
    2676             :                                             machine_name);
    2677         112 :                 if (spn == NULL) {
    2678           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2679           0 :                         goto done;
    2680             :                 }
    2681             : 
    2682         112 :                 ok = add_string_to_array(ctx,
    2683             :                                          spn,
    2684             :                                          &spn_array,
    2685             :                                          &num_spns);
    2686         112 :                 if (!ok) {
    2687           0 :                         ret = ADS_ERROR(LDAP_NO_MEMORY);
    2688           0 :                         goto done;
    2689             :                 }
    2690             :         }
    2691             : 
    2692             :         /* Make sure to NULL terminate the array */
    2693          56 :         spn_array = talloc_realloc(ctx, spn_array, const char *, num_spns + 1);
    2694          56 :         if (spn_array == NULL) {
    2695           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2696           0 :                 goto done;
    2697             :         }
    2698          56 :         spn_array[num_spns] = NULL;
    2699             : 
    2700          56 :         controlstr = talloc_asprintf(ctx, "%u", acct_control);
    2701          56 :         if (controlstr == NULL) {
    2702           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2703           0 :                 goto done;
    2704             :         }
    2705             : 
    2706          56 :         mods = ads_init_mods(ctx);
    2707          56 :         if (mods == NULL) {
    2708           0 :                 ret = ADS_ERROR(LDAP_NO_MEMORY);
    2709           0 :                 goto done;
    2710             :         }
    2711             : 
    2712          56 :         ads_mod_str(ctx, &mods, "objectClass", "Computer");
    2713          56 :         ads_mod_str(ctx, &mods, "SamAccountName", samAccountName);
    2714          56 :         ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
    2715          56 :         ads_mod_str(ctx, &mods, "DnsHostName", dns_hostname);
    2716          56 :         ads_mod_strlist(ctx, &mods, "ServicePrincipalName", spn_array);
    2717          56 :         ads_mod_ber(ctx, &mods, "unicodePwd", &machine_pw_val);
    2718             : 
    2719          56 :         ret = ads_gen_add(ads, new_dn, mods);
    2720             : 
    2721          60 : done:
    2722          60 :         SAFE_FREE(machine_escaped);
    2723          60 :         talloc_destroy(ctx);
    2724             : 
    2725          60 :         return ret;
    2726             : }
    2727             : 
    2728             : /**
    2729             :  * move a machine account to another OU on the ADS server
    2730             :  * @param ads - An initialized ADS_STRUCT
    2731             :  * @param machine_name - the NetBIOS machine name of this account.
    2732             :  * @param org_unit - The LDAP path in which to place this account
    2733             :  * @param moved - whether we moved the machine account (optional)
    2734             :  * @return 0 upon success, or non-zero otherwise
    2735             : **/
    2736             : 
    2737           0 : ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name,
    2738             :                                  const char *org_unit, bool *moved)
    2739             : {
    2740           0 :         ADS_STATUS rc;
    2741           0 :         int ldap_status;
    2742           0 :         LDAPMessage *res = NULL;
    2743           0 :         char *filter = NULL;
    2744           0 :         char *computer_dn = NULL;
    2745           0 :         char *parent_dn;
    2746           0 :         char *computer_rdn = NULL;
    2747           0 :         bool need_move = False;
    2748             : 
    2749           0 :         if (asprintf(&filter, "(samAccountName=%s$)", machine_name) == -1) {
    2750           0 :                 rc = ADS_ERROR(LDAP_NO_MEMORY);
    2751           0 :                 goto done;
    2752             :         }
    2753             : 
    2754             :         /* Find pre-existing machine */
    2755           0 :         rc = ads_search(ads, &res, filter, NULL);
    2756           0 :         if (!ADS_ERR_OK(rc)) {
    2757           0 :                 goto done;
    2758             :         }
    2759             : 
    2760           0 :         computer_dn = ads_get_dn(ads, talloc_tos(), res);
    2761           0 :         if (!computer_dn) {
    2762           0 :                 rc = ADS_ERROR(LDAP_NO_MEMORY);
    2763           0 :                 goto done;
    2764             :         }
    2765             : 
    2766           0 :         parent_dn = ads_parent_dn(computer_dn);
    2767           0 :         if (strequal(parent_dn, org_unit)) {
    2768           0 :                 goto done;
    2769             :         }
    2770             : 
    2771           0 :         need_move = True;
    2772             : 
    2773           0 :         if (asprintf(&computer_rdn, "CN=%s", machine_name) == -1) {
    2774           0 :                 rc = ADS_ERROR(LDAP_NO_MEMORY);
    2775           0 :                 goto done;
    2776             :         }
    2777             : 
    2778           0 :         ldap_status = ldap_rename_s(ads->ldap.ld, computer_dn, computer_rdn,
    2779             :                                     org_unit, 1, NULL, NULL);
    2780           0 :         rc = ADS_ERROR(ldap_status);
    2781             : 
    2782           0 : done:
    2783           0 :         ads_msgfree(ads, res);
    2784           0 :         SAFE_FREE(filter);
    2785           0 :         TALLOC_FREE(computer_dn);
    2786           0 :         SAFE_FREE(computer_rdn);
    2787             : 
    2788           0 :         if (!ADS_ERR_OK(rc)) {
    2789           0 :                 need_move = False;
    2790             :         }
    2791             : 
    2792           0 :         if (moved) {
    2793           0 :                 *moved = need_move;
    2794             :         }
    2795             : 
    2796           0 :         return rc;
    2797             : }
    2798             : 
    2799             : /*
    2800             :   dump a binary result from ldap
    2801             : */
    2802           0 : static void dump_binary(ADS_STRUCT *ads, const char *field, struct berval **values)
    2803             : {
    2804           0 :         size_t i;
    2805           0 :         for (i=0; values[i]; i++) {
    2806           0 :                 ber_len_t j;
    2807           0 :                 printf("%s: ", field);
    2808           0 :                 for (j=0; j<values[i]->bv_len; j++) {
    2809           0 :                         printf("%02X", (unsigned char)values[i]->bv_val[j]);
    2810             :                 }
    2811           0 :                 printf("\n");
    2812             :         }
    2813           0 : }
    2814             : 
    2815           0 : static void dump_guid(ADS_STRUCT *ads, const char *field, struct berval **values)
    2816             : {
    2817           0 :         int i;
    2818           0 :         for (i=0; values[i]; i++) {
    2819           0 :                 NTSTATUS status;
    2820           0 :                 DATA_BLOB in = data_blob_const(values[i]->bv_val, values[i]->bv_len);
    2821           0 :                 struct GUID guid;
    2822             : 
    2823           0 :                 status = GUID_from_ndr_blob(&in, &guid);
    2824           0 :                 if (NT_STATUS_IS_OK(status)) {
    2825           0 :                         printf("%s: %s\n", field, GUID_string(talloc_tos(), &guid));
    2826             :                 } else {
    2827           0 :                         printf("%s: INVALID GUID\n", field);
    2828             :                 }
    2829             :         }
    2830           0 : }
    2831             : 
    2832             : /*
    2833             :   dump a sid result from ldap
    2834             : */
    2835           0 : static void dump_sid(ADS_STRUCT *ads, const char *field, struct berval **values)
    2836             : {
    2837           0 :         int i;
    2838           0 :         for (i=0; values[i]; i++) {
    2839           0 :                 ssize_t ret;
    2840           0 :                 struct dom_sid sid;
    2841           0 :                 struct dom_sid_buf tmp;
    2842           0 :                 ret = sid_parse((const uint8_t *)values[i]->bv_val,
    2843           0 :                                 values[i]->bv_len, &sid);
    2844           0 :                 if (ret == -1) {
    2845           0 :                         return;
    2846             :                 }
    2847           0 :                 printf("%s: %s\n", field, dom_sid_str_buf(&sid, &tmp));
    2848             :         }
    2849             : }
    2850             : 
    2851             : /*
    2852             :   dump ntSecurityDescriptor
    2853             : */
    2854           0 : static void dump_sd(ADS_STRUCT *ads, const char *filed, struct berval **values)
    2855             : {
    2856           0 :         TALLOC_CTX *frame = talloc_stackframe();
    2857           0 :         struct security_descriptor *psd;
    2858           0 :         NTSTATUS status;
    2859             : 
    2860           0 :         status = unmarshall_sec_desc(talloc_tos(), (uint8_t *)values[0]->bv_val,
    2861           0 :                                      values[0]->bv_len, &psd);
    2862           0 :         if (!NT_STATUS_IS_OK(status)) {
    2863           0 :                 DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
    2864             :                           nt_errstr(status)));
    2865           0 :                 TALLOC_FREE(frame);
    2866           0 :                 return;
    2867             :         }
    2868             : 
    2869           0 :         if (psd) {
    2870           0 :                 ads_disp_sd(ads, talloc_tos(), psd);
    2871             :         }
    2872             : 
    2873           0 :         TALLOC_FREE(frame);
    2874             : }
    2875             : 
    2876             : /*
    2877             :   dump a string result from ldap
    2878             : */
    2879          71 : static void dump_string(const char *field, char **values)
    2880             : {
    2881           0 :         int i;
    2882         218 :         for (i=0; values[i]; i++) {
    2883         147 :                 printf("%s: %s\n", field, values[i]);
    2884             :         }
    2885          71 : }
    2886             : 
    2887             : /*
    2888             :   dump a field from LDAP on stdout
    2889             :   used for debugging
    2890             : */
    2891             : 
    2892         213 : static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *data_area)
    2893             : {
    2894           0 :         const struct {
    2895             :                 const char *name;
    2896             :                 bool string;
    2897             :                 void (*handler)(ADS_STRUCT *, const char *, struct berval **);
    2898         213 :         } handlers[] = {
    2899             :                 {"objectGUID", False, dump_guid},
    2900             :                 {"netbootGUID", False, dump_guid},
    2901             :                 {"nTSecurityDescriptor", False, dump_sd},
    2902             :                 {"dnsRecord", False, dump_binary},
    2903             :                 {"objectSid", False, dump_sid},
    2904             :                 {"tokenGroups", False, dump_sid},
    2905             :                 {"tokenGroupsNoGCAcceptable", False, dump_sid},
    2906             :                 {"tokengroupsGlobalandUniversal", False, dump_sid},
    2907             :                 {"mS-DS-CreatorSID", False, dump_sid},
    2908             :                 {"msExchMailboxGuid", False, dump_guid},
    2909             :                 {NULL, True, NULL}
    2910             :         };
    2911           0 :         int i;
    2912             : 
    2913         213 :         if (!field) { /* must be end of an entry */
    2914          71 :                 printf("\n");
    2915          71 :                 return False;
    2916             :         }
    2917             : 
    2918        1562 :         for (i=0; handlers[i].name; i++) {
    2919        1420 :                 if (strcasecmp_m(handlers[i].name, field) == 0) {
    2920           0 :                         if (!values) /* first time, indicate string or not */
    2921           0 :                                 return handlers[i].string;
    2922           0 :                         handlers[i].handler(ads, field, (struct berval **) values);
    2923           0 :                         break;
    2924             :                 }
    2925             :         }
    2926         142 :         if (!handlers[i].name) {
    2927         142 :                 if (!values) /* first time, indicate string conversion */
    2928          71 :                         return True;
    2929          71 :                 dump_string(field, (char **)values);
    2930             :         }
    2931          71 :         return False;
    2932             : }
    2933             : 
    2934             : /**
    2935             :  * Dump a result from LDAP on stdout
    2936             :  *  used for debugging
    2937             :  * @param ads connection to ads server
    2938             :  * @param res Results to dump
    2939             :  **/
    2940             : 
    2941          33 :  void ads_dump(ADS_STRUCT *ads, LDAPMessage *res)
    2942             : {
    2943          33 :         ads_process_results(ads, res, ads_dump_field, NULL);
    2944          33 : }
    2945             : 
    2946             : /**
    2947             :  * Walk through results, calling a function for each entry found.
    2948             :  *  The function receives a field name, a berval * array of values,
    2949             :  *  and a data area passed through from the start.  The function is
    2950             :  *  called once with null for field and values at the end of each
    2951             :  *  entry.
    2952             :  * @param ads connection to ads server
    2953             :  * @param res Results to process
    2954             :  * @param fn Function for processing each result
    2955             :  * @param data_area user-defined area to pass to function
    2956             :  **/
    2957          33 :  void ads_process_results(ADS_STRUCT *ads, LDAPMessage *res,
    2958             :                           bool (*fn)(ADS_STRUCT *, char *, void **, void *),
    2959             :                           void *data_area)
    2960             : {
    2961           0 :         LDAPMessage *msg;
    2962           0 :         TALLOC_CTX *ctx;
    2963           0 :         size_t converted_size;
    2964             : 
    2965          33 :         if (!(ctx = talloc_init("ads_process_results")))
    2966           0 :                 return;
    2967             : 
    2968         104 :         for (msg = ads_first_entry(ads, res); msg;
    2969          71 :              msg = ads_next_entry(ads, msg)) {
    2970           0 :                 char *utf8_field;
    2971           0 :                 BerElement *b;
    2972             : 
    2973          71 :                 for (utf8_field=ldap_first_attribute(ads->ldap.ld,
    2974             :                                                      (LDAPMessage *)msg,&b);
    2975         142 :                      utf8_field;
    2976          71 :                      utf8_field=ldap_next_attribute(ads->ldap.ld,
    2977             :                                                     (LDAPMessage *)msg,b)) {
    2978           0 :                         struct berval **ber_vals;
    2979           0 :                         char **str_vals;
    2980           0 :                         char **utf8_vals;
    2981           0 :                         char *field;
    2982           0 :                         bool string;
    2983             : 
    2984          71 :                         if (!pull_utf8_talloc(ctx, &field, utf8_field,
    2985             :                                               &converted_size))
    2986             :                         {
    2987           0 :                                 DEBUG(0,("ads_process_results: "
    2988             :                                          "pull_utf8_talloc failed: %s\n",
    2989             :                                          strerror(errno)));
    2990             :                         }
    2991             : 
    2992          71 :                         string = fn(ads, field, NULL, data_area);
    2993             : 
    2994          71 :                         if (string) {
    2995           0 :                                 const char **p;
    2996             : 
    2997          71 :                                 utf8_vals = ldap_get_values(ads->ldap.ld,
    2998             :                                                  (LDAPMessage *)msg, field);
    2999          71 :                                 p = discard_const_p(const char *, utf8_vals);
    3000          71 :                                 str_vals = ads_pull_strvals(ctx, p);
    3001          71 :                                 fn(ads, field, (void **) str_vals, data_area);
    3002          71 :                                 ldap_value_free(utf8_vals);
    3003             :                         } else {
    3004           0 :                                 ber_vals = ldap_get_values_len(ads->ldap.ld,
    3005             :                                                  (LDAPMessage *)msg, field);
    3006           0 :                                 fn(ads, field, (void **) ber_vals, data_area);
    3007             : 
    3008           0 :                                 ldap_value_free_len(ber_vals);
    3009             :                         }
    3010          71 :                         ldap_memfree(utf8_field);
    3011             :                 }
    3012          71 :                 ber_free(b, 0);
    3013          71 :                 talloc_free_children(ctx);
    3014          71 :                 fn(ads, NULL, NULL, data_area); /* completed an entry */
    3015             : 
    3016             :         }
    3017          33 :         talloc_destroy(ctx);
    3018             : }
    3019             : 
    3020             : /**
    3021             :  * count how many replies are in a LDAPMessage
    3022             :  * @param ads connection to ads server
    3023             :  * @param res Results to count
    3024             :  * @return number of replies
    3025             :  **/
    3026        1469 : int ads_count_replies(ADS_STRUCT *ads, void *res)
    3027             : {
    3028        1469 :         return ldap_count_entries(ads->ldap.ld, (LDAPMessage *)res);
    3029             : }
    3030             : 
    3031             : /**
    3032             :  * pull the first entry from a ADS result
    3033             :  * @param ads connection to ads server
    3034             :  * @param res Results of search
    3035             :  * @return first entry from result
    3036             :  **/
    3037          65 :  LDAPMessage *ads_first_entry(ADS_STRUCT *ads, LDAPMessage *res)
    3038             : {
    3039          65 :         return ldap_first_entry(ads->ldap.ld, res);
    3040             : }
    3041             : 
    3042             : /**
    3043             :  * pull the next entry from a ADS result
    3044             :  * @param ads connection to ads server
    3045             :  * @param res Results of search
    3046             :  * @return next entry from result
    3047             :  **/
    3048          71 :  LDAPMessage *ads_next_entry(ADS_STRUCT *ads, LDAPMessage *res)
    3049             : {
    3050          71 :         return ldap_next_entry(ads->ldap.ld, res);
    3051             : }
    3052             : 
    3053             : /**
    3054             :  * pull the first message from a ADS result
    3055             :  * @param ads connection to ads server
    3056             :  * @param res Results of search
    3057             :  * @return first message from result
    3058             :  **/
    3059           0 :  LDAPMessage *ads_first_message(ADS_STRUCT *ads, LDAPMessage *res)
    3060             : {
    3061           0 :         return ldap_first_message(ads->ldap.ld, res);
    3062             : }
    3063             : 
    3064             : /**
    3065             :  * pull the next message from a ADS result
    3066             :  * @param ads connection to ads server
    3067             :  * @param res Results of search
    3068             :  * @return next message from result
    3069             :  **/
    3070           0 :  LDAPMessage *ads_next_message(ADS_STRUCT *ads, LDAPMessage *res)
    3071             : {
    3072           0 :         return ldap_next_message(ads->ldap.ld, res);
    3073             : }
    3074             : 
    3075             : /**
    3076             :  * pull a single string from a ADS result
    3077             :  * @param ads connection to ads server
    3078             :  * @param mem_ctx TALLOC_CTX to use for allocating result string
    3079             :  * @param msg Results of search
    3080             :  * @param field Attribute to retrieve
    3081             :  * @return Result string in talloc context
    3082             :  **/
    3083         561 :  char *ads_pull_string(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, LDAPMessage *msg,
    3084             :                        const char *field)
    3085             : {
    3086           0 :         char **values;
    3087         561 :         char *ret = NULL;
    3088           0 :         char *ux_string;
    3089           0 :         size_t converted_size;
    3090             : 
    3091         561 :         values = ldap_get_values(ads->ldap.ld, msg, field);
    3092         561 :         if (!values)
    3093          12 :                 return NULL;
    3094             : 
    3095         549 :         if (values[0] && pull_utf8_talloc(mem_ctx, &ux_string, values[0],
    3096             :                                           &converted_size))
    3097             :         {
    3098         549 :                 ret = ux_string;
    3099             :         }
    3100         549 :         ldap_value_free(values);
    3101         549 :         return ret;
    3102             : }
    3103             : 
    3104             : /**
    3105             :  * pull an array of strings from a ADS result
    3106             :  * @param ads connection to ads server
    3107             :  * @param mem_ctx TALLOC_CTX to use for allocating result string
    3108             :  * @param msg Results of search
    3109             :  * @param field Attribute to retrieve
    3110             :  * @return Result strings in talloc context
    3111             :  **/
    3112          90 :  char **ads_pull_strings(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3113             :                          LDAPMessage *msg, const char *field,
    3114             :                          size_t *num_values)
    3115             : {
    3116           0 :         char **values;
    3117          90 :         char **ret = NULL;
    3118           0 :         size_t i, converted_size;
    3119             : 
    3120          90 :         values = ldap_get_values(ads->ldap.ld, msg, field);
    3121          90 :         if (!values)
    3122           0 :                 return NULL;
    3123             : 
    3124          90 :         *num_values = ldap_count_values(values);
    3125             : 
    3126          90 :         ret = talloc_array(mem_ctx, char *, *num_values + 1);
    3127          90 :         if (!ret) {
    3128           0 :                 ldap_value_free(values);
    3129           0 :                 return NULL;
    3130             :         }
    3131             : 
    3132         480 :         for (i=0;i<*num_values;i++) {
    3133         390 :                 if (!pull_utf8_talloc(mem_ctx, &ret[i], values[i],
    3134             :                                       &converted_size))
    3135             :                 {
    3136           0 :                         ldap_value_free(values);
    3137           0 :                         return NULL;
    3138             :                 }
    3139             :         }
    3140          90 :         ret[i] = NULL;
    3141             : 
    3142          90 :         ldap_value_free(values);
    3143          90 :         return ret;
    3144             : }
    3145             : 
    3146             : /**
    3147             :  * pull an array of strings from a ADS result
    3148             :  *  (handle large multivalue attributes with range retrieval)
    3149             :  * @param ads connection to ads server
    3150             :  * @param mem_ctx TALLOC_CTX to use for allocating result string
    3151             :  * @param msg Results of search
    3152             :  * @param field Attribute to retrieve
    3153             :  * @param current_strings strings returned by a previous call to this function
    3154             :  * @param next_attribute The next query should ask for this attribute
    3155             :  * @param num_values How many values did we get this time?
    3156             :  * @param more_values Are there more values to get?
    3157             :  * @return Result strings in talloc context
    3158             :  **/
    3159           0 :  char **ads_pull_strings_range(ADS_STRUCT *ads,
    3160             :                                TALLOC_CTX *mem_ctx,
    3161             :                                LDAPMessage *msg, const char *field,
    3162             :                                char **current_strings,
    3163             :                                const char **next_attribute,
    3164             :                                size_t *num_strings,
    3165             :                                bool *more_strings)
    3166             : {
    3167           0 :         char *attr;
    3168           0 :         char *expected_range_attrib, *range_attr = NULL;
    3169           0 :         BerElement *ptr = NULL;
    3170           0 :         char **strings;
    3171           0 :         char **new_strings;
    3172           0 :         size_t num_new_strings;
    3173           0 :         unsigned long int range_start;
    3174           0 :         unsigned long int range_end;
    3175             : 
    3176             :         /* we might have been given the whole lot anyway */
    3177           0 :         if ((strings = ads_pull_strings(ads, mem_ctx, msg, field, num_strings))) {
    3178           0 :                 *more_strings = False;
    3179           0 :                 return strings;
    3180             :         }
    3181             : 
    3182           0 :         expected_range_attrib = talloc_asprintf(mem_ctx, "%s;Range=", field);
    3183             : 
    3184             :         /* look for Range result */
    3185           0 :         for (attr = ldap_first_attribute(ads->ldap.ld, (LDAPMessage *)msg, &ptr);
    3186           0 :              attr;
    3187           0 :              attr = ldap_next_attribute(ads->ldap.ld, (LDAPMessage *)msg, ptr)) {
    3188             :                 /* we ignore the fact that this is utf8, as all attributes are ascii... */
    3189           0 :                 if (strnequal(attr, expected_range_attrib, strlen(expected_range_attrib))) {
    3190           0 :                         range_attr = attr;
    3191           0 :                         break;
    3192             :                 }
    3193           0 :                 ldap_memfree(attr);
    3194             :         }
    3195           0 :         if (!range_attr) {
    3196           0 :                 ber_free(ptr, 0);
    3197             :                 /* nothing here - this field is just empty */
    3198           0 :                 *more_strings = False;
    3199           0 :                 return NULL;
    3200             :         }
    3201             : 
    3202           0 :         if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-%lu",
    3203             :                    &range_start, &range_end) == 2) {
    3204           0 :                 *more_strings = True;
    3205             :         } else {
    3206           0 :                 if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-*",
    3207             :                            &range_start) == 1) {
    3208           0 :                         *more_strings = False;
    3209             :                 } else {
    3210           0 :                         DEBUG(1, ("ads_pull_strings_range:  Cannot parse Range attribute (%s)\n",
    3211             :                                   range_attr));
    3212           0 :                         ldap_memfree(range_attr);
    3213           0 :                         *more_strings = False;
    3214           0 :                         return NULL;
    3215             :                 }
    3216             :         }
    3217             : 
    3218           0 :         if ((*num_strings) != range_start) {
    3219           0 :                 DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) doesn't start at %u, but at %lu"
    3220             :                           " - aborting range retrieval\n",
    3221             :                           range_attr, (unsigned int)(*num_strings) + 1, range_start));
    3222           0 :                 ldap_memfree(range_attr);
    3223           0 :                 *more_strings = False;
    3224           0 :                 return NULL;
    3225             :         }
    3226             : 
    3227           0 :         new_strings = ads_pull_strings(ads, mem_ctx, msg, range_attr, &num_new_strings);
    3228             : 
    3229           0 :         if (*more_strings && ((*num_strings + num_new_strings) != (range_end + 1))) {
    3230           0 :                 DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) tells us we have %lu "
    3231             :                           "strings in this bunch, but we only got %lu - aborting range retrieval\n",
    3232             :                           range_attr, (unsigned long int)range_end - range_start + 1,
    3233             :                           (unsigned long int)num_new_strings));
    3234           0 :                 ldap_memfree(range_attr);
    3235           0 :                 *more_strings = False;
    3236           0 :                 return NULL;
    3237             :         }
    3238             : 
    3239           0 :         strings = talloc_realloc(mem_ctx, current_strings, char *,
    3240             :                                  *num_strings + num_new_strings);
    3241             : 
    3242           0 :         if (strings == NULL) {
    3243           0 :                 ldap_memfree(range_attr);
    3244           0 :                 *more_strings = False;
    3245           0 :                 return NULL;
    3246             :         }
    3247             : 
    3248           0 :         if (new_strings && num_new_strings) {
    3249           0 :                 memcpy(&strings[*num_strings], new_strings,
    3250             :                        sizeof(*new_strings) * num_new_strings);
    3251             :         }
    3252             : 
    3253           0 :         (*num_strings) += num_new_strings;
    3254             : 
    3255           0 :         if (*more_strings) {
    3256           0 :                 *next_attribute = talloc_asprintf(mem_ctx,
    3257             :                                                   "%s;range=%d-*",
    3258             :                                                   field,
    3259           0 :                                                   (int)*num_strings);
    3260             : 
    3261           0 :                 if (!*next_attribute) {
    3262           0 :                         DEBUG(1, ("talloc_asprintf for next attribute failed!\n"));
    3263           0 :                         ldap_memfree(range_attr);
    3264           0 :                         *more_strings = False;
    3265           0 :                         return NULL;
    3266             :                 }
    3267             :         }
    3268             : 
    3269           0 :         ldap_memfree(range_attr);
    3270             : 
    3271           0 :         return strings;
    3272             : }
    3273             : 
    3274             : /**
    3275             :  * pull a single uint32_t from a ADS result
    3276             :  * @param ads connection to ads server
    3277             :  * @param msg Results of search
    3278             :  * @param field Attribute to retrieve
    3279             :  * @param v Pointer to int to store result
    3280             :  * @return boolean indicating success
    3281             : */
    3282         386 :  bool ads_pull_uint32(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
    3283             :                       uint32_t *v)
    3284             : {
    3285           0 :         char **values;
    3286             : 
    3287         386 :         values = ldap_get_values(ads->ldap.ld, msg, field);
    3288         386 :         if (!values)
    3289         172 :                 return False;
    3290         214 :         if (!values[0]) {
    3291           0 :                 ldap_value_free(values);
    3292           0 :                 return False;
    3293             :         }
    3294             : 
    3295         214 :         *v = atoi(values[0]);
    3296         214 :         ldap_value_free(values);
    3297         214 :         return True;
    3298             : }
    3299             : 
    3300             : /**
    3301             :  * pull a single objectGUID from an ADS result
    3302             :  * @param ads connection to ADS server
    3303             :  * @param msg results of search
    3304             :  * @param guid 37-byte area to receive text guid
    3305             :  * @return boolean indicating success
    3306             :  **/
    3307           0 :  bool ads_pull_guid(ADS_STRUCT *ads, LDAPMessage *msg, struct GUID *guid)
    3308             : {
    3309           0 :         DATA_BLOB blob;
    3310           0 :         NTSTATUS status;
    3311             : 
    3312           0 :         if (!smbldap_talloc_single_blob(talloc_tos(), ads->ldap.ld, msg, "objectGUID",
    3313             :                                         &blob)) {
    3314           0 :                 return false;
    3315             :         }
    3316             : 
    3317           0 :         status = GUID_from_ndr_blob(&blob, guid);
    3318           0 :         talloc_free(blob.data);
    3319           0 :         return NT_STATUS_IS_OK(status);
    3320             : }
    3321             : 
    3322             : 
    3323             : /**
    3324             :  * pull a single struct dom_sid from a ADS result
    3325             :  * @param ads connection to ads server
    3326             :  * @param msg Results of search
    3327             :  * @param field Attribute to retrieve
    3328             :  * @param sid Pointer to sid to store result
    3329             :  * @return boolean indicating success
    3330             : */
    3331         178 :  bool ads_pull_sid(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
    3332             :                    struct dom_sid *sid)
    3333             : {
    3334         178 :         return smbldap_pull_sid(ads->ldap.ld, msg, field, sid);
    3335             : }
    3336             : 
    3337             : /**
    3338             :  * pull an array of struct dom_sids from a ADS result
    3339             :  * @param ads connection to ads server
    3340             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    3341             :  * @param msg Results of search
    3342             :  * @param field Attribute to retrieve
    3343             :  * @param sids pointer to sid array to allocate
    3344             :  * @return the count of SIDs pulled
    3345             :  **/
    3346           2 :  int ads_pull_sids(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3347             :                    LDAPMessage *msg, const char *field, struct dom_sid **sids)
    3348             : {
    3349           0 :         struct berval **values;
    3350           0 :         int count, i;
    3351             : 
    3352           2 :         values = ldap_get_values_len(ads->ldap.ld, msg, field);
    3353             : 
    3354           2 :         if (!values)
    3355           0 :                 return 0;
    3356             : 
    3357           6 :         for (i=0; values[i]; i++)
    3358             :                 /* nop */ ;
    3359             : 
    3360           2 :         if (i) {
    3361           2 :                 (*sids) = talloc_array(mem_ctx, struct dom_sid, i);
    3362           2 :                 if (!(*sids)) {
    3363           0 :                         ldap_value_free_len(values);
    3364           0 :                         return 0;
    3365             :                 }
    3366             :         } else {
    3367           0 :                 (*sids) = NULL;
    3368             :         }
    3369             : 
    3370           2 :         count = 0;
    3371           6 :         for (i=0; values[i]; i++) {
    3372           0 :                 ssize_t ret;
    3373           4 :                 ret = sid_parse((const uint8_t *)values[i]->bv_val,
    3374           4 :                                 values[i]->bv_len, &(*sids)[count]);
    3375           4 :                 if (ret != -1) {
    3376           0 :                         struct dom_sid_buf buf;
    3377           4 :                         DBG_DEBUG("pulling SID: %s\n",
    3378             :                                   dom_sid_str_buf(&(*sids)[count], &buf));
    3379           4 :                         count++;
    3380             :                 }
    3381             :         }
    3382             : 
    3383           2 :         ldap_value_free_len(values);
    3384           2 :         return count;
    3385             : }
    3386             : 
    3387             : /**
    3388             :  * pull a struct security_descriptor from a ADS result
    3389             :  * @param ads connection to ads server
    3390             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    3391             :  * @param msg Results of search
    3392             :  * @param field Attribute to retrieve
    3393             :  * @param sd Pointer to *struct security_descriptor to store result (talloc()ed)
    3394             :  * @return boolean indicating success
    3395             : */
    3396           4 :  bool ads_pull_sd(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3397             :                   LDAPMessage *msg, const char *field,
    3398             :                   struct security_descriptor **sd)
    3399             : {
    3400           0 :         struct berval **values;
    3401           4 :         bool ret = true;
    3402             : 
    3403           4 :         values = ldap_get_values_len(ads->ldap.ld, msg, field);
    3404             : 
    3405           4 :         if (!values) return false;
    3406             : 
    3407           4 :         if (values[0]) {
    3408           0 :                 NTSTATUS status;
    3409           4 :                 status = unmarshall_sec_desc(mem_ctx,
    3410           4 :                                              (uint8_t *)values[0]->bv_val,
    3411           4 :                                              values[0]->bv_len, sd);
    3412           4 :                 if (!NT_STATUS_IS_OK(status)) {
    3413           0 :                         DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
    3414             :                                   nt_errstr(status)));
    3415           0 :                         ret = false;
    3416             :                 }
    3417             :         }
    3418             : 
    3419           4 :         ldap_value_free_len(values);
    3420           4 :         return ret;
    3421             : }
    3422             : 
    3423             : /*
    3424             :  * in order to support usernames longer than 21 characters we need to
    3425             :  * use both the sAMAccountName and the userPrincipalName attributes
    3426             :  * It seems that not all users have the userPrincipalName attribute set
    3427             :  *
    3428             :  * @param ads connection to ads server
    3429             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    3430             :  * @param msg Results of search
    3431             :  * @return the username
    3432             :  */
    3433           0 :  char *ads_pull_username(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    3434             :                          LDAPMessage *msg)
    3435             : {
    3436             : #if 0   /* JERRY */
    3437             :         char *ret, *p;
    3438             : 
    3439             :         /* lookup_name() only works on the sAMAccountName to
    3440             :            returning the username portion of userPrincipalName
    3441             :            breaks winbindd_getpwnam() */
    3442             : 
    3443             :         ret = ads_pull_string(ads, mem_ctx, msg, "userPrincipalName");
    3444             :         if (ret && (p = strchr_m(ret, '@'))) {
    3445             :                 *p = 0;
    3446             :                 return ret;
    3447             :         }
    3448             : #endif
    3449           0 :         return ads_pull_string(ads, mem_ctx, msg, "sAMAccountName");
    3450             : }
    3451             : 
    3452             : 
    3453             : /**
    3454             :  * find the update serial number - this is the core of the ldap cache
    3455             :  * @param ads connection to ads server
    3456             :  * @param ads connection to ADS server
    3457             :  * @param usn Pointer to retrieved update serial number
    3458             :  * @return status of search
    3459             :  **/
    3460           0 : ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32_t *usn)
    3461             : {
    3462           0 :         const char *attrs[] = {"highestCommittedUSN", NULL};
    3463           0 :         ADS_STATUS status;
    3464           0 :         LDAPMessage *res;
    3465             : 
    3466           0 :         status = ads_do_search_retry(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3467           0 :         if (!ADS_ERR_OK(status))
    3468           0 :                 return status;
    3469             : 
    3470           0 :         if (ads_count_replies(ads, res) != 1) {
    3471           0 :                 ads_msgfree(ads, res);
    3472           0 :                 return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3473             :         }
    3474             : 
    3475           0 :         if (!ads_pull_uint32(ads, res, "highestCommittedUSN", usn)) {
    3476           0 :                 ads_msgfree(ads, res);
    3477           0 :                 return ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
    3478             :         }
    3479             : 
    3480           0 :         ads_msgfree(ads, res);
    3481           0 :         return ADS_SUCCESS;
    3482             : }
    3483             : 
    3484             : /* parse a ADS timestring - typical string is
    3485             :    '20020917091222.0Z0' which means 09:12.22 17th September
    3486             :    2002, timezone 0 */
    3487         357 : static time_t ads_parse_time(const char *str)
    3488             : {
    3489           0 :         struct tm tm;
    3490             : 
    3491         357 :         ZERO_STRUCT(tm);
    3492             : 
    3493         357 :         if (sscanf(str, "%4d%2d%2d%2d%2d%2d",
    3494             :                    &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
    3495             :                    &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
    3496           0 :                 return 0;
    3497             :         }
    3498         357 :         tm.tm_year -= 1900;
    3499         357 :         tm.tm_mon -= 1;
    3500             : 
    3501         357 :         return timegm(&tm);
    3502             : }
    3503             : 
    3504             : /********************************************************************
    3505             : ********************************************************************/
    3506             : 
    3507         357 : ADS_STATUS ads_current_time(ADS_STRUCT *ads)
    3508             : {
    3509         357 :         const char *attrs[] = {"currentTime", NULL};
    3510           0 :         ADS_STATUS status;
    3511           0 :         LDAPMessage *res;
    3512           0 :         char *timestr;
    3513         357 :         TALLOC_CTX *tmp_ctx = talloc_stackframe();
    3514         357 :         ADS_STRUCT *ads_s = ads;
    3515             : 
    3516             :         /* establish a new ldap tcp session if necessary */
    3517             : 
    3518         357 :         if ( !ads->ldap.ld ) {
    3519             :                 /*
    3520             :                  * ADS_STRUCT may be being reused after a
    3521             :                  * DC lookup, so ads->ldap.ss may already have a
    3522             :                  * good address. If not, re-initialize the passed-in
    3523             :                  * ADS_STRUCT with the given server.XXXX parameters.
    3524             :                  *
    3525             :                  * Note that this doesn't depend on
    3526             :                  * ads->server.ldap_server != NULL,
    3527             :                  * as the case where ads->server.ldap_server==NULL and
    3528             :                  * ads->ldap.ss != zero_address is precisely the DC
    3529             :                  * lookup case where ads->ldap.ss was found by going
    3530             :                  * through ads_find_dc() again we want to avoid repeating.
    3531             :                  */
    3532          15 :                 if (is_zero_addr(&ads->ldap.ss)) {
    3533           0 :                         ads_s = ads_init(tmp_ctx,
    3534             :                                          ads->server.realm,
    3535             :                                          ads->server.workgroup,
    3536             :                                          ads->server.ldap_server,
    3537             :                                          ADS_SASL_PLAIN );
    3538           0 :                         if (ads_s == NULL) {
    3539           0 :                                 status = ADS_ERROR(LDAP_NO_MEMORY);
    3540           0 :                                 goto done;
    3541             :                         }
    3542             :                 }
    3543             : 
    3544             :                 /*
    3545             :                  * Reset ads->config.flags as it can contain the flags
    3546             :                  * returned by the previous CLDAP ping when reusing the struct.
    3547             :                  */
    3548          15 :                 ads_s->config.flags = 0;
    3549             : 
    3550          15 :                 ads_s->auth.flags = ADS_AUTH_ANON_BIND;
    3551          15 :                 status = ads_connect( ads_s );
    3552          15 :                 if ( !ADS_ERR_OK(status))
    3553           0 :                         goto done;
    3554             :         }
    3555             : 
    3556         357 :         status = ads_do_search(ads_s, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3557         357 :         if (!ADS_ERR_OK(status)) {
    3558           0 :                 goto done;
    3559             :         }
    3560             : 
    3561         357 :         timestr = ads_pull_string(ads_s, tmp_ctx, res, "currentTime");
    3562         357 :         if (!timestr) {
    3563           0 :                 ads_msgfree(ads_s, res);
    3564           0 :                 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3565           0 :                 goto done;
    3566             :         }
    3567             : 
    3568             :         /* but save the time and offset in the original ADS_STRUCT */
    3569             : 
    3570         357 :         ads->config.current_time = ads_parse_time(timestr);
    3571             : 
    3572         357 :         if (ads->config.current_time != 0) {
    3573         357 :                 ads->auth.time_offset = ads->config.current_time - time(NULL);
    3574         357 :                 DEBUG(4,("KDC time offset is %d seconds\n", ads->auth.time_offset));
    3575             :         }
    3576             : 
    3577         357 :         ads_msgfree(ads, res);
    3578             : 
    3579         357 :         status = ADS_SUCCESS;
    3580             : 
    3581         357 : done:
    3582         357 :         TALLOC_FREE(tmp_ctx);
    3583             : 
    3584         357 :         return status;
    3585             : }
    3586             : 
    3587             : /********************************************************************
    3588             : ********************************************************************/
    3589             : 
    3590         116 : ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
    3591             : {
    3592         116 :         TALLOC_CTX *tmp_ctx = talloc_stackframe();
    3593         116 :         const char *attrs[] = {"domainFunctionality", NULL};
    3594           0 :         ADS_STATUS status;
    3595           0 :         LDAPMessage *res;
    3596         116 :         ADS_STRUCT *ads_s = ads;
    3597             : 
    3598         116 :         *val = DS_DOMAIN_FUNCTION_2000;
    3599             : 
    3600             :         /* establish a new ldap tcp session if necessary */
    3601             : 
    3602         116 :         if ( !ads->ldap.ld ) {
    3603             :                 /*
    3604             :                  * ADS_STRUCT may be being reused after a
    3605             :                  * DC lookup, so ads->ldap.ss may already have a
    3606             :                  * good address. If not, re-initialize the passed-in
    3607             :                  * ADS_STRUCT with the given server.XXXX parameters.
    3608             :                  *
    3609             :                  * Note that this doesn't depend on
    3610             :                  * ads->server.ldap_server != NULL,
    3611             :                  * as the case where ads->server.ldap_server==NULL and
    3612             :                  * ads->ldap.ss != zero_address is precisely the DC
    3613             :                  * lookup case where ads->ldap.ss was found by going
    3614             :                  * through ads_find_dc() again we want to avoid repeating.
    3615             :                  */
    3616           0 :                 if (is_zero_addr(&ads->ldap.ss)) {
    3617           0 :                         ads_s = ads_init(tmp_ctx,
    3618             :                                          ads->server.realm,
    3619             :                                          ads->server.workgroup,
    3620             :                                          ads->server.ldap_server,
    3621             :                                          ADS_SASL_PLAIN );
    3622           0 :                         if (ads_s == NULL ) {
    3623           0 :                                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    3624           0 :                                 goto done;
    3625             :                         }
    3626             :                 }
    3627             : 
    3628             :                 /*
    3629             :                  * Reset ads->config.flags as it can contain the flags
    3630             :                  * returned by the previous CLDAP ping when reusing the struct.
    3631             :                  */
    3632           0 :                 ads_s->config.flags = 0;
    3633             : 
    3634           0 :                 ads_s->auth.flags = ADS_AUTH_ANON_BIND;
    3635           0 :                 status = ads_connect( ads_s );
    3636           0 :                 if ( !ADS_ERR_OK(status))
    3637           0 :                         goto done;
    3638             :         }
    3639             : 
    3640             :         /* If the attribute does not exist assume it is a Windows 2000
    3641             :            functional domain */
    3642             : 
    3643         116 :         status = ads_do_search(ads_s, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3644         116 :         if (!ADS_ERR_OK(status)) {
    3645           0 :                 if ( status.err.rc == LDAP_NO_SUCH_ATTRIBUTE ) {
    3646           0 :                         status = ADS_SUCCESS;
    3647             :                 }
    3648           0 :                 goto done;
    3649             :         }
    3650             : 
    3651         116 :         if ( !ads_pull_uint32(ads_s, res, "domainFunctionality", val) ) {
    3652           0 :                 DEBUG(5,("ads_domain_func_level: Failed to pull the domainFunctionality attribute.\n"));
    3653             :         }
    3654         116 :         DEBUG(3,("ads_domain_func_level: %d\n", *val));
    3655             : 
    3656             : 
    3657         116 :         ads_msgfree(ads_s, res);
    3658             : 
    3659         116 : done:
    3660         116 :         TALLOC_FREE(tmp_ctx);
    3661             : 
    3662         116 :         return status;
    3663             : }
    3664             : 
    3665             : /**
    3666             :  * find the domain sid for our domain
    3667             :  * @param ads connection to ads server
    3668             :  * @param sid Pointer to domain sid
    3669             :  * @return status of search
    3670             :  **/
    3671           0 : ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
    3672             : {
    3673           0 :         const char *attrs[] = {"objectSid", NULL};
    3674           0 :         LDAPMessage *res;
    3675           0 :         ADS_STATUS rc;
    3676             : 
    3677           0 :         rc = ads_do_search_retry(ads, ads->config.bind_path, LDAP_SCOPE_BASE, "(objectclass=*)",
    3678             :                            attrs, &res);
    3679           0 :         if (!ADS_ERR_OK(rc)) return rc;
    3680           0 :         if (!ads_pull_sid(ads, res, "objectSid", sid)) {
    3681           0 :                 ads_msgfree(ads, res);
    3682           0 :                 return ADS_ERROR_SYSTEM(ENOENT);
    3683             :         }
    3684           0 :         ads_msgfree(ads, res);
    3685             : 
    3686           0 :         return ADS_SUCCESS;
    3687             : }
    3688             : 
    3689             : /**
    3690             :  * find our site name
    3691             :  * @param ads connection to ads server
    3692             :  * @param mem_ctx Pointer to talloc context
    3693             :  * @param site_name Pointer to the sitename
    3694             :  * @return status of search
    3695             :  **/
    3696           2 : ADS_STATUS ads_site_dn(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char **site_name)
    3697             : {
    3698           0 :         ADS_STATUS status;
    3699           0 :         LDAPMessage *res;
    3700           0 :         const char *dn, *service_name;
    3701           2 :         const char *attrs[] = { "dsServiceName", NULL };
    3702             : 
    3703           2 :         status = ads_do_search(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
    3704           2 :         if (!ADS_ERR_OK(status)) {
    3705           0 :                 return status;
    3706             :         }
    3707             : 
    3708           2 :         service_name = ads_pull_string(ads, mem_ctx, res, "dsServiceName");
    3709           2 :         if (service_name == NULL) {
    3710           0 :                 ads_msgfree(ads, res);
    3711           0 :                 return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3712             :         }
    3713             : 
    3714           2 :         ads_msgfree(ads, res);
    3715             : 
    3716             :         /* go up three levels */
    3717           2 :         dn = ads_parent_dn(ads_parent_dn(ads_parent_dn(service_name)));
    3718           2 :         if (dn == NULL) {
    3719           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3720             :         }
    3721             : 
    3722           2 :         *site_name = talloc_strdup(mem_ctx, dn);
    3723           2 :         if (*site_name == NULL) {
    3724           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3725             :         }
    3726             : 
    3727           2 :         return status;
    3728             :         /*
    3729             :         dsServiceName: CN=NTDS Settings,CN=W2K3DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ber,DC=suse,DC=de
    3730             :         */
    3731             : }
    3732             : 
    3733             : /**
    3734             :  * find the site dn where a machine resides
    3735             :  * @param ads connection to ads server
    3736             :  * @param mem_ctx Pointer to talloc context
    3737             :  * @param computer_name name of the machine
    3738             :  * @param site_name Pointer to the sitename
    3739             :  * @return status of search
    3740             :  **/
    3741           2 : ADS_STATUS ads_site_dn_for_machine(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char *computer_name, const char **site_dn)
    3742             : {
    3743           0 :         ADS_STATUS status;
    3744           0 :         LDAPMessage *res;
    3745           0 :         const char *parent, *filter;
    3746           2 :         char *config_context = NULL;
    3747           0 :         char *dn;
    3748             : 
    3749             :         /* shortcut a query */
    3750           2 :         if (strequal(computer_name, ads->config.ldap_server_name)) {
    3751           2 :                 return ads_site_dn(ads, mem_ctx, site_dn);
    3752             :         }
    3753             : 
    3754           0 :         status = ads_config_path(ads, mem_ctx, &config_context);
    3755           0 :         if (!ADS_ERR_OK(status)) {
    3756           0 :                 return status;
    3757             :         }
    3758             : 
    3759           0 :         filter = talloc_asprintf(mem_ctx, "(cn=%s)", computer_name);
    3760           0 :         if (filter == NULL) {
    3761           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3762             :         }
    3763             : 
    3764           0 :         status = ads_do_search(ads, config_context, LDAP_SCOPE_SUBTREE,
    3765             :                                filter, NULL, &res);
    3766           0 :         if (!ADS_ERR_OK(status)) {
    3767           0 :                 return status;
    3768             :         }
    3769             : 
    3770           0 :         if (ads_count_replies(ads, res) != 1) {
    3771           0 :                 ads_msgfree(ads, res);
    3772           0 :                 return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    3773             :         }
    3774             : 
    3775           0 :         dn = ads_get_dn(ads, mem_ctx, res);
    3776           0 :         if (dn == NULL) {
    3777           0 :                 ads_msgfree(ads, res);
    3778           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3779             :         }
    3780             : 
    3781             :         /* go up three levels */
    3782           0 :         parent = ads_parent_dn(ads_parent_dn(ads_parent_dn(dn)));
    3783           0 :         if (parent == NULL) {
    3784           0 :                 ads_msgfree(ads, res);
    3785           0 :                 TALLOC_FREE(dn);
    3786           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3787             :         }
    3788             : 
    3789           0 :         *site_dn = talloc_strdup(mem_ctx, parent);
    3790           0 :         if (*site_dn == NULL) {
    3791           0 :                 ads_msgfree(ads, res);
    3792           0 :                 TALLOC_FREE(dn);
    3793           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3794             :         }
    3795             : 
    3796           0 :         TALLOC_FREE(dn);
    3797           0 :         ads_msgfree(ads, res);
    3798             : 
    3799           0 :         return status;
    3800             : }
    3801             : 
    3802             : /**
    3803             :  * get the upn suffixes for a domain
    3804             :  * @param ads connection to ads server
    3805             :  * @param mem_ctx Pointer to talloc context
    3806             :  * @param suffixes Pointer to an array of suffixes
    3807             :  * @param num_suffixes Pointer to the number of suffixes
    3808             :  * @return status of search
    3809             :  **/
    3810           0 : ADS_STATUS ads_upn_suffixes(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, char ***suffixes, size_t *num_suffixes)
    3811             : {
    3812           0 :         ADS_STATUS status;
    3813           0 :         LDAPMessage *res;
    3814           0 :         const char *base;
    3815           0 :         char *config_context = NULL;
    3816           0 :         const char *attrs[] = { "uPNSuffixes", NULL };
    3817             : 
    3818           0 :         status = ads_config_path(ads, mem_ctx, &config_context);
    3819           0 :         if (!ADS_ERR_OK(status)) {
    3820           0 :                 return status;
    3821             :         }
    3822             : 
    3823           0 :         base = talloc_asprintf(mem_ctx, "cn=Partitions,%s", config_context);
    3824           0 :         if (base == NULL) {
    3825           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3826             :         }
    3827             : 
    3828           0 :         status = ads_search_dn(ads, &res, base, attrs);
    3829           0 :         if (!ADS_ERR_OK(status)) {
    3830           0 :                 return status;
    3831             :         }
    3832             : 
    3833           0 :         if (ads_count_replies(ads, res) != 1) {
    3834           0 :                 ads_msgfree(ads, res);
    3835           0 :                 return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    3836             :         }
    3837             : 
    3838           0 :         (*suffixes) = ads_pull_strings(ads, mem_ctx, res, "uPNSuffixes", num_suffixes);
    3839           0 :         if ((*suffixes) == NULL) {
    3840           0 :                 ads_msgfree(ads, res);
    3841           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    3842             :         }
    3843             : 
    3844           0 :         ads_msgfree(ads, res);
    3845             : 
    3846           0 :         return status;
    3847             : }
    3848             : 
    3849             : /**
    3850             :  * get the joinable ous for a domain
    3851             :  * @param ads connection to ads server
    3852             :  * @param mem_ctx Pointer to talloc context
    3853             :  * @param ous Pointer to an array of ous
    3854             :  * @param num_ous Pointer to the number of ous
    3855             :  * @return status of search
    3856             :  **/
    3857           0 : ADS_STATUS ads_get_joinable_ous(ADS_STRUCT *ads,
    3858             :                                 TALLOC_CTX *mem_ctx,
    3859             :                                 char ***ous,
    3860             :                                 size_t *num_ous)
    3861             : {
    3862           0 :         ADS_STATUS status;
    3863           0 :         LDAPMessage *res = NULL;
    3864           0 :         LDAPMessage *msg = NULL;
    3865           0 :         const char *attrs[] = { "dn", NULL };
    3866           0 :         int count = 0;
    3867             : 
    3868           0 :         status = ads_search(ads, &res,
    3869             :                             "(|(objectClass=domain)(objectclass=organizationalUnit))",
    3870             :                             attrs);
    3871           0 :         if (!ADS_ERR_OK(status)) {
    3872           0 :                 return status;
    3873             :         }
    3874             : 
    3875           0 :         count = ads_count_replies(ads, res);
    3876           0 :         if (count < 1) {
    3877           0 :                 ads_msgfree(ads, res);
    3878           0 :                 return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    3879             :         }
    3880             : 
    3881           0 :         for (msg = ads_first_entry(ads, res); msg;
    3882           0 :              msg = ads_next_entry(ads, msg)) {
    3883           0 :                 const char **p = discard_const_p(const char *, *ous);
    3884           0 :                 char *dn = NULL;
    3885             : 
    3886           0 :                 dn = ads_get_dn(ads, talloc_tos(), msg);
    3887           0 :                 if (!dn) {
    3888           0 :                         ads_msgfree(ads, res);
    3889           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    3890             :                 }
    3891             : 
    3892           0 :                 if (!add_string_to_array(mem_ctx, dn, &p, num_ous)) {
    3893           0 :                         TALLOC_FREE(dn);
    3894           0 :                         ads_msgfree(ads, res);
    3895           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    3896             :                 }
    3897             : 
    3898           0 :                 TALLOC_FREE(dn);
    3899           0 :                 *ous = discard_const_p(char *, p);
    3900             :         }
    3901             : 
    3902           0 :         ads_msgfree(ads, res);
    3903             : 
    3904           0 :         return status;
    3905             : }
    3906             : 
    3907             : 
    3908             : /**
    3909             :  * pull a struct dom_sid from an extended dn string
    3910             :  * @param mem_ctx TALLOC_CTX
    3911             :  * @param extended_dn string
    3912             :  * @param flags string type of extended_dn
    3913             :  * @param sid pointer to a struct dom_sid
    3914             :  * @return NT_STATUS_OK on success,
    3915             :  *         NT_INVALID_PARAMETER on error,
    3916             :  *         NT_STATUS_NOT_FOUND if no SID present
    3917             :  **/
    3918           0 : ADS_STATUS ads_get_sid_from_extended_dn(TALLOC_CTX *mem_ctx,
    3919             :                                         const char *extended_dn,
    3920             :                                         enum ads_extended_dn_flags flags,
    3921             :                                         struct dom_sid *sid)
    3922             : {
    3923           0 :         char *p, *q, *dn;
    3924             : 
    3925           0 :         if (!extended_dn) {
    3926           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3927             :         }
    3928             : 
    3929             :         /* otherwise extended_dn gets stripped off */
    3930           0 :         if ((dn = talloc_strdup(mem_ctx, extended_dn)) == NULL) {
    3931           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3932             :         }
    3933             :         /*
    3934             :          * ADS_EXTENDED_DN_HEX_STRING:
    3935             :          * <GUID=238e1963cb390f4bb032ba0105525a29>;<SID=010500000000000515000000bb68c8fd6b61b427572eb04556040000>;CN=gd,OU=berlin,OU=suse,DC=ber,DC=suse,DC=de
    3936             :          *
    3937             :          * ADS_EXTENDED_DN_STRING (only with w2k3):
    3938             :          * <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
    3939             :          *
    3940             :          * Object with no SID, such as an Exchange Public Folder
    3941             :          * <GUID=28907fb4bdf6854993e7f0a10b504e7c>;CN=public,CN=Microsoft Exchange System Objects,DC=sd2k3ms,DC=west,DC=isilon,DC=com
    3942             :          */
    3943             : 
    3944           0 :         p = strchr(dn, ';');
    3945           0 :         if (!p) {
    3946           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3947             :         }
    3948             : 
    3949           0 :         if (strncmp(p, ";<SID=", strlen(";<SID=")) != 0) {
    3950           0 :                 DEBUG(5,("No SID present in extended dn\n"));
    3951           0 :                 return ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
    3952             :         }
    3953             : 
    3954           0 :         p += strlen(";<SID=");
    3955             : 
    3956           0 :         q = strchr(p, '>');
    3957           0 :         if (!q) {
    3958           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3959             :         }
    3960             : 
    3961           0 :         *q = '\0';
    3962             : 
    3963           0 :         DEBUG(100,("ads_get_sid_from_extended_dn: sid string is %s\n", p));
    3964             : 
    3965           0 :         switch (flags) {
    3966             : 
    3967           0 :         case ADS_EXTENDED_DN_STRING:
    3968           0 :                 if (!string_to_sid(sid, p)) {
    3969           0 :                         return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3970             :                 }
    3971           0 :                 break;
    3972           0 :         case ADS_EXTENDED_DN_HEX_STRING: {
    3973           0 :                 ssize_t ret;
    3974           0 :                 fstring buf;
    3975           0 :                 size_t buf_len;
    3976             : 
    3977           0 :                 buf_len = strhex_to_str(buf, sizeof(buf), p, strlen(p));
    3978           0 :                 if (buf_len == 0) {
    3979           0 :                         return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3980             :                 }
    3981             : 
    3982           0 :                 ret = sid_parse((const uint8_t *)buf, buf_len, sid);
    3983           0 :                 if (ret == -1) {
    3984           0 :                         DEBUG(10,("failed to parse sid\n"));
    3985           0 :                         return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3986             :                 }
    3987           0 :                 break;
    3988             :                 }
    3989           0 :         default:
    3990           0 :                 DEBUG(10,("unknown extended dn format\n"));
    3991           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    3992             :         }
    3993             : 
    3994           0 :         return ADS_ERROR_NT(NT_STATUS_OK);
    3995             : }
    3996             : 
    3997             : /********************************************************************
    3998             : ********************************************************************/
    3999             : 
    4000          70 : char* ads_get_dnshostname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
    4001             : {
    4002          70 :         LDAPMessage *res = NULL;
    4003           0 :         ADS_STATUS status;
    4004          70 :         int count = 0;
    4005          70 :         char *name = NULL;
    4006             : 
    4007          70 :         status = ads_find_machine_acct(ads, &res, machine_name);
    4008          70 :         if (!ADS_ERR_OK(status)) {
    4009           0 :                 DEBUG(0,("ads_get_dnshostname: Failed to find account for %s\n",
    4010             :                         lp_netbios_name()));
    4011           0 :                 goto out;
    4012             :         }
    4013             : 
    4014          70 :         if ( (count = ads_count_replies(ads, res)) != 1 ) {
    4015           0 :                 DEBUG(1,("ads_get_dnshostname: %d entries returned!\n", count));
    4016           0 :                 goto out;
    4017             :         }
    4018             : 
    4019          70 :         if ( (name = ads_pull_string(ads, ctx, res, "dNSHostName")) == NULL ) {
    4020           0 :                 DEBUG(0,("ads_get_dnshostname: No dNSHostName attribute!\n"));
    4021             :         }
    4022             : 
    4023          70 : out:
    4024          70 :         ads_msgfree(ads, res);
    4025             : 
    4026          70 :         return name;
    4027             : }
    4028             : 
    4029             : /********************************************************************
    4030             : ********************************************************************/
    4031             : 
    4032         124 : static char **get_addl_hosts(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
    4033             :                               LDAPMessage *msg, size_t *num_values)
    4034             : {
    4035         124 :         const char *field = "msDS-AdditionalDnsHostName";
    4036         124 :         struct berval **values = NULL;
    4037         124 :         char **ret = NULL;
    4038           0 :         size_t i, converted_size;
    4039             : 
    4040             :         /*
    4041             :          * Windows DC implicitly adds a short name for each FQDN added to
    4042             :          * msDS-AdditionalDnsHostName, but it comes with a strange binary
    4043             :          * suffix "\0$" which we should ignore (see bug #14406).
    4044             :          */
    4045             : 
    4046         124 :         values = ldap_get_values_len(ads->ldap.ld, msg, field);
    4047         124 :         if (values == NULL) {
    4048          96 :                 return NULL;
    4049             :         }
    4050             : 
    4051          28 :         *num_values = ldap_count_values_len(values);
    4052             : 
    4053          28 :         ret = talloc_array(mem_ctx, char *, *num_values + 1);
    4054          28 :         if (ret == NULL) {
    4055           0 :                 ldap_value_free_len(values);
    4056           0 :                 return NULL;
    4057             :         }
    4058             : 
    4059         112 :         for (i = 0; i < *num_values; i++) {
    4060          84 :                 ret[i] = NULL;
    4061          84 :                 if (!convert_string_talloc(mem_ctx, CH_UTF8, CH_UNIX,
    4062          84 :                                            values[i]->bv_val,
    4063          84 :                                            strnlen(values[i]->bv_val,
    4064          84 :                                                    values[i]->bv_len),
    4065          84 :                                            &ret[i], &converted_size)) {
    4066           0 :                         ldap_value_free_len(values);
    4067           0 :                         return NULL;
    4068             :                 }
    4069             :         }
    4070          28 :         ret[i] = NULL;
    4071             : 
    4072          28 :         ldap_value_free_len(values);
    4073          28 :         return ret;
    4074             : }
    4075             : 
    4076         124 : ADS_STATUS ads_get_additional_dns_hostnames(TALLOC_CTX *mem_ctx,
    4077             :                                             ADS_STRUCT *ads,
    4078             :                                             const char *machine_name,
    4079             :                                             char ***hostnames_array,
    4080             :                                             size_t *num_hostnames)
    4081             : {
    4082           0 :         ADS_STATUS status;
    4083         124 :         LDAPMessage *res = NULL;
    4084           0 :         int count;
    4085             : 
    4086         124 :         status = ads_find_machine_acct(ads,
    4087             :                                        &res,
    4088             :                                        machine_name);
    4089         124 :         if (!ADS_ERR_OK(status)) {
    4090           0 :                 DEBUG(1,("Host Account for %s not found... skipping operation.\n",
    4091             :                          machine_name));
    4092           0 :                 return status;
    4093             :         }
    4094             : 
    4095         124 :         count = ads_count_replies(ads, res);
    4096         124 :         if (count != 1) {
    4097           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    4098           0 :                 goto done;
    4099             :         }
    4100             : 
    4101         124 :         *hostnames_array = get_addl_hosts(ads, mem_ctx, res, num_hostnames);
    4102         124 :         if (*hostnames_array == NULL) {
    4103          96 :                 DEBUG(1, ("Host account for %s does not have msDS-AdditionalDnsHostName.\n",
    4104             :                           machine_name));
    4105          96 :                 status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
    4106          96 :                 goto done;
    4107             :         }
    4108             : 
    4109          28 : done:
    4110         124 :         ads_msgfree(ads, res);
    4111             : 
    4112         124 :         return status;
    4113             : }
    4114             : 
    4115             : /********************************************************************
    4116             : ********************************************************************/
    4117             : 
    4118          10 : char* ads_get_upn( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
    4119             : {
    4120          10 :         LDAPMessage *res = NULL;
    4121           0 :         ADS_STATUS status;
    4122          10 :         int count = 0;
    4123          10 :         char *name = NULL;
    4124             : 
    4125          10 :         status = ads_find_machine_acct(ads, &res, machine_name);
    4126          10 :         if (!ADS_ERR_OK(status)) {
    4127           0 :                 DEBUG(0,("ads_get_upn: Failed to find account for %s\n",
    4128             :                         lp_netbios_name()));
    4129           0 :                 goto out;
    4130             :         }
    4131             : 
    4132          10 :         if ( (count = ads_count_replies(ads, res)) != 1 ) {
    4133           0 :                 DEBUG(1,("ads_get_upn: %d entries returned!\n", count));
    4134           0 :                 goto out;
    4135             :         }
    4136             : 
    4137          10 :         if ( (name = ads_pull_string(ads, ctx, res, "userPrincipalName")) == NULL ) {
    4138           8 :                 DEBUG(2,("ads_get_upn: No userPrincipalName attribute!\n"));
    4139             :         }
    4140             : 
    4141           2 : out:
    4142          10 :         ads_msgfree(ads, res);
    4143             : 
    4144          10 :         return name;
    4145             : }
    4146             : 
    4147             : /********************************************************************
    4148             : ********************************************************************/
    4149             : 
    4150          74 : bool ads_has_samaccountname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
    4151             : {
    4152          74 :         LDAPMessage *res = NULL;
    4153           0 :         ADS_STATUS status;
    4154          74 :         int count = 0;
    4155          74 :         char *name = NULL;
    4156          74 :         bool ok = false;
    4157             : 
    4158          74 :         status = ads_find_machine_acct(ads, &res, machine_name);
    4159          74 :         if (!ADS_ERR_OK(status)) {
    4160           0 :                 DEBUG(0,("ads_has_samaccountname: Failed to find account for %s\n",
    4161             :                         lp_netbios_name()));
    4162           0 :                 goto out;
    4163             :         }
    4164             : 
    4165          74 :         if ( (count = ads_count_replies(ads, res)) != 1 ) {
    4166           0 :                 DEBUG(1,("ads_has_samaccountname: %d entries returned!\n", count));
    4167           0 :                 goto out;
    4168             :         }
    4169             : 
    4170          74 :         if ( (name = ads_pull_string(ads, ctx, res, "sAMAccountName")) == NULL ) {
    4171           0 :                 DEBUG(0,("ads_has_samaccountname: No sAMAccountName attribute!\n"));
    4172             :         }
    4173             : 
    4174          74 : out:
    4175          74 :         ads_msgfree(ads, res);
    4176          74 :         if (name != NULL) {
    4177          74 :                 ok = (strlen(name) > 0);
    4178             :         }
    4179          74 :         TALLOC_FREE(name);
    4180          74 :         return ok;
    4181             : }
    4182             : 
    4183             : #if 0
    4184             : 
    4185             :    SAVED CODE - we used to join via ldap - remember how we did this. JRA.
    4186             : 
    4187             : /**
    4188             :  * Join a machine to a realm
    4189             :  *  Creates the machine account and sets the machine password
    4190             :  * @param ads connection to ads server
    4191             :  * @param machine name of host to add
    4192             :  * @param org_unit Organizational unit to place machine in
    4193             :  * @return status of join
    4194             :  **/
    4195             : ADS_STATUS ads_join_realm(ADS_STRUCT *ads, const char *machine_name,
    4196             :                         uint32_t account_type, const char *org_unit)
    4197             : {
    4198             :         ADS_STATUS status;
    4199             :         LDAPMessage *res = NULL;
    4200             :         char *machine;
    4201             : 
    4202             :         /* machine name must be lowercase */
    4203             :         machine = SMB_STRDUP(machine_name);
    4204             :         strlower_m(machine);
    4205             : 
    4206             :         /*
    4207             :         status = ads_find_machine_acct(ads, (void **)&res, machine);
    4208             :         if (ADS_ERR_OK(status) && ads_count_replies(ads, res) == 1) {
    4209             :                 DEBUG(0, ("Host account for %s already exists - deleting old account\n", machine));
    4210             :                 status = ads_leave_realm(ads, machine);
    4211             :                 if (!ADS_ERR_OK(status)) {
    4212             :                         DEBUG(0, ("Failed to delete host '%s' from the '%s' realm.\n",
    4213             :                                 machine, ads->config.realm));
    4214             :                         return status;
    4215             :                 }
    4216             :         }
    4217             :         */
    4218             :         status = ads_add_machine_acct(ads, machine, account_type, org_unit);
    4219             :         if (!ADS_ERR_OK(status)) {
    4220             :                 DEBUG(0, ("ads_join_realm: ads_add_machine_acct failed (%s): %s\n", machine, ads_errstr(status)));
    4221             :                 SAFE_FREE(machine);
    4222             :                 return status;
    4223             :         }
    4224             : 
    4225             :         status = ads_find_machine_acct(ads, (void **)(void *)&res, machine);
    4226             :         if (!ADS_ERR_OK(status)) {
    4227             :                 DEBUG(0, ("ads_join_realm: Host account test failed for machine %s\n", machine));
    4228             :                 SAFE_FREE(machine);
    4229             :                 return status;
    4230             :         }
    4231             : 
    4232             :         SAFE_FREE(machine);
    4233             :         ads_msgfree(ads, res);
    4234             : 
    4235             :         return status;
    4236             : }
    4237             : #endif
    4238             : 
    4239             : /**
    4240             :  * Delete a machine from the realm
    4241             :  * @param ads connection to ads server
    4242             :  * @param hostname Machine to remove
    4243             :  * @return status of delete
    4244             :  **/
    4245          32 : ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
    4246             : {
    4247           0 :         ADS_STATUS status;
    4248           0 :         void *msg;
    4249           0 :         LDAPMessage *res;
    4250           0 :         char *hostnameDN, *host;
    4251           0 :         int rc;
    4252           0 :         LDAPControl ldap_control;
    4253          32 :         LDAPControl  * pldap_control[2] = {NULL, NULL};
    4254             : 
    4255          32 :         pldap_control[0] = &ldap_control;
    4256          32 :         memset(&ldap_control, 0, sizeof(LDAPControl));
    4257          32 :         ldap_control.ldctl_oid = discard_const_p(char, LDAP_SERVER_TREE_DELETE_OID);
    4258             : 
    4259             :         /* hostname must be lowercase */
    4260          32 :         host = SMB_STRDUP(hostname);
    4261          32 :         if (!strlower_m(host)) {
    4262           0 :                 SAFE_FREE(host);
    4263           0 :                 return ADS_ERROR_SYSTEM(EINVAL);
    4264             :         }
    4265             : 
    4266          32 :         status = ads_find_machine_acct(ads, &res, host);
    4267          32 :         if (!ADS_ERR_OK(status)) {
    4268           0 :                 DEBUG(0, ("Host account for %s does not exist.\n", host));
    4269           0 :                 SAFE_FREE(host);
    4270           0 :                 return status;
    4271             :         }
    4272             : 
    4273          32 :         msg = ads_first_entry(ads, res);
    4274          32 :         if (!msg) {
    4275           0 :                 SAFE_FREE(host);
    4276           0 :                 return ADS_ERROR_SYSTEM(ENOENT);
    4277             :         }
    4278             : 
    4279          32 :         hostnameDN = ads_get_dn(ads, talloc_tos(), (LDAPMessage *)msg);
    4280          32 :         if (hostnameDN == NULL) {
    4281           0 :                 SAFE_FREE(host);
    4282           0 :                 return ADS_ERROR_SYSTEM(ENOENT);
    4283             :         }
    4284             : 
    4285          32 :         rc = ldap_delete_ext_s(ads->ldap.ld, hostnameDN, pldap_control, NULL);
    4286          32 :         if (rc) {
    4287           0 :                 DEBUG(3,("ldap_delete_ext_s failed with error code %d\n", rc));
    4288             :         }else {
    4289          32 :                 DEBUG(3,("ldap_delete_ext_s succeeded with error code %d\n", rc));
    4290             :         }
    4291             : 
    4292          32 :         if (rc != LDAP_SUCCESS) {
    4293           0 :                 const char *attrs[] = { "cn", NULL };
    4294           0 :                 LDAPMessage *msg_sub;
    4295             : 
    4296             :                 /* we only search with scope ONE, we do not expect any further
    4297             :                  * objects to be created deeper */
    4298             : 
    4299           0 :                 status = ads_do_search_retry(ads, hostnameDN,
    4300             :                                              LDAP_SCOPE_ONELEVEL,
    4301             :                                              "(objectclass=*)", attrs, &res);
    4302             : 
    4303           0 :                 if (!ADS_ERR_OK(status)) {
    4304           0 :                         SAFE_FREE(host);
    4305           0 :                         TALLOC_FREE(hostnameDN);
    4306           0 :                         return status;
    4307             :                 }
    4308             : 
    4309           0 :                 for (msg_sub = ads_first_entry(ads, res); msg_sub;
    4310           0 :                         msg_sub = ads_next_entry(ads, msg_sub)) {
    4311             : 
    4312           0 :                         char *dn = NULL;
    4313             : 
    4314           0 :                         if ((dn = ads_get_dn(ads, talloc_tos(), msg_sub)) == NULL) {
    4315           0 :                                 SAFE_FREE(host);
    4316           0 :                                 TALLOC_FREE(hostnameDN);
    4317           0 :                                 return ADS_ERROR(LDAP_NO_MEMORY);
    4318             :                         }
    4319             : 
    4320           0 :                         status = ads_del_dn(ads, dn);
    4321           0 :                         if (!ADS_ERR_OK(status)) {
    4322           0 :                                 DEBUG(3,("failed to delete dn %s: %s\n", dn, ads_errstr(status)));
    4323           0 :                                 SAFE_FREE(host);
    4324           0 :                                 TALLOC_FREE(dn);
    4325           0 :                                 TALLOC_FREE(hostnameDN);
    4326           0 :                                 return status;
    4327             :                         }
    4328             : 
    4329           0 :                         TALLOC_FREE(dn);
    4330             :                 }
    4331             : 
    4332             :                 /* there should be no subordinate objects anymore */
    4333           0 :                 status = ads_do_search_retry(ads, hostnameDN,
    4334             :                                              LDAP_SCOPE_ONELEVEL,
    4335             :                                              "(objectclass=*)", attrs, &res);
    4336             : 
    4337           0 :                 if (!ADS_ERR_OK(status) || ( (ads_count_replies(ads, res)) > 0 ) ) {
    4338           0 :                         SAFE_FREE(host);
    4339           0 :                         TALLOC_FREE(hostnameDN);
    4340           0 :                         return status;
    4341             :                 }
    4342             : 
    4343             :                 /* delete hostnameDN now */
    4344           0 :                 status = ads_del_dn(ads, hostnameDN);
    4345           0 :                 if (!ADS_ERR_OK(status)) {
    4346           0 :                         SAFE_FREE(host);
    4347           0 :                         DEBUG(3,("failed to delete dn %s: %s\n", hostnameDN, ads_errstr(status)));
    4348           0 :                         TALLOC_FREE(hostnameDN);
    4349           0 :                         return status;
    4350             :                 }
    4351             :         }
    4352             : 
    4353          32 :         TALLOC_FREE(hostnameDN);
    4354             : 
    4355          32 :         status = ads_find_machine_acct(ads, &res, host);
    4356          32 :         if ((status.error_type == ENUM_ADS_ERROR_LDAP) &&
    4357          32 :             (status.err.rc != LDAP_NO_SUCH_OBJECT)) {
    4358           0 :                 DEBUG(3, ("Failed to remove host account.\n"));
    4359           0 :                 SAFE_FREE(host);
    4360           0 :                 return status;
    4361             :         }
    4362             : 
    4363          32 :         SAFE_FREE(host);
    4364          32 :         return ADS_SUCCESS;
    4365             : }
    4366             : 
    4367             : /**
    4368             :  * pull all token-sids from an LDAP dn
    4369             :  * @param ads connection to ads server
    4370             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    4371             :  * @param dn of LDAP object
    4372             :  * @param user_sid pointer to struct dom_sid (objectSid)
    4373             :  * @param primary_group_sid pointer to struct dom_sid (self composed)
    4374             :  * @param sids pointer to sid array to allocate
    4375             :  * @param num_sids counter of SIDs pulled
    4376             :  * @return status of token query
    4377             :  **/
    4378           2 :  ADS_STATUS ads_get_tokensids(ADS_STRUCT *ads,
    4379             :                               TALLOC_CTX *mem_ctx,
    4380             :                               const char *dn,
    4381             :                               struct dom_sid *user_sid,
    4382             :                               struct dom_sid *primary_group_sid,
    4383             :                               struct dom_sid **sids,
    4384             :                               size_t *num_sids)
    4385             : {
    4386           0 :         ADS_STATUS status;
    4387           2 :         LDAPMessage *res = NULL;
    4388           2 :         int count = 0;
    4389           0 :         size_t tmp_num_sids;
    4390           0 :         struct dom_sid *tmp_sids;
    4391           0 :         struct dom_sid tmp_user_sid;
    4392           0 :         struct dom_sid tmp_primary_group_sid;
    4393           0 :         uint32_t pgid;
    4394           2 :         const char *attrs[] = {
    4395             :                 "objectSid",
    4396             :                 "tokenGroups",
    4397             :                 "primaryGroupID",
    4398             :                 NULL
    4399             :         };
    4400             : 
    4401           2 :         status = ads_search_retry_dn(ads, &res, dn, attrs);
    4402           2 :         if (!ADS_ERR_OK(status)) {
    4403           0 :                 return status;
    4404             :         }
    4405             : 
    4406           2 :         count = ads_count_replies(ads, res);
    4407           2 :         if (count != 1) {
    4408           0 :                 ads_msgfree(ads, res);
    4409           0 :                 return ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
    4410             :         }
    4411             : 
    4412           2 :         if (!ads_pull_sid(ads, res, "objectSid", &tmp_user_sid)) {
    4413           0 :                 ads_msgfree(ads, res);
    4414           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4415             :         }
    4416             : 
    4417           2 :         if (!ads_pull_uint32(ads, res, "primaryGroupID", &pgid)) {
    4418           0 :                 ads_msgfree(ads, res);
    4419           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4420             :         }
    4421             : 
    4422             :         {
    4423             :                 /* hack to compose the primary group sid without knowing the
    4424             :                  * domsid */
    4425             : 
    4426           0 :                 struct dom_sid domsid;
    4427             : 
    4428           2 :                 sid_copy(&domsid, &tmp_user_sid);
    4429             : 
    4430           2 :                 if (!sid_split_rid(&domsid, NULL)) {
    4431           0 :                         ads_msgfree(ads, res);
    4432           0 :                         return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4433             :                 }
    4434             : 
    4435           2 :                 if (!sid_compose(&tmp_primary_group_sid, &domsid, pgid)) {
    4436           0 :                         ads_msgfree(ads, res);
    4437           0 :                         return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4438             :                 }
    4439             :         }
    4440             : 
    4441           2 :         tmp_num_sids = ads_pull_sids(ads, mem_ctx, res, "tokenGroups", &tmp_sids);
    4442             : 
    4443           2 :         if (tmp_num_sids == 0 || !tmp_sids) {
    4444           0 :                 ads_msgfree(ads, res);
    4445           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4446             :         }
    4447             : 
    4448           2 :         if (num_sids) {
    4449           2 :                 *num_sids = tmp_num_sids;
    4450             :         }
    4451             : 
    4452           2 :         if (sids) {
    4453           2 :                 *sids = tmp_sids;
    4454             :         }
    4455             : 
    4456           2 :         if (user_sid) {
    4457           2 :                 *user_sid = tmp_user_sid;
    4458             :         }
    4459             : 
    4460           2 :         if (primary_group_sid) {
    4461           2 :                 *primary_group_sid = tmp_primary_group_sid;
    4462             :         }
    4463             : 
    4464           2 :         DEBUG(10,("ads_get_tokensids: returned %d sids\n", (int)tmp_num_sids + 2));
    4465             : 
    4466           2 :         ads_msgfree(ads, res);
    4467           2 :         return ADS_ERROR_LDAP(LDAP_SUCCESS);
    4468             : }
    4469             : 
    4470             : /**
    4471             :  * Find a sAMAccountName in LDAP
    4472             :  * @param ads connection to ads server
    4473             :  * @param mem_ctx TALLOC_CTX for allocating sid array
    4474             :  * @param samaccountname to search
    4475             :  * @param uac_ret uint32_t pointer userAccountControl attribute value
    4476             :  * @param dn_ret pointer to dn
    4477             :  * @return status of token query
    4478             :  **/
    4479           0 : ADS_STATUS ads_find_samaccount(ADS_STRUCT *ads,
    4480             :                                TALLOC_CTX *mem_ctx,
    4481             :                                const char *samaccountname,
    4482             :                                uint32_t *uac_ret,
    4483             :                                const char **dn_ret)
    4484             : {
    4485           0 :         ADS_STATUS status;
    4486           0 :         const char *attrs[] = { "userAccountControl", NULL };
    4487           0 :         const char *filter;
    4488           0 :         LDAPMessage *res = NULL;
    4489           0 :         char *dn = NULL;
    4490           0 :         uint32_t uac = 0;
    4491             : 
    4492           0 :         filter = talloc_asprintf(mem_ctx, "(&(objectclass=user)(sAMAccountName=%s))",
    4493             :                 samaccountname);
    4494           0 :         if (filter == NULL) {
    4495           0 :                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
    4496           0 :                 goto out;
    4497             :         }
    4498             : 
    4499           0 :         status = ads_do_search_all(ads, ads->config.bind_path,
    4500             :                                    LDAP_SCOPE_SUBTREE,
    4501             :                                    filter, attrs, &res);
    4502             : 
    4503           0 :         if (!ADS_ERR_OK(status)) {
    4504           0 :                 goto out;
    4505             :         }
    4506             : 
    4507           0 :         if (ads_count_replies(ads, res) != 1) {
    4508           0 :                 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
    4509           0 :                 goto out;
    4510             :         }
    4511             : 
    4512           0 :         dn = ads_get_dn(ads, talloc_tos(), res);
    4513           0 :         if (dn == NULL) {
    4514           0 :                 status = ADS_ERROR(LDAP_NO_MEMORY);
    4515           0 :                 goto out;
    4516             :         }
    4517             : 
    4518           0 :         if (!ads_pull_uint32(ads, res, "userAccountControl", &uac)) {
    4519           0 :                 status = ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
    4520           0 :                 goto out;
    4521             :         }
    4522             : 
    4523           0 :         if (uac_ret) {
    4524           0 :                 *uac_ret = uac;
    4525             :         }
    4526             : 
    4527           0 :         if (dn_ret) {
    4528           0 :                 *dn_ret = talloc_strdup(mem_ctx, dn);
    4529           0 :                 if (!*dn_ret) {
    4530           0 :                         status = ADS_ERROR(LDAP_NO_MEMORY);
    4531           0 :                         goto out;
    4532             :                 }
    4533             :         }
    4534           0 :  out:
    4535           0 :         TALLOC_FREE(dn);
    4536           0 :         ads_msgfree(ads, res);
    4537             : 
    4538           0 :         return status;
    4539             : }
    4540             : 
    4541             : /**
    4542             :  * find our configuration path
    4543             :  * @param ads connection to ads server
    4544             :  * @param mem_ctx Pointer to talloc context
    4545             :  * @param config_path Pointer to the config path
    4546             :  * @return status of search
    4547             :  **/
    4548           0 : ADS_STATUS ads_config_path(ADS_STRUCT *ads,
    4549             :                            TALLOC_CTX *mem_ctx,
    4550             :                            char **config_path)
    4551             : {
    4552           0 :         ADS_STATUS status;
    4553           0 :         LDAPMessage *res = NULL;
    4554           0 :         const char *config_context = NULL;
    4555           0 :         const char *attrs[] = { "configurationNamingContext", NULL };
    4556             : 
    4557           0 :         status = ads_do_search(ads, "", LDAP_SCOPE_BASE,
    4558             :                                "(objectclass=*)", attrs, &res);
    4559           0 :         if (!ADS_ERR_OK(status)) {
    4560           0 :                 return status;
    4561             :         }
    4562             : 
    4563           0 :         config_context = ads_pull_string(ads, mem_ctx, res,
    4564             :                                          "configurationNamingContext");
    4565           0 :         ads_msgfree(ads, res);
    4566           0 :         if (!config_context) {
    4567           0 :                 return ADS_ERROR(LDAP_NO_MEMORY);
    4568             :         }
    4569             : 
    4570           0 :         if (config_path) {
    4571           0 :                 *config_path = talloc_strdup(mem_ctx, config_context);
    4572           0 :                 if (!*config_path) {
    4573           0 :                         return ADS_ERROR(LDAP_NO_MEMORY);
    4574             :                 }
    4575             :         }
    4576             : 
    4577           0 :         return ADS_ERROR(LDAP_SUCCESS);
    4578             : }
    4579             : 
    4580             : /**
    4581             :  * find the displayName of an extended right
    4582             :  * @param ads connection to ads server
    4583             :  * @param config_path The config path
    4584             :  * @param mem_ctx Pointer to talloc context
    4585             :  * @param GUID struct of the rightsGUID
    4586             :  * @return status of search
    4587             :  **/
    4588           0 : const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
    4589             :                                                 const char *config_path,
    4590             :                                                 TALLOC_CTX *mem_ctx,
    4591             :                                                 const struct GUID *rights_guid)
    4592             : {
    4593           0 :         ADS_STATUS rc;
    4594           0 :         LDAPMessage *res = NULL;
    4595           0 :         char *expr = NULL;
    4596           0 :         const char *attrs[] = { "displayName", NULL };
    4597           0 :         const char *result = NULL;
    4598           0 :         const char *path;
    4599             : 
    4600           0 :         if (!ads || !mem_ctx || !rights_guid) {
    4601           0 :                 goto done;
    4602             :         }
    4603             : 
    4604           0 :         expr = talloc_asprintf(mem_ctx, "(rightsGuid=%s)",
    4605             :                                GUID_string(mem_ctx, rights_guid));
    4606           0 :         if (!expr) {
    4607           0 :                 goto done;
    4608             :         }
    4609             : 
    4610           0 :         path = talloc_asprintf(mem_ctx, "cn=Extended-Rights,%s", config_path);
    4611           0 :         if (!path) {
    4612           0 :                 goto done;
    4613             :         }
    4614             : 
    4615           0 :         rc = ads_do_search_retry(ads, path, LDAP_SCOPE_SUBTREE,
    4616             :                                  expr, attrs, &res);
    4617           0 :         if (!ADS_ERR_OK(rc)) {
    4618           0 :                 goto done;
    4619             :         }
    4620             : 
    4621           0 :         if (ads_count_replies(ads, res) != 1) {
    4622           0 :                 goto done;
    4623             :         }
    4624             : 
    4625           0 :         result = ads_pull_string(ads, mem_ctx, res, "displayName");
    4626             : 
    4627           0 :  done:
    4628           0 :         ads_msgfree(ads, res);
    4629           0 :         return result;
    4630             : }
    4631             : 
    4632             : /**
    4633             :  * verify or build and verify an account ou
    4634             :  * @param mem_ctx Pointer to talloc context
    4635             :  * @param ads connection to ads server
    4636             :  * @param account_ou
    4637             :  * @return status of search
    4638             :  **/
    4639             : 
    4640          60 : ADS_STATUS ads_check_ou_dn(TALLOC_CTX *mem_ctx,
    4641             :                            ADS_STRUCT *ads,
    4642             :                            const char **account_ou)
    4643             : {
    4644           0 :         char **exploded_dn;
    4645           0 :         const char *name;
    4646           0 :         char *ou_string;
    4647             : 
    4648          60 :         if (account_ou == NULL) {
    4649           0 :                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
    4650             :         }
    4651             : 
    4652          60 :         if (*account_ou != NULL) {
    4653           2 :                 exploded_dn = ldap_explode_dn(*account_ou, 0);
    4654           2 :                 if (exploded_dn) {
    4655           0 :                         ldap_value_free(exploded_dn);
    4656           0 :                         return ADS_SUCCESS;
    4657             :                 }
    4658             :         }
    4659             : 
    4660          60 :         ou_string = ads_ou_string(ads, *account_ou);
    4661          60 :         if (!ou_string) {
    4662           0 :                 return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
    4663             :         }
    4664             : 
    4665          60 :         name = talloc_asprintf(mem_ctx, "%s,%s", ou_string,
    4666             :                                ads->config.bind_path);
    4667          60 :         SAFE_FREE(ou_string);
    4668             : 
    4669          60 :         if (!name) {
    4670           0 :                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
    4671             :         }
    4672             : 
    4673          60 :         exploded_dn = ldap_explode_dn(name, 0);
    4674          60 :         if (!exploded_dn) {
    4675           0 :                 return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
    4676             :         }
    4677          60 :         ldap_value_free(exploded_dn);
    4678             : 
    4679          60 :         *account_ou = name;
    4680          60 :         return ADS_SUCCESS;
    4681             : }
    4682             : 
    4683             : #endif

Generated by: LCOV version 1.14