summaryrefslogtreecommitdiffstats
path: root/src/tests/sysdb_ssh-tests.c
diff options
context:
space:
mode:
authorJakub Hrozek <jhrozek@redhat.com>2013-06-07 07:19:27 +0200
committerJakub Hrozek <jhrozek@redhat.com>2013-06-10 11:31:20 +0200
commit265ce7e9fcd9aeaaac1a36c4446072f57f3bd0c2 (patch)
tree4e1512ef0917dc22963596d330a710f70a9f4e69 /src/tests/sysdb_ssh-tests.c
parentfbd63f8f920a2591310d601b01c7b79aa4023a95 (diff)
dyndns: Fix NULL check
Diffstat (limited to 'src/tests/sysdb_ssh-tests.c')
0 files changed, 0 insertions, 0 deletions
104' href='#n104'>104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
#! /usr/bin/python -E
# Authors: Rich Megginson <richm@redhat.com>
#          Rob Crittenden <rcritten@redhat.com
#
# Copyright (C) 2007  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 or later
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

import sys
import os
import os.path
import popen2
import base64
import urllib
import urllib2
import socket
import ldif
import re
import string
import ldap
import cStringIO
import time
import operator
import struct
import ldap.sasl
from ldap.controls import LDAPControl,DecodeControlTuples,EncodeControlTuples
from ldap.ldapobject import SimpleLDAPObject
from ipa import ipaerror, ipautil

# Global variable to define SASL auth
sasl_auth = ldap.sasl.sasl({},'GSSAPI')

class Entry:
    """This class represents an LDAP Entry object.  An LDAP entry consists of a DN
    and a list of attributes.  Each attribute consists of a name and a list of
    values.  In python-ldap, entries are returned as a list of 2-tuples.
    Instance variables:
    dn - string - the string DN of the entry
    data - CIDict - case insensitive dict of the attributes and values"""

    def __init__(self,entrydata):
        """data is the raw data returned from the python-ldap result method, which is
        a search result entry or a reference or None.
        If creating a new empty entry, data is the string DN."""
        if entrydata:
            if isinstance(entrydata,tuple):
                self.dn = entrydata[0]
                self.data = ipautil.CIDict(entrydata[1])
            elif isinstance(entrydata,str) or isinstance(entrydata,unicode):
                self.dn = entrydata
                self.data = ipautil.CIDict()
        else:
            self.dn = ''
            self.data = ipautil.CIDict()

    def __nonzero__(self):
        """This allows us to do tests like if entry: returns false if there is no data,
        true otherwise"""
        return self.data != None and len(self.data) > 0

    def hasAttr(self,name):
        """Return True if this entry has an attribute named name, False otherwise"""
        return self.data and self.data.has_key(name)

    def __getattr__(self,name):
        """If name is the name of an LDAP attribute, return the first value for that
        attribute - equivalent to getValue - this allows the use of
        entry.cn
        instead of
        entry.getValue('cn')
        This also allows us to return None if an attribute is not found rather than
        throwing an exception"""
        return self.getValue(name)

    def getValues(self,name):
        """Get the list (array) of values for the attribute named name"""
        return self.data.get(name)

    def getValue(self,name):
        """Get the first value for the attribute named name"""
        return self.data.get(name,[None])[0]

    def setValue(self,name,*value):
        """Value passed in may be a single value, several values, or a single sequence.
        For example:
           ent.setValue('name', 'value')
           ent.setValue('name', 'value1', 'value2', ..., 'valueN')
           ent.setValue('name', ['value1', 'value2', ..., 'valueN'])
           ent.setValue('name', ('value1', 'value2', ..., 'valueN'))
        Since *value is a tuple, we may have to extract a list or tuple from that
        tuple as in the last two examples above"""
        if isinstance(value[0],list) or isinstance(value[0],tuple):
            self.data[name] = value[0]
        else:
            self.data[name] = value

    setValues = setValue

    def toTupleList(self):
        """Convert the attrs and values to a list of 2-tuples.  The first element
        of the tuple is the attribute name.  The second element is either a
        single value or a list of values."""
        return self.data.items()

    def __str__(self):
        """Convert the Entry to its LDIF representation"""
        return self.__repr__()

    # the ldif class base64 encodes some attrs which I would rather see in raw form - to
    # encode specific attrs as base64, add them to the list below
    ldif.safe_string_re = re.compile('^$')
    base64_attrs = ['nsstate', 'krbprincipalkey', 'krbExtraData']

    def __repr__(self):
        """Convert the Entry to its LDIF representation"""
        sio = cStringIO.StringIO()
        # what's all this then?  the unparse method will currently only accept
        # a list or a dict, not a class derived from them.  self.data is a
        # cidict, so unparse barfs on it.  I've filed a bug against python-ldap,
        # but in the meantime, we have to convert to a plain old dict for printing
        # I also don't want to see wrapping, so set the line width really high (1000)
        newdata = {}
        newdata.update(self.data)
        ldif.LDIFWriter(sio,Entry.base64_attrs,1000).unparse(self.dn,newdata)
        return sio.getvalue()

