<commit_before>/* Written by <NAME> <<EMAIL>>.
 * Copyright (c) 2006-2014 Yubico AB
 * Copyright (c) 2011 <NAME> <<EMAIL>>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <syslog.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "util.h"
#include "drop_privs.h"

#include <ykclient.h>

#if HAVE_CR
/* for yubikey_hex_encode */
#include <yubikey.h>
/* for yubikey pbkdf2*/
#include <ykpbkdf2.h>
#endif /* HAVE_CR */

/* Libtool defines PIC for shared objects */
#ifndef PIC
#define PAM_STATIC
#endif

/* These #defines must be present according to PAM documentation. */
#define PAM_SM_AUTH

#ifdef HAVE_SECURITY_PAM_APPL_H
#include <security/pam_appl.h>
#endif
#ifdef HAVE_SECURITY_PAM_MODULES_H
#include <security/pam_modules.h>
#endif

#ifdef HAVE_LIBLDAP
/* Some functions like ldap_init, ldap_simple_bind_s, ldap_unbind are
   deprecated but still available. We will drop support for 'ldapserver'
   (in favour of 'ldap_uri' and update to using the new functions instead
   soon.
*/
#define LDAP_DEPRECATED 1

#include <ldap.h>
#define PORT_NUMBER  LDAP_PORT
#endif

#ifndef PAM_EXTERN
#ifdef PAM_STATIC
#define PAM_EXTERN static
#else
#define PAM_EXTERN extern
#endif
#endif

#define TOKEN_OTP_LEN 32u
#define MAX_TOKEN_ID_LEN 16u
#define DEFAULT_TOKEN_ID_LEN 12u

#define TMPFILE_SUFFIX ".XXXXXX"

enum key_mode {
  CHRESP,
  CLIENT
};

struct cfg
{
  unsigned int client_id;
  const char *client_key;
  int debug;
  int alwaysok;
  int verbose_otp;
  int try_first_pass;
  int use_first_pass;
  const char *auth_file;
  const char *capath;
  const char *cainfo;
  const char *proxy;
  const char *url;
  const char *urllist;
  const char *ldapserver;
  const char *ldap_uri;
  const char *ldap_bind_user;
  const char *ldap_bind_password;
  const char *ldap_filter;
  const char *ldap_cacertfile;
  const char *ldapdn;
  const char *user_attr;
  const char *yubi_attr;
  const char *yubi_attr_prefix;
  unsigned int token_id_length;
  enum key_mode mode;
  const char *chalresp_path;
};

#ifdef DBG
#undef DBG
#endif
#define DBG(x) if (cfg->debug) { D(x); }

/*
 * Authorize authenticated OTP_ID for login as USERNAME using
 * AUTHFILE.  Return -2 if the user is unknown, -1 if the OTP_ID does not match,  0 on internal failures, otherwise success.
 */
static int
authorize_user_token (struct cfg *cfg,
		      const char *username,
		      const char *otp_id,
		      pam_handle_t *pamh)
{
  int retval;

  if (cfg->auth_file)
    {
      /* Administrator had configured the file and specified is name
         as an argument for this module.
       */
      DBG (("Using system-wide auth_file %s", cfg->auth_file));
      retval = check_user_token (cfg->auth_file, username, otp_id, cfg->debug);
    }
  else
    {
      char *userfile = NULL;
      struct passwd *p;
      PAM_MODUTIL_DEF_PRIVS(privs);

#ifdef HAVE_PAM_MODUTIL_GETPWNAM
      p = pam_modutil_getpwnam (pamh, username);
#else
      p = getpwnam (username);
#endif
      if (p == NULL) {
	DBG (("getpwnam: %s", strerror(errno)));
	return 0;
      }

      /* Getting file from user home directory
         ..... i.e. ~/.yubico/authorized_yubikeys
       */
      if (! get_user_cfgfile_path (NULL, "authorized_yubikeys", p, &userfile)) {
	D (("Failed figuring out per-user cfgfile"));
	return 0;
      }

      DBG (("Dropping privileges"));
      if(pam_modutil_drop_priv(pamh, &privs, p)) {
        DBG (("could not drop privileges"));
	retval = 0;
	goto free_out;
      }

      retval = check_user_token (userfile, username, otp_id, cfg->debug);

      if(pam_modutil_regain_priv(pamh, &privs)) {
        DBG (("could not restore privileges"));
        retval = 0;
        goto free_out;
      }

free_out:
      free (userfile);
    }

  return retval;
}

