Exemplo n.º 1
0
def __reserve_user_db(user, password):
    encrypted_password = CFG.encrypted_passwords
    log_debug(3, user, CFG.disallow_user_creation, encrypted_password, CFG.pam_auth_service)
    user = str(user)
    h = rhnSQL.prepare("""
    select w.id, w.password, w.old_password, w.org_id, ui.use_pam_authentication
    from web_contact w, rhnUserInfo ui
    where w.login_uc = upper(:p1)
    and w.id = ui.user_id
    """)
    h.execute(p1=user)
    data = h.fetchone_dict()
    if data and data["id"]:
        # contact exists, check password
        if data['use_pam_authentication'] == 'Y' and CFG.pam_auth_service:
            # We use PAM for authentication
            import rhnAuthPAM
            if rhnAuthPAM.check_password(user, password, CFG.pam_auth_service) > 0:
                return 1
            return -1

        if check_password(password, data['password'], data['old_password']) > 0:
            return 1
        return -1

    # user doesn't exist.  now we fail, instead of reserving user.
    if CFG.disallow_user_creation:
        raise rhnFault(2001)

    # now check the reserved table
    h = rhnSQL.prepare("""
    select r.login, r.password from rhnUserReserved r
    where r.login_uc = upper(:p1)
    """)
    h.execute(p1=user)
    data = h.fetchone_dict()   
    if data and data["login"]:
        # found already reserved
        if check_password(password, data["password"], None) > 0: 
            return 1
        return -2

    validate_new_username(user)
    log_debug(3, "calling validate_new_password" )
    validate_new_password(password)

    # this is not reserved either, register it
    if encrypted_password:
        # Encrypt the password, let the function pick the salt
        password = encrypt_password(password)

    h = rhnSQL.prepare("""
    insert into rhnUserReserved (login, password)
    values (:username, :password)
    """)
    h.execute(username=user, password=password)
    rhnSQL.commit()
    
    # all should be dandy
    return 0
Exemplo n.º 2
0
    def save(self):
        expires = int(time.time()) + self.duration

        h = rhnSQL.prepare("""
                insert into PXTSessions (id, web_user_id, expires, value)
                values (:id, :web_user_id, :expires, :value)
        """)
        h.execute(id=self.session_id, web_user_id=self.uid,
                  expires=expires, value='RHNAPP')
        rhnSQL.commit()
        return self
Exemplo n.º 3
0
    def save(self):
        expires = int(time.time()) + self.duration

        h = rhnSQL.prepare("""
                insert into PXTSessions (id, web_user_id, expires, value)
                values (:id, :web_user_id, :expires, :value)
        """)
        h.execute(id=self.session_id, web_user_id=self.uid,
                  expires=expires, value='RHNAPP')
        rhnSQL.commit()
        return self
Exemplo n.º 4
0
 def save(self):
     log_debug(3, self.username)
     rhnSQL.commit()
     try:
         self.__save()
     except:            
         rhnSQL.rollback()
         # shoot the exception up the chain
         raise
     else:
         rhnSQL.commit()
     return 0
Exemplo n.º 5
0
    def load(self, session):
        arr = string.split(session, "x", 1)
        if len(arr) != 2:
            raise InvalidSessionError("Invalid session string")

        digest = arr[1]
        if len(digest) != 64:
            raise InvalidSessionError("Invalid session string (wrong length)")

        try:
            self.session_id = int(arr[0])
        except ValueError:
            raise_with_tb(InvalidSessionError("Invalid session identifier"), sys.exc_info()[2])

        if digest != self.digest():
            raise InvalidSessionError("Bad session checksum")

        h = rhnSQL.prepare(
            """
            select web_user_id, expires, value
              from pxtSessions
             where id = :session_id
        """
        )
        h.execute(session_id=self.session_id)

        row = h.fetchone_dict()
        if row:
            # Session is stored in the DB
            if time.time() < row["expires"]:
                # And it's not expired yet - good to go
                self.expires = row["expires"]
                self.uid = row["web_user_id"]
                return self

            # Old session - clean it up
            h = rhnSQL.prepare(
                """
                    delete from pxtSessions where id = :session_id
            """
            )
            h.execute(session_id=self.session_id)
            rhnSQL.commit()

        raise ExpiredSessionError("Session not found")