def wrapper(f,name):
    """This is the method that wraps all of the methods of the superclass.  This seems
    to need to be an unbound method, that's why it's outside of IPAdmin.  Perhaps there
    is some way to do this with the new classmethod or staticmethod of 2.4.
    Basically, we replace every call to a method in SimpleLDAPObject (the superclass
    of IPAdmin) with a call to inner.  The f argument to wrapper is the bound method
    of IPAdmin (which is inherited from the superclass).  Bound means that it will implicitly
    be called with the self argument, it is not in the args list.  name is the name of
    the method to call.  If name is a method that returns entry objects (e.g. result),
    we wrap the data returned by an Entry class.  If name is a method that takes an entry
    argument, we extract the raw data from the entry object to pass in."""
    def inner(*args, **kargs):
        if name == 'result':
            type, data = f(*args, **kargs)
            # data is either a 2-tuple or a list of 2-tuples
            # print data
            if data:
                if isinstance(data,tuple):
                    return type, Entry(data)
                elif isinstance(data,list):
                    return type, [Entry(x) for x in data]
                else:
                    raise TypeError, "unknown data type %s returned by result" % type(data)
            else:
                return type, data
        elif name.startswith('add'):
            # the first arg is self
            # the second and third arg are the dn and the data to send
            # We need to convert the Entry into the format used by
            # python-ldap
            ent = args[0]
            if isinstance(ent,Entry):
                return f(ent.dn, ent.toTupleList(), *args[2:])
            else:
                return f(*args, **kargs)
        else:
            return f(*args, **kargs)
    return inner

class IPAdmin(SimpleLDAPObject):
    CFGSUFFIX = "o=NetscapeRoot"
    DEFAULT_USER_ID = "nobody"
    
    def __initPart2(self):
        if self.binddn and len(self.binddn) and not hasattr(self,'sroot'):
            try:
                ent = self.getEntry('cn=config', ldap.SCOPE_BASE, '(objectclass=*)',
                                    [ 'nsslapd-instancedir', 'nsslapd-errorlog' ])
                instdir = ent.getValue('nsslapd-instancedir')
                self.sroot, self.inst = re.match(r'(.*)[\/]slapd-(\w+)$', instdir).groups()
                self.errlog = ent.getValue('nsslapd-errorlog')
            except (ldap.INSUFFICIENT_ACCESS, ldap.CONNECT_ERROR,
                    ipaerror.exception_for(ipaerror.LDAP_NOT_FOUND)):
                pass # usually means 
#                print "ignored exception"
            except ldap.LDAPError, e:
                print "caught exception ", e
                raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)

    def __localinit__(self):
        """If a CA certificate is provided then it is assumed that we are
           doing SSL client authentication with proxy auth.

           If a CA certificate is not present then it is assumed that we are
           using a forwarded kerberos ticket for SASL auth. SASL provides
           its own encryption.
        """
        if self.cacert is not None:
            SimpleLDAPObject.__init__(self,'ldaps://%s:%d' % (self.host,self.port))
        else:
            SimpleLDAPObject.__init__(self,'ldap://%s:%d' % (self.host,self.port))

    def __init__(self,host,port,cacert,bindcert,bindkey,proxydn=None):
        """We just set our instance variables and wrap the methods - the real
           work is done in __localinit__ and __initPart2 - these are separated
           out this way so that we can call them from places other than
           instance creation e.g. when we just need to reconnect, not create a
           new instance"""