/*
 * This function will look in ldap id the token correspond to the
 * requested user. It will returns 0 for failure and 1 for success.
 *
 * ldaps is only supported for ldap_uri based connections.
 * ldap_cacertfile usually needs to be set for this to work.
 *
 * ldap serve can be on a remote host.
 *
 * You need the following parameters in you pam config:
 * ldapserver=  OR ldap_uri=
 * ldapdn=
 * user_attr=
 * yubi_attr=
 *
 * If using ldap_uri, you can specify multiple failover hosts
 * eg.
 * ldap_uri=ldaps://host1.fqdn.example.com,ldaps://host2.fqdn.example.com
 */
static int
authorize_user_token_ldap (struct cfg *cfg,
			   const char *user,
			   const char *token_id)
{
  int retval = 0;
#ifdef HAVE_LIBLDAP
  /* LDAPv2 is historical -- RFC3494. */
  int protocol = LDAP_VERSION3;
  size_t yubi_attr_prefix_len = 0;
  LDAP *ld = NULL;
  LDAPMessage *result = NULL, *e;
  BerElement *ber;
  char *a;
  char *attrs[2] = {NULL, NULL};

  struct berval **vals;
  int rc;
  size_t i;

  char *filter = NULL;
  char *find = NULL;
  int scope = LDAP_SCOPE_BASE;
#endif
  DBG(("called"));
#ifdef HAVE_LIBLDAP
  if (cfg->yubi_attr == NULL) {
    DBG (("Trying to look up user to YubiKey mapping in LDAP, but yubi_attr not set!"));
    return 0;
  }
  if (cfg->user_attr && cfg->ldapdn == NULL) {
    DBG (("Trying to look up user to YubiKey mapping in LDAP, user_attr set but ldapdn not set!"));
    return 0;
  }

  /* Get a handle to an LDAP connection. */
  if (cfg->ldap_uri)
    {
      rc = ldap_initialize (&ld, cfg->ldap_uri);
      if (rc != LDAP_SUCCESS)
	{
	  DBG (("ldap_initialize: %s", ldap_err2string (rc)));
	  retval = 0;
	  goto done;
	}
    }
  else
    {
      if ((ld = ldap_init (cfg->ldapserver, PORT_NUMBER)) == NULL)
	{
	  DBG (("ldap_init"));
	  retval = 0;
	  goto done;
	}
    }

  ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
  ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &protocol);

  if (cfg->ldap_uri && cfg->ldap_cacertfile) {
    /* Set CA CERTFILE.  This makes ldaps work when using ldap_uri */
    ldap_set_option (0, LDAP_OPT_X_TLS_CACERTFILE, cfg->ldap_cacertfile);
  }
  /* Bind anonymously to the LDAP server. */
  if (cfg->ldap_bind_user && cfg->ldap_bind_password) {
    DBG (("try bind with: %s:[%s]", cfg->ldap_bind_user, cfg->ldap_bind_password));
    rc = ldap_simple_bind_s (ld, cfg->ldap_bind_user, cfg->ldap_bind_password);
  } else {
    DBG (("try bind anonymous"));
    rc = ldap_simple_bind_s (ld, NULL, NULL);
  }
  if (rc != LDAP_SUCCESS)
    {
      DBG (("ldap_simple_bind_s: %s", ldap_err2string (rc)));
      retval = 0;
      goto done;
    }

  /* Allocation of memory for search strings depending on input size */
  if (cfg->user_attr && cfg->yubi_attr && cfg->ldapdn) {
    i = (strlen(cfg->user_attr) + strlen(cfg->ldapdn) + strlen(user) + 3) * sizeof(char);
    if ((find = malloc(i)) == NULL) {
      DBG (("Failed allocating %zu bytes", i));
      retval = 0;
      goto done;
    }
    sprintf (find, "%s=%s,%s", cfg->user_attr, user, cfg->ldapdn);
    filter = NULL;
  } else if (cfg->ldapdn) {
    find = strdup(cfg->ldapdn); /* allow free later */
  }
  if (cfg->ldap_filter) {
    filter = filter_printf(cfg->ldap_filter, user);
    scope = LDAP_SCOPE_SUBTREE;
  }
  attrs[0] = (char *) cfg->yubi_attr;

  DBG(("LDAP : look up object base='%s' filter='%s', ask for attribute '%s'", find,
      filter ? filter:"(null)", cfg->yubi_attr));

  /* Search for the entry. */
  if ((rc = ldap_search_ext_s (ld, find, scope,
			       filter, attrs, 0, NULL, NULL, LDAP_NO_LIMIT,
			       LDAP_NO_LIMIT, &result)) != LDAP_SUCCESS)
    {
      DBG (("ldap_search_ext_s: %s", ldap_err2string (rc)));

      retval = 0;
      goto done;
    }

  e = ldap_first_entry (ld, result);
  if (e == NULL)
    {
      DBG (("No result from LDAP search"));
      retval = -2;
    }
  else
    {
      retval = -1;
      /* Iterate through each returned attribute. */
      for (a = ldap_first_attribute (ld, e, &ber);
	   a != NULL; a = ldap_next_attribute (ld, e, ber))
	{
	  if ((vals = ldap_get_values_len (ld, e, a)) != NULL)
	    {
	      yubi_attr_prefix_len = cfg->yubi_attr_prefix ? strlen(cfg->yubi_attr_prefix) : 0;

	      /* Compare each value for the attribute against the token id. */
	      for (i = 0; vals[i] != NULL; i++)
		{
	          DBG(("LDAP : Found %i values - checking if any of them match '%s:%s:%s'",
		       ldap_count_values_len(vals),
		       vals[i]->bv_val,
		       cfg->yubi_attr_prefix ? cfg->yubi_attr_prefix : "", token_id));

		  /* Only values containing this prefix are considered. */
		  if ((!cfg->yubi_attr_prefix || !strncmp (cfg->yubi_attr_prefix, vals[i]->bv_val, yubi_attr_prefix_len)))
		    {
		      if(!strncmp (token_id, vals[i]->bv_val + yubi_attr_prefix_len, strlen (token_id)))
		        {
		          DBG (("Token Found :: %s", vals[i]->bv_val));
		          retval = 1;
		        }
		    }
		}
	      ldap_value_free_len (vals);
	    }
	  ldap_memfree (a);
	}
      if (ber != NULL)
	  ber_free (ber, 0);
    }

 done:
  if (result != NULL)
    ldap_msgfree (result);
  if (ld != NULL)
    ldap_unbind (ld);

  /* free memory allocated for search strings */
  if (find != NULL)
    free(find);
  if (filter != NULL)
    free(filter);