Exemplo n.º 6
0
    def load(self, session):
        arr = string.split(session, 'x', 1)
        if len(arr) != 2:
            raise InvalidSessionError("Invalid session string")

        digest = arr[1]
        if len(digest) != 64:
            raise InvalidSessionError("Invalid session string (wrong length)")

        try:
            self.session_id = int(arr[0])
        except ValueError:
            raise_with_tb(InvalidSessionError("Invalid session identifier"),
                          sys.exc_info()[2])

        if digest != self.digest():
            raise InvalidSessionError("Bad session checksum")

        h = rhnSQL.prepare("""
            select web_user_id, expires, value
              from pxtSessions
             where id = :session_id
        """)
        h.execute(session_id=self.session_id)

        row = h.fetchone_dict()
        if row:
            # Session is stored in the DB
            if time.time() < row['expires']:
                # And it's not expired yet - good to go
                self.expires = row['expires']
                self.uid = row['web_user_id']
                return self

            # Old session - clean it up
            h = rhnSQL.prepare("""
                    delete from pxtSessions where id = :session_id
            """)
            h.execute(session_id=self.session_id)
            rhnSQL.commit()

        raise ExpiredSessionError("Session not found")
Exemplo n.º 7
0
 def check_password(self, password, allow_read_only=False):
     """ simple check for a password that might become more complex sometime """
     if not allow_read_only and is_user_read_only(self.contact["login"]):
         raise rhnFault(702)
     good_pwd = str(self.contact["password"])
     if CFG.pam_auth_service:
         # a PAM service is defined
         # We have to check the user's rhnUserInfo.use_pam_authentication
         # XXX Should we create yet another __init_blah function?
         # since it's the first time we had to lool at rhnUserInfo,
         # I'll assume it's not something to happen very frequently,
         # so I'll use a query for now
         # - misa
         #
         h = rhnSQL.prepare("""
             select ui.use_pam_authentication
             from web_contact w, rhnUserInfo ui
             where w.login_uc = UPPER(:login)
             and w.id = ui.user_id""")
         h.execute(login=self.contact["login"])
         data = h.fetchone_dict()
         if not data:
             # This should not happen
             raise rhnException("No entry found for user %s" %
                                self.contact["login"])
         if data['use_pam_authentication'] == 'Y':
             # use PAM
             import rhnAuthPAM
             return rhnAuthPAM.check_password(self.contact["login"],
                                              password,
                                              CFG.pam_auth_service)
     # If the entry in rhnUserInfo is 'N', perform regular authentication
     ret = check_password(password, good_pwd)
     if ret and CFG.encrypted_passwords and self.contact['password'].find(
             '$1$') == 0:
         # If successfully authenticated and the current password is
         # MD5 encoded, convert the password to SHA-256 and save it in the DB.
         self.contact['password'] = encrypt_password(password)
         self.contact.save()
         rhnSQL.commit()
     return ret
