ccs-pykerberos icon indicating copy to clipboard operation
ccs-pykerberos copied to clipboard

Memory leak in kerberos.authGSSServerStep()

Open JacobHenner opened this issue 9 months ago • 3 comments

There appears to be a memory leak in kerberos.authGSSServerStep(). I am able to reproduce it consistently by calling the following function in a tight loop:

def gssapi_authenticate(client_token: str):

    state = None
    try:
        rc, state = kerberos.authGSSServerInit("")
        if rc != kerberos.AUTH_GSS_COMPLETE:
            return None
        rc = kerberos.authGSSServerStep(state, client_token)
        if rc == kerberos.AUTH_GSS_COMPLETE:
            return dict(
                rc=rc,
                kerberos_token=kerberos.authGSSServerResponse(state),
                username=kerberos.authGSSServerUserName(state),
                servername=kerberos.authGSSServerTargetName(state),
            )
        elif rc == kerberos.AUTH_GSS_CONTINUE:
            return dict(rc=kerberos.AUTH_GSS_CONTINUE)
        else:
            return None
    except kerberos.GSSError:
        return None
    finally:
        if state:
            kerberos.authGSSServerClean(state)

After a few minutes memory usage goes from 30MiB to a few hundred MiB. This was identified in a web server using the library which would leak considerable amounts of memory over several days.

Environment:

kerberos (this library) version 1.3.11 RHEL 7, CentOS 7, and AmazonLinux 2 krb5-libs 1.15.1 Python 3.11

JacobHenner avatar Oct 04 '23 02:10 JacobHenner

I've isolated this to the following code block:

https://github.com/apple/ccs-pykerberos/blob/c05e4fd1dff58e2d966576e3e566c3fba5624387/src/kerberosgss.c#L773-L776

The memory leak happens even though gss_delete_sec_context(...) is called:

        maj_stat = gss_delete_sec_context(
            &min_stat, &state->context, GSS_C_NO_BUFFER
        );

Could this be this Kerberos issue from 2007? For comparison, I do not see a memory leak when I use python-gssapi for the same purpose (server-side Kerberos authentication over HTTP), even though IIUC that library also depends on MIT Kerberos's GSSAPI implementation.

JacobHenner avatar Dec 04 '23 02:12 JacobHenner

I've identified the issue and will open a pull request as soon as I'm authorized to do so.

JacobHenner avatar Dec 05 '23 03:12 JacobHenner

Opened #99 with fixes for two memory leaks in authenticate_gss_server_step.

JacobHenner avatar Dec 06 '23 18:12 JacobHenner