#else
  DBG (("Trying to use LDAP, but this function is not compiled in pam_yubico!!"));
  DBG (("Install libldap-dev and then recompile pam_yubico."));
#endif
  return retval;
}

#if HAVE_CR
static int
display_error(pam_handle_t *pamh, const char *message) {
  struct pam_conv *conv;
  const struct pam_message *pmsg[1];
  struct pam_message msg[1];
  struct pam_response *resp = NULL;
  int retval;

  retval = pam_get_item (pamh, PAM_CONV, (const void **) &conv);
  if (retval != PAM_SUCCESS) {
    D(("get conv returned error: %s", pam_strerror (pamh, retval)));
    return retval;
  }

  pmsg[0] = &msg[0];
  msg[0].msg = (char *) message; /* on some systems, pam_message.msg isn't const */
  msg[0].msg_style = PAM_ERROR_MSG;
  retval = conv->conv(1, pmsg, &resp, conv->appdata_ptr);

  if (retval != PAM_SUCCESS) {
    D(("conv returned error: %s", pam_strerror (pamh, retval)));
    return retval;
  }<commit_msg>add check for NULL conv<commit_after>/* Written by <NAME> <<EMAIL>>.
 * Copyright (c) 2006-2014 Yubico AB
 * Copyright (c) 2011 <NAME> <<EMAIL>>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <syslog.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "util.h"
#include "drop_privs.h"

#include <ykclient.h>

#if HAVE_CR
/* for yubikey_hex_encode */
#include <yubikey.h>
/* for yubikey pbkdf2*/
#include <ykpbkdf2.h>
#endif /* HAVE_CR */

/* Libtool defines PIC for shared objects */
#ifndef PIC
#define PAM_STATIC
#endif

/* These #defines must be present according to PAM documentation. */
#define PAM_SM_AUTH

#ifdef HAVE_SECURITY_PAM_APPL_H
#include <security/pam_appl.h>
#endif
#ifdef HAVE_SECURITY_PAM_MODULES_H
#include <security/pam_modules.h>
#endif

#ifdef HAVE_LIBLDAP
/* Some functions like ldap_init, ldap_simple_bind_s, ldap_unbind are
   deprecated but still available. We will drop support for 'ldapserver'
   (in favour of 'ldap_uri' and update to using the new functions instead
   soon.
*/
#define LDAP_DEPRECATED 1

#include <ldap.h>
#define PORT_NUMBER  LDAP_PORT
#endif

#ifndef PAM_EXTERN
#ifdef PAM_STATIC
#define PAM_EXTERN static
#else
#define PAM_EXTERN extern
#endif
#endif

#define TOKEN_OTP_LEN 32u
#define MAX_TOKEN_ID_LEN 16u
#define DEFAULT_TOKEN_ID_LEN 12u

#define TMPFILE_SUFFIX ".XXXXXX"

enum key_mode {
  CHRESP,
  CLIENT
};

struct cfg
{
  unsigned int client_id;
  const char *client_key;
  int debug;
  int alwaysok;
  int verbose_otp;
  int try_first_pass;
  int use_first_pass;
  const char *auth_file;
  const char *capath;
  const char *cainfo;
  const char *proxy;
  const char *url;
  const char *urllist;
  const char *ldapserver;
  const char *ldap_uri;
  const char *ldap_bind_user;
  const char *ldap_bind_password;
  const char *ldap_filter;
  const char *ldap_cacertfile;
  const char *ldapdn;
  const char *user_attr;
  const char *yubi_attr;
  const char *yubi_attr_prefix;
  unsigned int token_id_length;
  enum key_mode mode;
  const char *chalresp_path;
};

#ifdef DBG
#undef DBG
#endif
#define DBG(x) if (cfg->debug) { D(x); }

/*
 * Authorize authenticated OTP_ID for login as USERNAME using
 * AUTHFILE.  Return -2 if the user is unknown, -1 if the OTP_ID does not match,  0 on internal failures, otherwise success.
 */
static int
authorize_user_token (struct cfg *cfg,
		      const char *username,
		      const char *otp_id,
		      pam_handle_t *pamh)
{
  int retval;

  if (cfg->auth_file)
    {
      /* Administrator had configured the file and specified is name
         as an argument for this module.
       */
      DBG (("Using system-wide auth_file %s", cfg->auth_file));
      retval = check_user_token (cfg->auth_file, username, otp_id, cfg->debug);
    }
  else
    {
      char *userfile = NULL;
      struct passwd *p;
      PAM_MODUTIL_DEF_PRIVS(privs);

#ifdef HAVE_PAM_MODUTIL_GETPWNAM
      p = pam_modutil_getpwnam (pamh, username);
#else
      p = getpwnam (username);
#endif
      if (p == NULL) {
	DBG (("getpwnam: %s", strerror(errno)));
	return 0;
      }

      /* Getting file from user home directory
         ..... i.e. ~/.yubico/authorized_yubikeys
       */
      if (! get_user_cfgfile_path (NULL, "authorized_yubikeys", p, &userfile)) {
	D (("Failed figuring out per-user cfgfile"));
	return 0;
      }

      DBG (("Dropping privileges"));
      if(pam_modutil_drop_priv(pamh, &privs, p)) {
        DBG (("could not drop privileges"));
	retval = 0;
	goto free_out;
      }

      retval = check_user_token (userfile, username, otp_id, cfg->debug);

      if(pam_modutil_regain_priv(pamh, &privs)) {
        DBG (("could not restore privileges"));
        retval = 0;
        goto free_out;
      }

free_out:
      free (userfile);
    }

  return retval;
}

/*
 * This function will look in ldap id the token correspond to the
 * requested user. It will returns 0 for failure and 1 for success.
 *
 * ldaps is only supported for ldap_uri based connections.
 * ldap_cacertfile usually needs to be set for this to work.
 *
 * ldap serve can be on a remote host.
 *
 * You need the following parameters in you pam config:
 * ldapserver=  OR ldap_uri=
 * ldapdn=
 * user_attr=
 * yubi_attr=
 *
 * If using ldap_uri, you can specify multiple failover hosts
 * eg.
 * ldap_uri=ldaps://host1.fqdn.example.com,ldaps://host2.fqdn.example.com
 */
static int
authorize_user_token_ldap (struct cfg *cfg,
			   const char *user,
			   const char *token_id)
{
  int retval = 0;
#ifdef HAVE_LIBLDAP
  /* LDAPv2 is historical -- RFC3494. */
  int protocol = LDAP_VERSION3;
  size_t yubi_attr_prefix_len = 0;
  LDAP *ld = NULL;
  LDAPMessage *result = NULL, *e;
  BerElement *ber;
  char *a;
  char *attrs[2] = {NULL, NULL};

  struct berval **vals;
  int rc;
  size_t i;

  char *filter = NULL;
  char *find = NULL;
  int scope = LDAP_SCOPE_BASE;
#endif
  DBG(("called"));
#ifdef HAVE_LIBLDAP
  if (cfg->yubi_attr == NULL) {
    DBG (("Trying to look up user to YubiKey mapping in LDAP, but yubi_attr not set!"));
    return 0;
  }
  if (cfg->user_attr && cfg->ldapdn == NULL) {
    DBG (("Trying to look up user to YubiKey mapping in LDAP, user_attr set but ldapdn not set!"));
    return 0;
  }

  /* Get a handle to an LDAP connection. */
  if (cfg->ldap_uri)
    {
      rc = ldap_initialize (&ld, cfg->ldap_uri);
      if (rc != LDAP_SUCCESS)
	{
	  DBG (("ldap_initialize: %s", ldap_err2string (rc)));
	  retval = 0;
	  goto done;
	}
    }
  else
    {
      if ((ld = ldap_init (cfg->ldapserver, PORT_NUMBER)) == NULL)
	{
	  DBG (("ldap_init"));
	  retval = 0;
	  goto done;
	}
    }

  ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
  ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &protocol);

  if (cfg->ldap_uri && cfg->ldap_cacertfile) {
    /* Set CA CERTFILE.  This makes ldaps work when using ldap_uri */
    ldap_set_option (0, LDAP_OPT_X_TLS_CACERTFILE, cfg->ldap_cacertfile);
  }
  /* Bind anonymously to the LDAP server. */
  if (cfg->ldap_bind_user && cfg->ldap_bind_password) {
    DBG (("try bind with: %s:[%s]", cfg->ldap_bind_user, cfg->ldap_bind_password));
    rc = ldap_simple_bind_s (ld, cfg->ldap_bind_user, cfg->ldap_bind_password);
  } else {
    DBG (("try bind anonymous"));
    rc = ldap_simple_bind_s (ld, NULL, NULL);
  }
  if (rc != LDAP_SUCCESS)
    {
      DBG (("ldap_simple_bind_s: %s", ldap_err2string (rc)));
      retval = 0;
      goto done;
    }

  /* Allocation of memory for search strings depending on input size */
  if (cfg->user_attr && cfg->yubi_attr && cfg->ldapdn) {
    i = (strlen(cfg->user_attr) + strlen(cfg->ldapdn) + strlen(user) + 3) * sizeof(char);
    if ((find = malloc(i)) == NULL) {
      DBG (("Failed allocating %zu bytes", i));
      retval = 0;
      goto done;
    }
    sprintf (find, "%s=%s,%s", cfg->user_attr, user, cfg->ldapdn);
    filter = NULL;
  } else if (cfg->ldapdn) {
    find = strdup(cfg->ldapdn); /* allow free later */
  }
  if (cfg->ldap_filter) {
    filter = filter_printf(cfg->ldap_filter, user);
    scope = LDAP_SCOPE_SUBTREE;
  }
  attrs[0] = (char *) cfg->yubi_attr;

  DBG(("LDAP : look up object base='%s' filter='%s', ask for attribute '%s'", find,
      filter ? filter:"(null)", cfg->yubi_attr));

  /* Search for the entry. */
  if ((rc = ldap_search_ext_s (ld, find, scope,
			       filter, attrs, 0, NULL, NULL, LDAP_NO_LIMIT,
			       LDAP_NO_LIMIT, &result)) != LDAP_SUCCESS)
    {
      DBG (("ldap_search_ext_s: %s", ldap_err2string (rc)));

      retval = 0;
      goto done;
    }

  e = ldap_first_entry (ld, result);
  if (e == NULL)
    {
      DBG (("No result from LDAP search"));
      retval = -2;
    }
  else
    {
      retval = -1;
      /* Iterate through each returned attribute. */
      for (a = ldap_first_attribute (ld, e, &ber);
	   a != NULL; a = ldap_next_attribute (ld, e, ber))
	{
	  if ((vals = ldap_get_values_len (ld, e, a)) != NULL)
	    {
	      yubi_attr_prefix_len = cfg->yubi_attr_prefix ? strlen(cfg->yubi_attr_prefix) : 0;

	      /* Compare each value for the attribute against the token id. */
	      for (i = 0; vals[i] != NULL; i++)
		{
	          DBG(("LDAP : Found %i values - checking if any of them match '%s:%s:%s'",
		       ldap_count_values_len(vals),
		       vals[i]->bv_val,
		       cfg->yubi_attr_prefix ? cfg->yubi_attr_prefix : "", token_id));

		  /* Only values containing this prefix are considered. */
		  if ((!cfg->yubi_attr_prefix || !strncmp (cfg->yubi_attr_prefix, vals[i]->bv_val, yubi_attr_prefix_len)))
		    {
		      if(!strncmp (token_id, vals[i]->bv_val + yubi_attr_prefix_len, strlen (token_id)))
		        {
		          DBG (("Token Found :: %s", vals[i]->bv_val));
		          retval = 1;
		        }
		    }
		}
	      ldap_value_free_len (vals);
	    }
	  ldap_memfree (a);
	}
      if (ber != NULL)
	  ber_free (ber, 0);
    }

 done:
  if (result != NULL)
    ldap_msgfree (result);
  if (ld != NULL)
    ldap_unbind (ld);

  /* free memory allocated for search strings */
  if (find != NULL)
    free(find);
  if (filter != NULL)
    free(filter);

#else
  DBG (("Trying to use LDAP, but this function is not compiled in pam_yubico!!"));
  DBG (("Install libldap-dev and then recompile pam_yubico."));
#endif
  return retval;
}