Exemplo n.º 8
0
    def check_password(self, password, allow_read_only=False):
        """ simple check for a password that might become more complex sometime """
        if not allow_read_only and is_user_read_only(self.contact["login"]):
            raise rhnFault(702)
        good_pwd = str(self.contact["password"])
        if CFG.pam_auth_service:
            # a PAM service is defined
            # We have to check the user's rhnUserInfo.use_pam_authentication
            # XXX Should we create yet another __init_blah function?
            # since it's the first time we had to lool at rhnUserInfo,
            # I'll assume it's not something to happen very frequently,
            # so I'll use a query for now
            # - misa
            #
            h = rhnSQL.prepare(
                """
                select ui.use_pam_authentication
                from web_contact w, rhnUserInfo ui
                where w.login_uc = UPPER(:login)
                and w.id = ui.user_id"""
            )
            h.execute(login=self.contact["login"])
            data = h.fetchone_dict()
            if not data:
                # This should not happen
                raise rhnException("No entry found for user %s" % self.contact["login"])
            if data["use_pam_authentication"] == "Y":
                # use PAM
                import rhnAuthPAM

                return rhnAuthPAM.check_password(self.contact["login"], password, CFG.pam_auth_service)
        # If the entry in rhnUserInfo is 'N', perform regular authentication
        ret = check_password(password, good_pwd)
        if ret and CFG.encrypted_passwords and self.contact["password"].find("$1$") == 0:
            # If successfully authenticated and the current password is
            # MD5 encoded, convert the password to SHA-256 and save it in the DB.
            self.contact["password"] = encrypt_password(password)
            self.contact.save()
            rhnSQL.commit()
        return ret
Exemplo n.º 9
0
def __reserve_user_db(user, password):
    encrypted_password = CFG.encrypted_passwords
    log_debug(3, user, CFG.disallow_user_creation, encrypted_password,
              CFG.pam_auth_service)
    user = str(user)
    h = rhnSQL.prepare("""
    select w.id, w.password, w.org_id, ui.use_pam_authentication
    from web_contact w, rhnUserInfo ui
    where w.login_uc = upper(:p1)
    and w.id = ui.user_id
    """)
    h.execute(p1=user)
    data = h.fetchone_dict()
    if data and data["id"]:
        # contact exists, check password
        if data['use_pam_authentication'] == 'Y' and CFG.pam_auth_service:
            # We use PAM for authentication
            import rhnAuthPAM
            if rhnAuthPAM.check_password(user, password,
                                         CFG.pam_auth_service) > 0:
                return 1
            return -1

        if check_password(password, data['password']) > 0:
            return 1
        return -1

    # user doesn't exist.  now we fail, instead of reserving user.
    if CFG.disallow_user_creation:
        raise rhnFault(2001)
    user, password = check_user_password(user, password)

    # now check the reserved table
    h = rhnSQL.prepare("""
    select r.login, r.password from rhnUserReserved r
    where r.login_uc = upper(:p1)
    """)
    h.execute(p1=user)
    data = h.fetchone_dict()
    if data and data["login"]:
        # found already reserved
        if check_password(password, data["password"]) > 0:
            return 1
        return -2

    validate_new_username(user)
    log_debug(3, "calling validate_new_password")
    validate_new_password(password)

    # this is not reserved either, register it
    if encrypted_password:
        # Encrypt the password, let the function pick the salt
        password = encrypt_password(password)

    h = rhnSQL.prepare("""
    insert into rhnUserReserved (login, password)
    values (:username, :password)
    """)
    h.execute(username=user, password=password)
    rhnSQL.commit()

    # all should be dandy
    return 0