#        ldap.set_option(ldap.OPT_DEBUG_LEVEL,255)
        if cacert is not None:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,cacert)
            ldap.set_option(ldap.OPT_X_TLS_CERTFILE,bindcert)
            ldap.set_option(ldap.OPT_X_TLS_KEYFILE,bindkey)

        self.__wrapmethods()
        self.port = port or 389
        self.host = host
        self.cacert = cacert
        self.bindcert = bindcert
        self.bindkey = bindkey
        self.proxydn = proxydn
        # see if is local or not
        host1 = IPAdmin.getfqdn(host)
        host2 = IPAdmin.getfqdn()
        self.isLocal = (host1 == host2)
        self.suffixes = {}
        self.__localinit__()

    def __str__(self):
        return self.host + ":" + str(self.port)

    def __get_server_controls__(self):
        """Create the proxy user server control. The control has the form
        0x04 = Octet String
        4|0x80 sets the length of the string length field at 4 bytes
        the struct() gets us the length in bytes of string self.proxydn
        self.proxydn is the proxy dn to send"""

        import sys

        if self.proxydn is not None:
            proxydn = chr(0x04) + chr(4|0x80) + struct.pack('l', socket.htonl(len(self.proxydn))) + self.proxydn;

            # Create the proxy control
            sctrl=[]
            sctrl.append(LDAPControl('2.16.840.1.113730.3.4.18',True,proxydn))
        else:
            sctrl=None

        return sctrl

    def toLDAPURL(self):
        return "ldap://%s:%d/" % (self.host,self.port)

    def set_proxydn(self, proxydn):
        self.proxydn = proxydn

    def set_keytab(self, keytab):
        if keytab is not None:
            os.environ["KRB5CCNAME"] = keytab
            self.sasl_interactive_bind_s("", sasl_auth)
        self.proxydn = None

    def getEntry(self,*args):
        """This wraps the search function.  It is common to just get one entry"""

        sctrl = self.__get_server_controls__()

        if sctrl is not None:
            self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)

        try:
            res = self.search(*args)
            type, obj = self.result(res)

    #        res = self.search_ext(args[0], args[1], filterstr=args[2], attrlist=args[3], serverctrls=sctrl)
        except ldap.LDAPError, e:
            raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)

        if not obj:
            raise ipaerror.gen_exception(ipaerror.LDAP_NOT_FOUND,
                    "no such entry for " + str(args))
        elif isinstance(obj,Entry):
            return obj
        else: # assume list/tuple
            return obj[0]

    def getList(self,*args):
        """This wraps the search function to find all users."""

        sctrl = self.__get_server_controls__()
        if sctrl is not None:
            self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)

        try:
            res = self.search(*args)
            type, obj = self.result(res)
        except (ldap.ADMINLIMIT_EXCEEDED, ldap.SIZELIMIT_EXCEEDED), e:
            raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR,
                    "Too many results returned by search", e)
        except ldap.LDAPError, e:
            raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)

        if not obj:
            raise ipaerror.gen_exception(ipaerror.LDAP_NOT_FOUND,
                    "no such entry for " + str(args))

        all_users = []
        for s in obj:
            all_users.append(s)

        return all_users

    def getListAsync(self,*args):
        """This version performs an asynchronous search, to allow
           results even if we hit a limit.

           It returns a list: counter followed by the results.
           If the results are truncated, counter will be set to -1.
           """

        sctrl = self.__get_server_controls__()
        if sctrl is not None:
            self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)

        entries = []
        partial = 0

        try:
            msgid = self.search_ext(*args)
            type, result_list = self.result(msgid, 0)
            while result_list:
                for result in result_list:
                    entries.append(result)
                type, result_list = self.result(msgid, 0)
        except (ldap.ADMINLIMIT_EXCEEDED, ldap.SIZELIMIT_EXCEEDED), e:
            partial = 1
        except ldap.LDAPError, e:
            raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)

        if not entries:
            raise ipaerror.gen_exception(ipaerror.LDAP_NOT_FOUND,
                    "no such entry for " + str(args))

        if partial == 1:
            counter = -1
        else:
            counter = len(entries)

        return [counter] + entries

    def addEntry(self,*args):
        """This wraps the add function. It assumes that the entry is already
           populated with all of the desired objectclasses and attributes"""

        sctrl = self.__get_server_controls__()

        try:
            if sctrl is not None:
                self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
            self.add_s(*args)
        except ldap.ALREADY_EXISTS:
            raise ipaerror.gen_exception(ipaerror.LDAP_DUPLICATE)
        except ldap.LDAPError, e:
            raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
        return "Success"

    def updateEntry(self,dn,olduser,newuser):
        """This wraps the mod function. It assumes that the entry is already
           populated with all of the desired objectclasses and attributes"""

        sctrl = self.__get_server_controls__()

        modlist = self.generateModList(olduser, newuser)

        if len(modlist) == 0:
            raise ipaerror.gen_exception(ipaerror.LDAP_EMPTY_MODLIST)

        try:
            if sctrl is not None:
                self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
            self.modify_s(dn, modlist)
        # this is raised when a 'delete' attribute isn't found.
        # it indicates the previous attribute was removed by another
        # update, making the olduser stale.
        except ldap.NO_SUCH_ATTRIBUTE:
            raise ipaerror.gen_exception(ipaerror.LDAP_MIDAIR_COLLISION)
        except ldap.LDAPError, e:
            raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
        return "Success"

    def generateModList(self, old_entry, new_entry):
        """A mod list generator that computes more precise modification lists
           than the python-ldap version.  This version purposely generates no
           REPLACE operations, to deal with multi-user updates more properly."""
        modlist = []

        old_entry = ipautil.CIDict(old_entry)
        new_entry = ipautil.CIDict(new_entry)

        keys = set(map(string.lower, old_entry.keys()))
        keys.update(map(string.lower, new_entry.keys()))

        for key in keys:
            new_values = new_entry.get(key, [])
            if not(isinstance(new_values,list) or isinstance(new_values,tuple)):
                new_values = [new_values]
            new_values = filter(lambda value:value!=None, new_values)
            new_values = set(new_values)

            old_values = old_entry.get(key, [])
            if not(isinstance(old_values,list) or isinstance(old_values,tuple)):
                old_values = [old_values]
            old_values = filter(lambda value:value!=None, old_values)
            old_values = set(old_values)

            adds = list(new_values.difference(old_values))
            removes = list(old_values.difference(new_values))

            if len(adds) > 0:
                modlist.append((ldap.MOD_ADD, key, adds))
            if len(removes) > 0:
                modlist.append((ldap.MOD_DELETE, key, removes))

        return modlist

    def inactivateEntry(self,dn,has_key):