#if HAVE_CR
static int
display_error(pam_handle_t *pamh, const char *message) {
  struct pam_conv *conv;
  const struct pam_message *pmsg[1];
  struct pam_message msg[1];
  struct pam_response *resp = NULL;
  int retval;

  retval = pam_get_item (pamh, PAM_CONV, (const void **) &conv);
  if (retval != PAM_SUCCESS) {
    D(("get conv returned error: %s", pam_strerror (pamh, retval)));
    return retval;
  }

  if(!conv || !conv->conv){
    D(("conv() function invalid"));
    return PAM_CONV_ERR;
  }
  pmsg[0] = &msg[0];
  msg[0].msg = (char *) message; /* on some systems, pam_message.msg isn't const */
  msg[0].msg_style = PAM_ERROR_MSG;
  retval = conv->conv(1, pmsg, &resp, conv->appdata_ptr);
  
  if (retval != PAM_SUCCESS) {
    D(("conv returned error: %s", pam_strerror (pamh, retval)));
    return retval;
  }
{'fraction_non_alphanumeric': 0.12153973582109072, 'fraction_numerical': 0.005928767601028816, 'mean_word_length': 3.214587543634025, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 142, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4387137', 'n_tokens_mistral': 8553, 'n_tokens_neox': 8138, 'n_words': 2445}