Exemplo n.º 10
0
def update_client_capabilities(server_id):
    caps = get_client_capabilities()

    if caps is None:
        caps = {}

    caps = caps.copy()

    h = rhnSQL.prepare(
        """
        select cc.capability_name_id, ccn.name capability, cc.version
        from rhnClientCapability cc, rhnClientCapabilityName ccn
        where cc.server_id = :server_id
        and cc.capability_name_id = ccn.id
    """
    )

    updates = {"server_id": [], "capability_name_id": [], "version": []}
    deletes = {"server_id": [], "capability_name_id": []}
    inserts = {"server_id": [], "capability": [], "version": []}

    h.execute(server_id=server_id)
    while 1:
        row = h.fetchone_dict()
        if not row:
            break

        name = row["capability"]
        version = row["version"]
        capability_name_id = row["capability_name_id"]

        if caps.has_key(name):
            local_ver = caps[name]["version"]
            del caps[name]
            if local_ver == version:
                # Nothing to do - same version
                continue

            updates["server_id"].append(server_id)
            updates["capability_name_id"].append(capability_name_id)
            updates["version"].append(local_ver)
            continue

        # Have to delete it
        deletes["server_id"].append(server_id)
        deletes["capability_name_id"].append(capability_name_id)

    # Everything else has to be inserted
    for name, hash in caps.items():
        inserts["server_id"].append(server_id)
        inserts["capability"].append(name)
        inserts["version"].append(hash["version"])

    log_debug(5, "Deletes:", deletes)
    log_debug(5, "Updates:", updates)
    log_debug(5, "Inserts:", inserts)

    if deletes["server_id"]:
        h = rhnSQL.prepare(
            """
            delete from rhnClientCapability
            where server_id = :server_id
            and capability_name_id = :capability_name_id
        """
        )
        h.executemany(**deletes)

    if updates["server_id"]:
        h = rhnSQL.prepare(
            """
            update rhnClientCapability
            set version = :version
            where server_id = :server_id
            and capability_name_id = :capability_name_id
        """
        )
        h.executemany(**updates)

    if inserts["server_id"]:
        h = rhnSQL.prepare(
            """
            insert into rhnClientCapability
            (server_id, capability_name_id, version)
            values (:server_id, LOOKUP_CLIENT_CAPABILITY(:capability), :version)
        """
        )
        h.executemany(**inserts)

    # Commit work. This can be dangerous if there is previously uncommited
    # work
    rhnSQL.commit()
Exemplo n.º 11
0
def update_client_capabilities(server_id):
    caps = get_client_capabilities()

    if caps is None:
        caps = {}

    caps = caps.copy()

    h = rhnSQL.prepare("""
        select cc.capability_name_id, ccn.name capability, cc.version
        from rhnClientCapability cc, rhnClientCapabilityName ccn
        where cc.server_id = :server_id
        and cc.capability_name_id = ccn.id
    """)

    updates = {'server_id': [], 'capability_name_id': [], 'version': []}
    deletes = {'server_id': [], 'capability_name_id': []}
    inserts = {'server_id': [], 'capability': [], 'version': []}

    h.execute(server_id=server_id)
    while 1:
        row = h.fetchone_dict()
        if not row:
            break

        name = row['capability']
        version = row['version']
        capability_name_id = row['capability_name_id']

        if name in caps:
            local_ver = caps[name]['version']
            del caps[name]
            if local_ver == version:
                # Nothing to do - same version
                continue

            updates['server_id'].append(server_id)
            updates['capability_name_id'].append(capability_name_id)
            updates['version'].append(local_ver)
            continue

        # Have to delete it
        deletes['server_id'].append(server_id)
        deletes['capability_name_id'].append(capability_name_id)

    # Everything else has to be inserted
    for name, hash in caps.items():
        inserts['server_id'].append(server_id)
        inserts['capability'].append(name)
        inserts['version'].append(hash['version'])

    log_debug(5, "Deletes:", deletes)
    log_debug(5, "Updates:", updates)
    log_debug(5, "Inserts:", inserts)

    if deletes['server_id']:
        h = rhnSQL.prepare("""
            delete from rhnClientCapability
            where server_id = :server_id
            and capability_name_id = :capability_name_id
        """)
        h.executemany(**deletes)

    if updates['server_id']:
        h = rhnSQL.prepare("""
            update rhnClientCapability
            set version = :version
            where server_id = :server_id
            and capability_name_id = :capability_name_id
        """)
        h.executemany(**updates)

    if inserts['server_id']:
        h = rhnSQL.prepare("""
            insert into rhnClientCapability
            (server_id, capability_name_id, version)
            values (:server_id, LOOKUP_CLIENT_CAPABILITY(:capability), :version)
        """)
        h.executemany(**inserts)

    # Commit work. This can be dangerous if there is previously uncommited
    # work
    rhnSQL.commit()