Description: backport pam_faillock module from pam 1.4.0
Author: Marc Deslauriers <marc.deslauriers@canonical.com>

--- a/configure.in
+++ b/configure.in
@@ -609,6 +609,7 @@ AC_CONFIG_FILES([Makefile libpam/Makefil
 	modules/pam_echo/Makefile modules/pam_env/Makefile \
 	modules/pam_extrausers/Makefile \
 	modules/pam_faildelay/Makefile \
+	modules/pam_faillock/Makefile \
 	modules/pam_filter/Makefile modules/pam_filter/upperLOWER/Makefile \
 	modules/pam_ftp/Makefile modules/pam_group/Makefile \
 	modules/pam_issue/Makefile modules/pam_keyinit/Makefile \
--- /dev/null
+++ b/doc/sag/pam_faillock.xml
@@ -0,0 +1,38 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
+        "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
+<section id='sag-pam_faillock'>
+  <title>pam_faillock - temporarily locking access based on failed authentication attempts during an interval</title>
+  <cmdsynopsis>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//cmdsynopsis[@id = "pam_faillock-cmdsynopsisauth"]/*)'/>
+  </cmdsynopsis>
+  <cmdsynopsis>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//cmdsynopsis[@id = "pam_faillock-cmdsynopsisacct"]/*)'/>
+  </cmdsynopsis>
+  <section id='sag-pam_faillock-description'>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-description"]/*)'/>
+  </section>
+  <section id='sag-pam_faillock-options'>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-options"]/*)'/>
+  </section>
+  <section id='sag-pam_faillock-types'>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-types"]/*)'/>
+  </section>
+  <section id='sag-pam_faillock-return_values'>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-return_values"]/*)'/>
+  </section>
+  <section id='sag-pam_faillock-examples'>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-examples"]/*)'/>
+  </section>
+  <section id='sag-pam_faillock-author'>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+     href="../../modules/pam_faillock/pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-author"]/*)'/>
+  </section>
+</section>
--- /dev/null
+++ b/modules/pam_faillock/Makefile.am
@@ -0,0 +1,47 @@
+#
+# Copyright (c) 2005, 2006, 2007, 2009 Thorsten Kukuk <kukuk@thkukuk.de>
+# Copyright (c) 2008, 2018, 2020 Red Hat, Inc.
+# Copyright (c) 2010 Tomas Mraz <tmraz@redhat.com>
+#
+
+CLEANFILES = *~
+MAINTAINERCLEANFILES = $(MANS) README
+
+EXTRA_DIST = README $(MANS) $(XMLS) tst-pam_faillock
+
+man_MANS = pam_faillock.8 faillock.8 faillock.conf.5
+XMLS = README.xml pam_faillock.8.xml faillock.8.xml faillock.conf.5.xml
+
+TESTS = tst-pam_faillock
+
+securelibdir = $(SECUREDIR)
+secureconfdir = $(SCONFIGDIR)
+
+noinst_HEADERS = faillock.h
+
+AM_CFLAGS = -I$(top_srcdir)/libpam/include -I$(top_srcdir)/libpamc/include \
+	$(WARN_CFLAGS)
+
+faillock_CFLAGS = $(AM_CFLAGS) @PIE_CFLAGS@
+
+pam_faillock_la_LDFLAGS = -no-undefined -avoid-version -module
+pam_faillock_la_LIBADD = $(top_builddir)/libpam/libpam.la $(LIBAUDIT)
+if HAVE_VERSIONING
+  pam_faillock_la_LDFLAGS += -Wl,--version-script=$(srcdir)/../modules.map
+endif
+
+faillock_LDFLAGS = @PIE_LDFLAGS@
+faillock_LDADD = $(top_builddir)/libpam/libpam.la $(LIBAUDIT)
+
+dist_secureconf_DATA = faillock.conf
+
+securelib_LTLIBRARIES = pam_faillock.la
+sbin_PROGRAMS = faillock
+
+pam_faillock_la_SOURCES = pam_faillock.c faillock.c
+faillock_SOURCES = main.c faillock.c
+
+#if ENABLE_REGENERATE_MAN
+#dist_noinst_DATA = README
+#-include $(top_srcdir)/Make.xml.rules
+#endif
--- /dev/null
+++ b/modules/pam_faillock/README
@@ -0,0 +1,140 @@
+pam_faillock — Module counting authentication failures during a specified
+interval
+
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+DESCRIPTION
+
+This module maintains a list of failed authentication attempts per user during
+a specified interval and locks the account in case there were more than deny
+consecutive failed authentications.
+
+Normally, failed attempts to authenticate root will not cause the root account
+to become blocked, to prevent denial-of-service: if your users aren't given
+shell accounts and root may only login via su or at the machine console (not
+telnet/rsh, etc), this is safe.
+
+OPTIONS
+
+{preauth|authfail|authsucc}
+
+    This argument must be set accordingly to the position of this module
+    instance in the PAM stack.
+
+    The preauth argument must be used when the module is called before the
+    modules which ask for the user credentials such as the password. The module
+    just examines whether the user should be blocked from accessing the service
+    in case there were anomalous number of failed consecutive authentication
+    attempts recently. This call is optional if authsucc is used.
+
+    The authfail argument must be used when the module is called after the
+    modules which determine the authentication outcome, failed. Unless the user
+    is already blocked due to previous authentication failures, the module will
+    record the failure into the appropriate user tally file.
+
+    The authsucc argument must be used when the module is called after the
+    modules which determine the authentication outcome, succeeded. Unless the
+    user is already blocked due to previous authentication failures, the module
+    will then clear the record of the failures in the respective user tally
+    file. Otherwise it will return authentication error. If this call is not
+    done, the pam_faillock will not distinguish between consecutive and
+    non-consecutive failed authentication attempts. The preauth call must be
+    used in such case. Due to complications in the way the PAM stack can be
+    configured it is also possible to call pam_faillock as an account module.
+    In such configuration the module must be also called in the preauth stage.
+
+conf=/path/to/config-file
+
+    Use another configuration file instead of the default /etc/security/
+    faillock.conf.
+
+The options for configuring the module behavior are described in the 
+faillock.conf(5) manual page. The options specified on the module command line
+override the values from the configuration file.
+
+NOTES
+
+Configuring options on the module command line is not recommend. The /etc/
+security/faillock.conf should be used instead.
+
+The setup of pam_faillock in the PAM stack is different from the pam_tally2
+module setup.
+
+Individual files with the failure records are created as owned by the user.
+This allows pam_faillock.so module to work correctly when it is called from a
+screensaver.
+
+Note that using the module in preauth without the silent option specified in /
+etc/security/faillock.conf or with requisite control field leaks an information
+about existence or non-existence of an user account in the system because the
+failures are not recorded for the unknown users. The message about the user
+account being locked is never displayed for non-existing user accounts allowing
+the adversary to infer that a particular account is not existing on a system.
+
+EXAMPLES
+
+Here are two possible configuration examples for /etc/pam.d/login. They make 
+pam_faillock to lock the account after 4 consecutive failed logins during the
+default interval of 15 minutes. Root account will be locked as well. The
+accounts will be automatically unlocked after 20 minutes.
+
+In the first example the module is called only in the auth phase and the module
+does not print any information about the account being blocked by pam_faillock.
+The preauth call can be added to tell users that their logins are blocked by
+the module and also to abort the authentication without even asking for
+password in such case.
+
+/etc/security/faillock.conf file example:
+
+deny=4
+unlock_time=1200
+silent
+
+
+/etc/pam.d/config file example:
+
+auth     required       pam_securetty.so
+auth     required       pam_env.so
+auth     required       pam_nologin.so
+# optionally call: auth requisite pam_faillock.so preauth
+# to display the message about account being locked
+auth     [success=1 default=bad] pam_unix.so
+auth     [default=die]  pam_faillock.so authfail
+auth     sufficient     pam_faillock.so authsucc
+auth     required       pam_deny.so
+account  required       pam_unix.so
+password required       pam_unix.so shadow
+session  required       pam_selinux.so close
+session  required       pam_loginuid.so
+session  required       pam_unix.so
+session  required       pam_selinux.so open
+
+
+In the second example the module is called both in the auth and account phases
+and the module informs the authenticating user when the account is locked if
+silent option is not specified in the faillock.conf.
+
+auth     required       pam_securetty.so
+auth     required       pam_env.so
+auth     required       pam_nologin.so
+auth     required       pam_faillock.so preauth
+# optionally use requisite above if you do not want to prompt for the password
+# on locked accounts
+auth     sufficient     pam_unix.so
+auth     [default=die]  pam_faillock.so authfail
+auth     required       pam_deny.so
+account  required       pam_faillock.so
+# if you drop the above call to pam_faillock.so the lock will be done also
+# on non-consecutive authentication failures
+account  required       pam_unix.so
+password required       pam_unix.so shadow
+session  required       pam_selinux.so close
+session  required       pam_loginuid.so
+session  required       pam_unix.so
+session  required       pam_selinux.so open
+
+
+AUTHOR
+
+pam_faillock was written by Tomas Mraz.
+
--- /dev/null
+++ b/modules/pam_faillock/README.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding='UTF-8'?>
+<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
+"http://www.docbook.org/xml/4.3/docbookx.dtd"
+[
+<!--
+<!ENTITY pamaccess SYSTEM "pam_faillock.8.xml">
+-->
+]>
+
+<article>
+
+  <articleinfo>
+
+    <title>
+      <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+      href="pam_faillock.8.xml" xpointer='xpointer(//refnamediv[@id = "pam_faillock-name"]/*)'/>
+    </title>
+
+  </articleinfo>
+
+  <section>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+      href="pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-description"]/*)'/>
+  </section>
+
+  <section>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+      href="pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-options"]/*)'/>
+  </section>
+
+  <section>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+      href="pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-notes"]/*)'/>
+  </section>
+
+  <section>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+      href="pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-examples"]/*)'/>
+  </section>
+
+  <section>
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude"
+      href="pam_faillock.8.xml" xpointer='xpointer(//refsect1[@id = "pam_faillock-author"]/*)'/>
+  </section>
+
+</article>
--- /dev/null
+++ b/modules/pam_faillock/faillock.8
@@ -0,0 +1,78 @@
+'\" t
+.\"     Title: faillock
+.\"    Author: [see the "AUTHOR" section]
+.\" Generator: DocBook XSL Stylesheets v1.79.1 <http://docbook.sf.net/>
+.\"      Date: 06/08/2020
+.\"    Manual: Linux-PAM Manual
+.\"    Source: Linux-PAM Manual
+.\"  Language: English
+.\"
+.TH "FAILLOCK" "8" "06/08/2020" "Linux-PAM Manual" "Linux\-PAM Manual"
+.\" -----------------------------------------------------------------
+.\" * Define some portability stuff
+.\" -----------------------------------------------------------------
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" http://bugs.debian.org/507673
+.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.ie \n(.g .ds Aq \(aq
+.el       .ds Aq '
+.\" -----------------------------------------------------------------
+.\" * set default formatting
+.\" -----------------------------------------------------------------
+.\" disable hyphenation
+.nh
+.\" disable justification (adjust text to left margin only)
+.ad l
+.\" -----------------------------------------------------------------
+.\" * MAIN CONTENT STARTS HERE *
+.\" -----------------------------------------------------------------
+.SH "NAME"
+faillock \- Tool for displaying and modifying the authentication failure record files
+.SH "SYNOPSIS"
+.HP \w'\fBfaillock\fR\ 'u
+\fBfaillock\fR [\-\-dir\ \fI/path/to/tally\-directory\fR] [\-\-user\ \fIusername\fR] [\-\-reset]
+.SH "DESCRIPTION"
+.PP
+The
+\fIpam_faillock\&.so\fR
+module maintains a list of failed authentication attempts per user during a specified interval and locks the account in case there were more than
+\fIdeny\fR
+consecutive failed authentications\&. It stores the failure records into per\-user files in the tally directory\&.
+.PP
+The
+\fBfaillock\fR
+command is an application which can be used to examine and modify the contents of the tally files\&. It can display the recent failed authentication attempts of the
+\fIusername\fR
+or clear the tally files of all or individual
+\fIusernames\fR\&.
+.SH "OPTIONS"
+.PP
+\fB\-\-dir \fR\fB\fI/path/to/tally\-directory\fR\fR
+.RS 4
+The directory where the user files with the failure records are kept\&. The default is
+/var/run/faillock\&.
+.RE
+.PP
+\fB\-\-user \fR\fB\fIusername\fR\fR
+.RS 4
+The user whose failure records should be displayed or cleared\&.
+.RE
+.PP
+\fB\-\-reset\fR
+.RS 4
+Instead of displaying the user\*(Aqs failure records, clear them\&.
+.RE
+.SH "FILES"
+.PP
+/var/run/faillock/*
+.RS 4
+the files logging the authentication failures for users
+.RE
+.SH "SEE ALSO"
+.PP
+\fBpam_faillock\fR(8),
+\fBpam\fR(8)
+.SH "AUTHOR"
+.PP
+faillock was written by Tomas Mraz\&.
--- /dev/null
+++ b/modules/pam_faillock/faillock.8.xml
@@ -0,0 +1,123 @@
+<?xml version="1.0" encoding='UTF-8'?>
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
+	"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
+
+<refentry id="faillock">
+
+  <refmeta>
+    <refentrytitle>faillock</refentrytitle>
+    <manvolnum>8</manvolnum>
+    <refmiscinfo class="sectdesc">Linux-PAM Manual</refmiscinfo>
+  </refmeta>
+
+  <refnamediv id="pam_faillock-name">
+    <refname>faillock</refname>
+    <refpurpose>Tool for displaying and modifying the authentication failure record files</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis id="faillock-cmdsynopsis">
+      <command>faillock</command>
+      <arg choice="opt">
+        --dir <replaceable>/path/to/tally-directory</replaceable>
+      </arg>
+      <arg choice="opt">
+        --user <replaceable>username</replaceable>
+      </arg>
+      <arg choice="opt">
+        --reset
+      </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+  <refsect1 id="faillock-description">
+
+    <title>DESCRIPTION</title>
+
+    <para>
+      The <emphasis>pam_faillock.so</emphasis> module maintains a list of
+      failed authentication attempts per user during a specified interval
+      and locks the account in case there were more than
+      <replaceable>deny</replaceable> consecutive failed authentications.
+      It stores the failure records into per-user files in the tally
+      directory.
+    </para>
+    <para>
+      The <command>faillock</command> command is an application which
+      can be used to examine and modify the contents of the
+      tally files. It can display the recent failed authentication
+      attempts of the <replaceable>username</replaceable> or clear the tally
+      files of all or individual <replaceable>usernames</replaceable>.
+    </para>
+  </refsect1>
+
+  <refsect1 id="faillock-options">
+
+    <title>OPTIONS</title>
+         <variablelist>
+            <varlistentry>
+              <term>
+                <option>--dir <replaceable>/path/to/tally-directory</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  The directory where the user files with the failure records are kept. The
+                  default is <filename>/var/run/faillock</filename>.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>--user <replaceable>username</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  The user whose failure records should be displayed or cleared.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>--reset</option>
+              </term>
+              <listitem>
+                <para>
+                  Instead of displaying the user's failure records, clear them.
+                </para>
+              </listitem>
+            </varlistentry>
+        </variablelist>
+  </refsect1>
+
+  <refsect1 id="faillock-files">
+    <title>FILES</title>
+    <variablelist>
+      <varlistentry>
+        <term><filename>/var/run/faillock/*</filename></term>
+        <listitem>
+          <para>the files logging the authentication failures for users</para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </refsect1>
+
+  <refsect1 id='faillock-see_also'>
+    <title>SEE ALSO</title>
+    <para>
+      <citerefentry>
+        <refentrytitle>pam_faillock</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>
+    </para>
+  </refsect1>
+
+  <refsect1 id='faillock-author'>
+    <title>AUTHOR</title>
+      <para>
+        faillock was written by Tomas Mraz.
+      </para>
+  </refsect1>
+
+</refentry>
--- /dev/null
+++ b/modules/pam_faillock/faillock.c
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2010 Tomas Mraz <tmraz@redhat.com>
+ * Copyright (c) 2010, 2016, 2017 Red Hat, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, and the entire permission notice in its entirety,
+ *    including the disclaimer of warranties.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * ALTERNATIVELY, this product may be distributed under the terms of
+ * the GNU Public License, in which case the provisions of the GPL are
+ * required INSTEAD OF the above restrictions.  (This clause is
+ * necessary due to a potential bad interaction between the GPL and
+ * the restrictions contained in a BSD-style copyright.)
+ *
+ * THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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 "config.h"
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <security/pam_modutil.h>
+
+#include "faillock.h"
+
+#define ignore_return(x) if (1==((int)x)) {;}
+
+int
+open_tally (const char *dir, const char *user, uid_t uid, int create)
+{
+	char *path;
+	int flags = O_RDWR;
+	int fd;
+
+	if (dir == NULL || strstr(user, "../") != NULL)
+	/* just a defensive programming as the user must be a
+	 * valid user on the system anyway
+	 */
+		return -1;
+	path = malloc(strlen(dir) + strlen(user) + 2);
+	if (path == NULL)
+		return -1;
+
+	strcpy(path, dir);
+	if (*dir && dir[strlen(dir) - 1] != '/') {
+		strcat(path, "/");
+	}
+	strcat(path, user);
+
+	if (create) {
+		flags |= O_CREAT;
+	}
+
+	fd = open(path, flags, 0600);
+
+	free(path);
+
+	if (fd != -1) {
+		struct stat st;
+
+		while (flock(fd, LOCK_EX) == -1 && errno == EINTR);
+		if (fstat(fd, &st) == 0) {
+			if (st.st_uid != uid) {
+				ignore_return(fchown(fd, uid, -1));
+			}
+		}
+	}
+
+	return fd;
+}
+
+#define CHUNK_SIZE (64 * sizeof(struct tally))
+#define MAX_RECORDS 1024
+
+int
+read_tally(int fd, struct tally_data *tallies)
+{
+	void *data = NULL, *newdata;
+	unsigned int count = 0;
+	ssize_t chunk = 0;
+
+	do {
+		newdata = realloc(data, count * sizeof(struct tally) + CHUNK_SIZE);
+		if (newdata == NULL) {
+			free(data);
+			return -1;
+		}
+
+		data = newdata;
+
+		chunk = pam_modutil_read(fd, (char *)data + count * sizeof(struct tally), CHUNK_SIZE);
+		if (chunk < 0) {
+			free(data);
+			return -1;
+		}
+
+		count += chunk/sizeof(struct tally);
+
+		if (count >= MAX_RECORDS)
+			break;
+	}
+	while (chunk == CHUNK_SIZE);
+
+	tallies->records = data;
+	tallies->count = count;
+
+	return 0;
+}
+
+int
+update_tally(int fd, struct tally_data *tallies)
+{
+	void *data = tallies->records;
+	unsigned int count = tallies->count;
+	ssize_t chunk;
+
+	if (tallies->count > MAX_RECORDS) {
+		data = tallies->records + (count - MAX_RECORDS);
+		count = MAX_RECORDS;
+	}
+
+	if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
+		return -1;
+	}
+
+	chunk = pam_modutil_write(fd, data, count * sizeof(struct tally));
+
+	if (chunk != (ssize_t)(count * sizeof(struct tally))) {
+		return -1;
+	}
+
+	if (ftruncate(fd, count * sizeof(struct tally)) == -1)
+		return -1;
+
+	return 0;
+}
--- /dev/null
+++ b/modules/pam_faillock/faillock.conf
@@ -0,0 +1,62 @@
+# Configuration for locking the user after multiple failed
+# authentication attempts.
+#
+# The directory where the user files with the failure records are kept.
+# The default is /var/run/faillock.
+# dir = /var/run/faillock
+#
+# Will log the user name into the system log if the user is not found.
+# Enabled if option is present.
+# audit
+#
+# Don't print informative messages.
+# Enabled if option is present.
+# silent
+#
+# Don't log informative messages via syslog.
+# Enabled if option is present.
+# no_log_info
+#
+# Only track failed user authentications attempts for local users
+# in /etc/passwd and ignore centralized (AD, IdM, LDAP, etc.) users.
+# The `faillock` command will also no longer track user failed
+# authentication attempts. Enabling this option will prevent a
+# double-lockout scenario where a user is locked out locally and
+# in the centralized mechanism.
+# Enabled if option is present.
+# local_users_only
+#
+# Deny access if the number of consecutive authentication failures
+# for this user during the recent interval exceeds n tries.
+# The default is 3.
+# deny = 3
+#
+# The length of the interval during which the consecutive
+# authentication failures must happen for the user account
+# lock out is <replaceable>n</replaceable> seconds.
+# The default is 900 (15 minutes).
+# fail_interval = 900
+#
+# The access will be re-enabled after n seconds after the lock out.
+# The value 0 has the same meaning as value `never` - the access
+# will not be re-enabled without resetting the faillock
+# entries by the `faillock` command.
+# The default is 600 (10 minutes).
+# unlock_time = 600
+#
+# Root account can become locked as well as regular accounts.
+# Enabled if option is present.
+# even_deny_root
+#
+# This option implies the `even_deny_root` option.
+# Allow access after n seconds to root account after the
+# account is locked. In case the option is not specified
+# the value is the same as of the `unlock_time` option.
+# root_unlock_time = 900
+#
+# If a group name is specified with this option, members
+# of the group will be handled by this module the same as
+# the root account (the options `even_deny_root>` and
+# `root_unlock_time` will apply to them.
+# By default, the option is not set.
+# admin_group = <admin_group_name>
--- /dev/null
+++ b/modules/pam_faillock/faillock.conf.5
@@ -0,0 +1,166 @@
+'\" t
+.\"     Title: faillock.conf
+.\"    Author: [see the "AUTHOR" section]
+.\" Generator: DocBook XSL Stylesheets v1.79.1 <http://docbook.sf.net/>
+.\"      Date: 06/08/2020
+.\"    Manual: Linux-PAM Manual
+.\"    Source: Linux-PAM Manual
+.\"  Language: English
+.\"
+.TH "FAILLOCK\&.CONF" "5" "06/08/2020" "Linux-PAM Manual" "Linux\-PAM Manual"
+.\" -----------------------------------------------------------------
+.\" * Define some portability stuff
+.\" -----------------------------------------------------------------
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" http://bugs.debian.org/507673
+.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.ie \n(.g .ds Aq \(aq
+.el       .ds Aq '
+.\" -----------------------------------------------------------------
+.\" * set default formatting
+.\" -----------------------------------------------------------------
+.\" disable hyphenation
+.nh
+.\" disable justification (adjust text to left margin only)
+.ad l
+.\" -----------------------------------------------------------------
+.\" * MAIN CONTENT STARTS HERE *
+.\" -----------------------------------------------------------------
+.SH "NAME"
+faillock.conf \- pam_faillock configuration file
+.SH "DESCRIPTION"
+.PP
+\fBfaillock\&.conf\fR
+provides a way to configure the default settings for locking the user after multiple failed authentication attempts\&. This file is read by the
+\fIpam_faillock\fR
+module and is the preferred method over configuring
+\fIpam_faillock\fR
+directly\&.
+.PP
+The file has a very simple
+\fIname = value\fR
+format with possible comments starting with
+\fI#\fR
+character\&. The whitespace at the beginning of line, end of line, and around the
+\fI=\fR
+sign is ignored\&.
+.SH "OPTIONS"
+.PP
+\fBdir=\fR\fB\fI/path/to/tally\-directory\fR\fR
+.RS 4
+The directory where the user files with the failure records are kept\&. The default is
+/var/run/faillock\&.
+.RE
+.PP
+\fBaudit\fR
+.RS 4
+Will log the user name into the system log if the user is not found\&.
+.RE
+.PP
+\fBsilent\fR
+.RS 4
+Don\*(Aqt print informative messages to the user\&. Please note that when this option is not used there will be difference in the authentication behavior for users which exist on the system and non\-existing users\&.
+.RE
+.PP
+\fBno_log_info\fR
+.RS 4
+Don\*(Aqt log informative messages via
+\fBsyslog\fR(3)\&.
+.RE
+.PP
+\fBlocal_users_only\fR
+.RS 4
+Only track failed user authentications attempts for local users in /etc/passwd and ignore centralized (AD, IdM, LDAP, etc\&.) users\&. The
+\fBfaillock\fR(8)
+command will also no longer track user failed authentication attempts\&. Enabling this option will prevent a double\-lockout scenario where a user is locked out locally and in the centralized mechanism\&.
+.RE
+.PP
+\fBdeny=\fR\fB\fIn\fR\fR
+.RS 4
+Deny access if the number of consecutive authentication failures for this user during the recent interval exceeds
+\fIn\fR\&. The default is 3\&.
+.RE
+.PP
+\fBfail_interval=\fR\fB\fIn\fR\fR
+.RS 4
+The length of the interval during which the consecutive authentication failures must happen for the user account lock out is
+\fIn\fR
+seconds\&. The default is 900 (15 minutes)\&.
+.RE
+.PP
+\fBunlock_time=\fR\fB\fIn\fR\fR
+.RS 4
+The access will be re\-enabled after
+\fIn\fR
+seconds after the lock out\&. The value 0 has the same meaning as value
+\fInever\fR
+\- the access will not be re\-enabled without resetting the faillock entries by the
+\fBfaillock\fR(8)
+command\&. The default is 600 (10 minutes)\&.
+.sp
+Note that the default directory that
+\fIpam_faillock\fR
+uses is usually cleared on system boot so the access will be also re\-enabled after system reboot\&. If that is undesirable a different tally directory must be set with the
+\fBdir\fR
+option\&.
+.sp
+Also note that it is usually undesirable to permanently lock out users as they can become easily a target of denial of service attack unless the usernames are random and kept secret to potential attackers\&.
+.RE
+.PP
+\fBeven_deny_root\fR
+.RS 4
+Root account can become locked as well as regular accounts\&.
+.RE
+.PP
+\fBroot_unlock_time=\fR\fB\fIn\fR\fR
+.RS 4
+This option implies
+\fBeven_deny_root\fR
+option\&. Allow access after
+\fIn\fR
+seconds to root account after the account is locked\&. In case the option is not specified the value is the same as of the
+\fBunlock_time\fR
+option\&.
+.RE
+.PP
+\fBadmin_group=\fR\fB\fIname\fR\fR
+.RS 4
+If a group name is specified with this option, members of the group will be handled by this module the same as the root account (the options
+\fBeven_deny_root\fR
+and
+\fBroot_unlock_time\fR
+will apply to them\&. By default the option is not set\&.
+.RE
+.SH "EXAMPLES"
+.PP
+/etc/security/faillock\&.conf file example:
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+deny=4
+unlock_time=1200
+silent
+    
+.fi
+.if n \{\
+.RE
+.\}
+.SH "FILES"
+.PP
+/etc/security/faillock\&.conf
+.RS 4
+the config file for custom options
+.RE
+.SH "SEE ALSO"
+.PP
+\fBfaillock\fR(8),
+\fBpam_faillock\fR(8),
+\fBpam.conf\fR(5),
+\fBpam.d\fR(5),
+\fBpam\fR(8)
+.SH "AUTHOR"
+.PP
+pam_faillock was written by Tomas Mraz\&. The support for faillock\&.conf was written by Brian Ward\&.
--- /dev/null
+++ b/modules/pam_faillock/faillock.conf.5.xml
@@ -0,0 +1,243 @@
+<?xml version="1.0" encoding='UTF-8'?>
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
+	"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
+
+<refentry id="faillock.conf">
+
+  <refmeta>
+    <refentrytitle>faillock.conf</refentrytitle>
+    <manvolnum>5</manvolnum>
+    <refmiscinfo class="sectdesc">Linux-PAM Manual</refmiscinfo>
+  </refmeta>
+
+  <refnamediv id="faillock.conf-name">
+    <refname>faillock.conf</refname>
+    <refpurpose>pam_faillock configuration file</refpurpose>
+  </refnamediv>
+
+  <refsect1 id="faillock.conf-description">
+
+    <title>DESCRIPTION</title>
+    <para>
+       <emphasis remap='B'>faillock.conf</emphasis> provides a way to configure the
+       default settings for locking the user after multiple failed authentication attempts.
+       This file is read by the <emphasis>pam_faillock</emphasis> module and is the
+       preferred method over configuring <emphasis>pam_faillock</emphasis> directly.
+    </para>
+    <para>
+       The file has a very simple <emphasis>name = value</emphasis> format with possible comments
+       starting with <emphasis>#</emphasis> character. The whitespace at the beginning of line, end
+       of line, and around the <emphasis>=</emphasis> sign is ignored.
+    </para>
+  </refsect1>
+
+  <refsect1 id="faillock.conf-options">
+
+    <title>OPTIONS</title>
+         <variablelist>
+            <varlistentry>
+              <term>
+                <option>dir=<replaceable>/path/to/tally-directory</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  The directory where the user files with the failure records are kept. The
+                  default is <filename>/var/run/faillock</filename>.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>audit</option>
+              </term>
+              <listitem>
+                <para>
+                  Will log the user name into the system log if the user is not found.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>silent</option>
+              </term>
+              <listitem>
+                <para>
+                  Don't print informative messages to the user. Please note that when
+                  this option is not used there will be difference in the authentication
+                  behavior for users which exist on the system and non-existing users.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>no_log_info</option>
+              </term>
+              <listitem>
+                <para>
+                  Don't log informative messages via <citerefentry><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>local_users_only</option>
+              </term>
+              <listitem>
+                <para>
+                  Only track failed user authentications attempts for local users
+                  in /etc/passwd and ignore centralized (AD, IdM, LDAP, etc.) users.
+                  The <citerefentry><refentrytitle>faillock</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+                  command will also no longer track user failed
+                  authentication attempts. Enabling this option will prevent a
+                  double-lockout scenario where a user is locked out locally and
+                  in the centralized mechanism.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>deny=<replaceable>n</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  Deny access if the number of consecutive authentication failures
+                  for this user during the recent interval exceeds
+                  <replaceable>n</replaceable>. The default is 3.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>fail_interval=<replaceable>n</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  The length of the interval during which the consecutive
+                  authentication failures must happen for the user account
+                  lock out is <replaceable>n</replaceable> seconds.
+                  The default is 900 (15 minutes).
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>unlock_time=<replaceable>n</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  The access will be re-enabled after
+                  <replaceable>n</replaceable> seconds after the lock out.
+                  The value 0 has the same meaning as value
+                  <emphasis>never</emphasis> - the access
+                  will not be re-enabled without resetting the faillock
+                  entries by the <citerefentry><refentrytitle>faillock</refentrytitle><manvolnum>8</manvolnum></citerefentry> command.
+                  The default is 600 (10 minutes).
+                </para>
+                <para>
+                  Note that the default directory that <emphasis>pam_faillock</emphasis>
+                  uses is usually cleared on system boot so the access will be also re-enabled
+                  after system reboot. If that is undesirable a different tally directory
+                  must be set with the <option>dir</option> option.
+                </para>
+                <para>
+                  Also note that it is usually undesirable to permanently lock
+                  out users as they can become easily a target of denial of service
+                  attack unless the usernames are random and kept secret to potential
+                  attackers.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>even_deny_root</option>
+              </term>
+              <listitem>
+                <para>
+                  Root account can become locked as well as regular accounts.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>root_unlock_time=<replaceable>n</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  This option implies <option>even_deny_root</option> option.
+                  Allow access after <replaceable>n</replaceable> seconds
+                  to root account after the account is locked. In case the
+                  option is not specified the value is the same as of the
+                  <option>unlock_time</option> option.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+              <term>
+                <option>admin_group=<replaceable>name</replaceable></option>
+              </term>
+              <listitem>
+                <para>
+                  If a group name is specified with this option, members
+                  of the group will be handled by this module the same as
+                  the root account (the options <option>even_deny_root</option>
+                  and <option>root_unlock_time</option> will apply to them.
+                  By default the option is not set.
+                </para>
+              </listitem>
+            </varlistentry>
+        </variablelist>
+  </refsect1>
+
+  <refsect1 id='faillock.conf-examples'>
+    <title>EXAMPLES</title>
+    <para>
+      /etc/security/faillock.conf file example:
+    </para>
+    <programlisting>
+deny=4
+unlock_time=1200
+silent
+    </programlisting>
+  </refsect1>
+
+  <refsect1 id="faillock.conf-files">
+    <title>FILES</title>
+    <variablelist>
+      <varlistentry>
+        <term><filename>/etc/security/faillock.conf</filename></term>
+        <listitem>
+          <para>the config file for custom options</para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </refsect1>
+
+  <refsect1 id='faillock.conf-see_also'>
+    <title>SEE ALSO</title>
+    <para>
+      <citerefentry>
+        <refentrytitle>faillock</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam_faillock</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam.conf</refentrytitle><manvolnum>5</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam.d</refentrytitle><manvolnum>5</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>
+    </para>
+  </refsect1>
+
+  <refsect1 id='faillock.conf-author'>
+    <title>AUTHOR</title>
+      <para>
+        pam_faillock was written by Tomas Mraz. The support for faillock.conf was written by Brian Ward.
+      </para>
+  </refsect1>
+
+</refentry>
--- /dev/null
+++ b/modules/pam_faillock/faillock.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2010 Tomas Mraz <tmraz@redhat.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, and the entire permission notice in its entirety,
+ *    including the disclaimer of warranties.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * ALTERNATIVELY, this product may be distributed under the terms of
+ * the GNU Public License, in which case the provisions of the GPL are
+ * required INSTEAD OF the above restrictions.  (This clause is
+ * necessary due to a potential bad interaction between the GPL and
+ * the restrictions contained in a BSD-style copyright.)
+ *
+ * THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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.
+ */
+
+/*
+ * faillock.h - authentication failure data file record structure
+ *
+ * Each record in the file represents an instance of login failure of
+ * the user at the recorded time.
+ */
+
+
+#ifndef _FAILLOCK_H
+#define _FAILLOCK_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#define TALLY_STATUS_VALID     0x1       /* the tally file entry is valid */
+#define TALLY_STATUS_RHOST     0x2       /* the source is rhost */
+#define TALLY_STATUS_TTY       0x4       /* the source is tty */
+/* If neither TALLY_FLAG_RHOST nor TALLY_FLAG_TTY are set the source is service. */
+
+struct	tally {
+	char		source[52];	/* rhost or tty of the login failure */
+					/* (not necessarily NULL terminated) */
+	uint16_t	reserved;	/* reserved for future use */
+	uint16_t	status;		/* record status  */
+	uint64_t	time;		/* time of the login failure */
+};
+/* 64 bytes per entry */
+
+struct tally_data {
+	struct tally *records;		/* array of tallies */
+	unsigned int count;		/* number of records */
+};
+
+#define FAILLOCK_DEFAULT_TALLYDIR "/var/run/faillock"
+#define FAILLOCK_DEFAULT_CONF "/etc/security/faillock.conf"
+
+/*
+ * Evaluates to
+ * - a syntax error if the argument is 0,
+ * 0, otherwise.
+ */
+#define PAM_FAIL_BUILD_ON_ZERO(e_)	(sizeof(int[-1 + 2 * !!(e_)]) * 0)
+
+/*
+ * Evaluates to
+ * 1, if the given two types are known to be the same
+ * 0, otherwise.
+ */
+# define PAM_IS_SAME_TYPE(x_, y_)					\
+	__builtin_types_compatible_p(__typeof__(x_), __typeof__(y_))
+
+/*
+ * Evaluates to
+ * 1, if the given type is known to be a non-array type
+ * 0, otherwise.
+ */
+#define PAM_IS_NOT_ARRAY(a_)		PAM_IS_SAME_TYPE((a_), &(a_)[0])
+
+/*
+ * Evaluates to
+ * - a syntax error if the argument is not an array,
+ * 0, otherwise.
+ */
+#define PAM_MUST_BE_ARRAY(a_)		PAM_FAIL_BUILD_ON_ZERO(!PAM_IS_NOT_ARRAY(a_))
+/*
+ * Returns NULL if STR does not start with PREFIX,
+ * or a pointer to the first char in STR after PREFIX.
+ * The length of PREFIX is specified by PREFIX_LEN.
+ */
+static inline const char *
+pam_str_skip_prefix_len(const char *str, const char *prefix, size_t prefix_len)
+{
+	return strncmp(str, prefix, prefix_len) ? NULL : str + prefix_len;
+}
+
+#define pam_str_skip_prefix(str_, prefix_)	\
+	pam_str_skip_prefix_len((str_), (prefix_), sizeof(prefix_) - 1 + PAM_MUST_BE_ARRAY(prefix_))
+
+int open_tally(const char *dir, const char *user, uid_t uid, int create);
+int read_tally(int fd, struct tally_data *tallies);
+int update_tally(int fd, struct tally_data *tallies);
+#endif
--- /dev/null
+++ b/modules/pam_faillock/main.c
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2010 Tomas Mraz <tmraz@redhat.com>
+ * Copyright (c) 2010 Red Hat, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, and the entire permission notice in its entirety,
+ *    including the disclaimer of warranties.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * ALTERNATIVELY, this product may be distributed under the terms of
+ * the GNU Public License, in which case the provisions of the GPL are
+ * required INSTEAD OF the above restrictions.  (This clause is
+ * necessary due to a potential bad interaction between the GPL and
+ * the restrictions contained in a BSD-style copyright.)
+ *
+ * THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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 "config.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dirent.h>
+#include <errno.h>
+#include <pwd.h>
+#include <time.h>
+#include <sys/types.h>
+#include <unistd.h>
+#ifdef HAVE_LIBAUDIT
+#include <libaudit.h>
+
+#define AUDIT_NO_ID     ((unsigned int) -1)
+#endif
+
+#include "faillock.h"
+
+struct options {
+	unsigned int reset;
+	const char *dir;
+	const char *user;
+	const char *progname;
+};
+
+static int
+args_parse(int argc, char **argv, struct options *opts)
+{
+	int i;
+	memset(opts, 0, sizeof(*opts));
+
+	opts->dir = FAILLOCK_DEFAULT_TALLYDIR;
+	opts->progname = argv[0];
+
+	for (i = 1; i < argc; ++i) {
+
+		if (strcmp(argv[i], "--dir") == 0) {
+			++i;
+			if (i >= argc || strlen(argv[i]) == 0) {
+				fprintf(stderr, "%s: No directory supplied.\n", argv[0]);
+				return -1;
+			}
+		        opts->dir = argv[i];
+		}
+		else if (strcmp(argv[i], "--user") == 0) {
+			++i;
+			if (i >= argc || strlen(argv[i]) == 0) {
+				fprintf(stderr, "%s: No user name supplied.\n", argv[0]);
+				return -1;
+			}
+		        opts->user = argv[i];
+		}
+		else if (strcmp(argv[i], "--reset") == 0) {
+			opts->reset = 1;
+		}
+		else {
+			fprintf(stderr, "%s: Unknown option: %s\n", argv[0], argv[i]);
+			return -1;
+		}
+	}
+	return 0;
+}
+
+static void
+usage(const char *progname)
+{
+	fprintf(stderr, _("Usage: %s [--dir /path/to/tally-directory] [--user username] [--reset]\n"),
+		progname);
+}
+
+static int
+do_user(struct options *opts, const char *user)
+{
+	int fd;
+	int rv;
+	struct tally_data tallies;
+	struct passwd *pwd;
+
+	pwd = getpwnam(user);
+
+	fd = open_tally(opts->dir, user, pwd != NULL ? pwd->pw_uid : 0, 0);
+
+	if (fd == -1) {
+		if (errno == ENOENT) {
+			return 0;
+		}
+		else {
+			fprintf(stderr, "%s: Error opening the tally file for %s:",
+				opts->progname, user);
+			perror(NULL);
+			return 3;
+		}
+	}
+	if (opts->reset) {
+#ifdef HAVE_LIBAUDIT
+		int audit_fd;
+#endif
+
+		while ((rv=ftruncate(fd, 0)) == -1 && errno == EINTR);
+		if (rv == -1) {
+			fprintf(stderr, "%s: Error clearing the tally file for %s:",
+				opts->progname, user);
+			perror(NULL);
+#ifdef HAVE_LIBAUDIT
+		}
+		if ((audit_fd=audit_open()) >= 0) {
+			audit_log_acct_message(audit_fd, AUDIT_USER_MGMT, NULL,
+				"faillock-reset", user,
+				pwd != NULL ? pwd->pw_uid : AUDIT_NO_ID,
+				NULL, NULL, NULL, rv == 0);
+			close(audit_fd);
+		}
+		if (rv == -1) {
+#endif
+			close(fd);
+			return 4;
+		}
+	}
+	else {
+		unsigned int i;
+
+		memset(&tallies, 0, sizeof(tallies));
+		if ((rv=read_tally(fd, &tallies)) == -1) {
+			fprintf(stderr, "%s: Error reading the tally file for %s:",
+				opts->progname, user);
+			perror(NULL);
+			close(fd);
+			return 5;
+		}
+
+		printf("%s:\n", user);
+		printf("%-19s %-5s %-48s %-5s\n", "When", "Type", "Source", "Valid");
+
+		for (i = 0; i < tallies.count; i++) {
+			struct tm *tm;
+			char timebuf[80];
+			uint16_t status = tallies.records[i].status;
+			time_t when = tallies.records[i].time;
+
+			tm = localtime(&when);
+			strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", tm);
+			printf("%-19s %-5s %-52.52s %s\n", timebuf,
+				status & TALLY_STATUS_RHOST ? "RHOST" : (status & TALLY_STATUS_TTY ? "TTY" : "SVC"),
+				tallies.records[i].source, status & TALLY_STATUS_VALID ? "V":"I");
+		}
+		free(tallies.records);
+	}
+	close(fd);
+	return 0;
+}
+
+static int
+do_allusers(struct options *opts)
+{
+	struct dirent **userlist;
+	int rv, i;
+
+	rv = scandir(opts->dir, &userlist, NULL, alphasort);
+	if (rv < 0) {
+		fprintf(stderr, "%s: Error reading tally directory: %m\n", opts->progname);
+		return 2;
+	}
+
+	for (i = 0; i < rv; i++) {
+		if (userlist[i]->d_name[0] == '.') {
+			if ((userlist[i]->d_name[1] == '.' && userlist[i]->d_name[2] == '\0') ||
+			    userlist[i]->d_name[1] == '\0')
+				continue;
+		}
+		do_user(opts, userlist[i]->d_name);
+		free(userlist[i]);
+	}
+	free(userlist);
+
+	return 0;
+}
+
+
+/*-----------------------------------------------------------------------*/
+int
+main (int argc, char *argv[])
+{
+	struct options opts;
+
+	if (args_parse(argc, argv, &opts)) {
+		usage(argv[0]);
+		return 1;
+	}
+
+	if (opts.user == NULL) {
+		return do_allusers(&opts);
+	}
+
+	return do_user(&opts, opts.user);
+}
--- /dev/null
+++ b/modules/pam_faillock/pam_faillock.8
@@ -0,0 +1,262 @@
+'\" t
+.\"     Title: pam_faillock
+.\"    Author: [see the "AUTHOR" section]
+.\" Generator: DocBook XSL Stylesheets v1.79.1 <http://docbook.sf.net/>
+.\"      Date: 06/08/2020
+.\"    Manual: Linux-PAM Manual
+.\"    Source: Linux-PAM Manual
+.\"  Language: English
+.\"
+.TH "PAM_FAILLOCK" "8" "06/08/2020" "Linux-PAM Manual" "Linux\-PAM Manual"
+.\" -----------------------------------------------------------------
+.\" * Define some portability stuff
+.\" -----------------------------------------------------------------
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" http://bugs.debian.org/507673
+.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.ie \n(.g .ds Aq \(aq
+.el       .ds Aq '
+.\" -----------------------------------------------------------------
+.\" * set default formatting
+.\" -----------------------------------------------------------------
+.\" disable hyphenation
+.nh
+.\" disable justification (adjust text to left margin only)
+.ad l
+.\" -----------------------------------------------------------------
+.\" * MAIN CONTENT STARTS HERE *
+.\" -----------------------------------------------------------------
+.SH "NAME"
+pam_faillock \- Module counting authentication failures during a specified interval
+.SH "SYNOPSIS"
+.HP \w'\fBauth\ \&.\&.\&.\ pam_faillock\&.so\fR\ 'u
+\fBauth \&.\&.\&. pam_faillock\&.so\fR {preauth|authfail|authsucc} [conf=\fI/path/to/config\-file\fR] [dir=\fI/path/to/tally\-directory\fR] [even_deny_root] [deny=\fIn\fR] [fail_interval=\fIn\fR] [unlock_time=\fIn\fR] [root_unlock_time=\fIn\fR] [admin_group=\fIname\fR] [audit] [silent] [no_log_info]
+.HP \w'\fBaccount\ \&.\&.\&.\ pam_faillock\&.so\fR\ 'u
+\fBaccount \&.\&.\&. pam_faillock\&.so\fR [dir=\fI/path/to/tally\-directory\fR] [no_log_info]
+.SH "DESCRIPTION"
+.PP
+This module maintains a list of failed authentication attempts per user during a specified interval and locks the account in case there were more than
+\fIdeny\fR
+consecutive failed authentications\&.
+.PP
+Normally, failed attempts to authenticate
+\fIroot\fR
+will
+\fBnot\fR
+cause the root account to become blocked, to prevent denial\-of\-service: if your users aren\*(Aqt given shell accounts and root may only login via
+\fBsu\fR
+or at the machine console (not telnet/rsh, etc), this is safe\&.
+.SH "OPTIONS"
+.PP
+\fB{preauth|authfail|authsucc}\fR
+.RS 4
+This argument must be set accordingly to the position of this module instance in the PAM stack\&.
+.sp
+The
+\fIpreauth\fR
+argument must be used when the module is called before the modules which ask for the user credentials such as the password\&. The module just examines whether the user should be blocked from accessing the service in case there were anomalous number of failed consecutive authentication attempts recently\&. This call is optional if
+\fIauthsucc\fR
+is used\&.
+.sp
+The
+\fIauthfail\fR
+argument must be used when the module is called after the modules which determine the authentication outcome, failed\&. Unless the user is already blocked due to previous authentication failures, the module will record the failure into the appropriate user tally file\&.
+.sp
+The
+\fIauthsucc\fR
+argument must be used when the module is called after the modules which determine the authentication outcome, succeeded\&. Unless the user is already blocked due to previous authentication failures, the module will then clear the record of the failures in the respective user tally file\&. Otherwise it will return authentication error\&. If this call is not done, the pam_faillock will not distinguish between consecutive and non\-consecutive failed authentication attempts\&. The
+\fIpreauth\fR
+call must be used in such case\&. Due to complications in the way the PAM stack can be configured it is also possible to call
+\fIpam_faillock\fR
+as an account module\&. In such configuration the module must be also called in the
+\fIpreauth\fR
+stage\&.
+.RE
+.PP
+\fBconf=/path/to/config\-file\fR
+.RS 4
+Use another configuration file instead of the default
+/etc/security/faillock\&.conf\&.
+.RE
+.PP
+The options for configuring the module behavior are described in the
+\fBfaillock.conf\fR(5)
+manual page\&. The options specified on the module command line override the values from the configuration file\&.
+.SH "MODULE TYPES PROVIDED"
+.PP
+The
+\fBauth\fR
+and
+\fBaccount\fR
+module types are provided\&.
+.SH "RETURN VALUES"
+.PP
+PAM_AUTH_ERR
+.RS 4
+An invalid option was given, the module was not able to retrieve the user name, no valid counter file was found, or too many failed logins\&.
+.RE
+.PP
+PAM_BUF_ERR
+.RS 4
+Memory buffer error\&.
+.RE
+.PP
+PAM_CONV_ERR
+.RS 4
+The conversation method supplied by the application failed to obtain the username\&.
+.RE
+.PP
+PAM_INCOMPLETE
+.RS 4
+The conversation method supplied by the application returned PAM_CONV_AGAIN\&.
+.RE
+.PP
+PAM_SUCCESS
+.RS 4
+Everything was successful\&.
+.RE
+.PP
+PAM_IGNORE
+.RS 4
+User not present in passwd database\&.
+.RE
+.SH "NOTES"
+.PP
+Configuring options on the module command line is not recommend\&. The
+/etc/security/faillock\&.conf
+should be used instead\&.
+.PP
+The setup of
+\fIpam_faillock\fR
+in the PAM stack is different from the
+\fIpam_tally2\fR
+module setup\&.
+.PP
+Individual files with the failure records are created as owned by the user\&. This allows
+\fBpam_faillock\&.so\fR
+module to work correctly when it is called from a screensaver\&.
+.PP
+Note that using the module in
+\fBpreauth\fR
+without the
+\fBsilent\fR
+option specified in
+/etc/security/faillock\&.conf
+or with
+\fIrequisite\fR
+control field leaks an information about existence or non\-existence of an user account in the system because the failures are not recorded for the unknown users\&. The message about the user account being locked is never displayed for non\-existing user accounts allowing the adversary to infer that a particular account is not existing on a system\&.
+.SH "EXAMPLES"
+.PP
+Here are two possible configuration examples for
+/etc/pam\&.d/login\&. They make
+\fIpam_faillock\fR
+to lock the account after 4 consecutive failed logins during the default interval of 15 minutes\&. Root account will be locked as well\&. The accounts will be automatically unlocked after 20 minutes\&.
+.PP
+In the first example the module is called only in the
+\fIauth\fR
+phase and the module does not print any information about the account being blocked by
+\fIpam_faillock\fR\&. The
+\fIpreauth\fR
+call can be added to tell users that their logins are blocked by the module and also to abort the authentication without even asking for password in such case\&.
+.PP
+/etc/security/faillock\&.conf
+file example:
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+deny=4
+unlock_time=1200
+silent
+    
+.fi
+.if n \{\
+.RE
+.\}
+.PP
+/etc/pam\&.d/config file example:
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+auth     required       pam_securetty\&.so
+auth     required       pam_env\&.so
+auth     required       pam_nologin\&.so
+# optionally call: auth requisite pam_faillock\&.so preauth
+# to display the message about account being locked
+auth     [success=1 default=bad] pam_unix\&.so
+auth     [default=die]  pam_faillock\&.so authfail
+auth     sufficient     pam_faillock\&.so authsucc
+auth     required       pam_deny\&.so
+account  required       pam_unix\&.so
+password required       pam_unix\&.so shadow
+session  required       pam_selinux\&.so close
+session  required       pam_loginuid\&.so
+session  required       pam_unix\&.so
+session  required       pam_selinux\&.so open
+    
+.fi
+.if n \{\
+.RE
+.\}
+.PP
+In the second example the module is called both in the
+\fIauth\fR
+and
+\fIaccount\fR
+phases and the module informs the authenticating user when the account is locked if
+\fBsilent\fR
+option is not specified in the
+faillock\&.conf\&.
+.sp
+.if n \{\
+.RS 4
+.\}
+.nf
+auth     required       pam_securetty\&.so
+auth     required       pam_env\&.so
+auth     required       pam_nologin\&.so
+auth     required       pam_faillock\&.so preauth
+# optionally use requisite above if you do not want to prompt for the password
+# on locked accounts
+auth     sufficient     pam_unix\&.so
+auth     [default=die]  pam_faillock\&.so authfail
+auth     required       pam_deny\&.so
+account  required       pam_faillock\&.so
+# if you drop the above call to pam_faillock\&.so the lock will be done also
+# on non\-consecutive authentication failures
+account  required       pam_unix\&.so
+password required       pam_unix\&.so shadow
+session  required       pam_selinux\&.so close
+session  required       pam_loginuid\&.so
+session  required       pam_unix\&.so
+session  required       pam_selinux\&.so open
+    
+.fi
+.if n \{\
+.RE
+.\}
+.SH "FILES"
+.PP
+/var/run/faillock/*
+.RS 4
+the files logging the authentication failures for users
+.RE
+.PP
+/etc/security/faillock\&.conf
+.RS 4
+the config file for pam_faillock options
+.RE
+.SH "SEE ALSO"
+.PP
+\fBfaillock\fR(8),
+\fBfaillock.conf\fR(5),
+\fBpam.conf\fR(5),
+\fBpam.d\fR(5),
+\fBpam\fR(8)
+.SH "AUTHOR"
+.PP
+pam_faillock was written by Tomas Mraz\&.
--- /dev/null
+++ b/modules/pam_faillock/pam_faillock.8.xml
@@ -0,0 +1,362 @@
+<?xml version="1.0" encoding='UTF-8'?>
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
+	"http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd">
+
+<refentry id="pam_faillock">
+
+  <refmeta>
+    <refentrytitle>pam_faillock</refentrytitle>
+    <manvolnum>8</manvolnum>
+    <refmiscinfo class="sectdesc">Linux-PAM Manual</refmiscinfo>
+  </refmeta>
+
+  <refnamediv id="pam_faillock-name">
+    <refname>pam_faillock</refname>
+    <refpurpose>Module counting authentication failures during a specified interval</refpurpose>
+  </refnamediv>
+
+  <refsynopsisdiv>
+    <cmdsynopsis id="pam_faillock-cmdsynopsisauth">
+      <command>auth ... pam_faillock.so</command>
+      <arg choice="req">
+        preauth|authfail|authsucc
+      </arg>
+      <arg choice="opt">
+        conf=<replaceable>/path/to/config-file</replaceable>
+      </arg>
+      <arg choice="opt">
+        dir=<replaceable>/path/to/tally-directory</replaceable>
+      </arg>
+      <arg choice="opt">
+        even_deny_root
+      </arg>
+      <arg choice="opt">
+        deny=<replaceable>n</replaceable>
+      </arg>
+      <arg choice="opt">
+        fail_interval=<replaceable>n</replaceable>
+      </arg>
+      <arg choice="opt">
+        unlock_time=<replaceable>n</replaceable>
+      </arg>
+      <arg choice="opt">
+        root_unlock_time=<replaceable>n</replaceable>
+      </arg>
+      <arg choice="opt">
+        admin_group=<replaceable>name</replaceable>
+      </arg>
+      <arg choice="opt">
+        audit
+      </arg>
+      <arg choice="opt">
+        silent
+      </arg>
+      <arg choice="opt">
+        no_log_info
+      </arg>
+    </cmdsynopsis>
+    <cmdsynopsis id="pam_faillock-cmdsynopsisacct">
+      <command>account ... pam_faillock.so</command>
+      <arg choice="opt">
+        dir=<replaceable>/path/to/tally-directory</replaceable>
+      </arg>
+      <arg choice="opt">
+        no_log_info
+      </arg>
+    </cmdsynopsis>
+  </refsynopsisdiv>
+
+  <refsect1 id="pam_faillock-description">
+
+    <title>DESCRIPTION</title>
+
+    <para>
+      This module maintains a list of failed authentication attempts per
+      user during a specified interval and locks the account in case
+      there were more than <replaceable>deny</replaceable> consecutive
+      failed authentications.
+    </para>
+    <para>
+      Normally, failed attempts to authenticate <emphasis>root</emphasis> will
+      <emphasis remap='B'>not</emphasis> cause the root account to become
+      blocked, to prevent denial-of-service: if your users aren't given
+      shell accounts and root may only login via <command>su</command> or
+      at the machine console (not telnet/rsh, etc), this is safe.
+    </para>
+  </refsect1>
+
+  <refsect1 id="pam_faillock-options">
+
+    <title>OPTIONS</title>
+        <variablelist>
+            <varlistentry>
+              <term>
+                <option>{preauth|authfail|authsucc}</option>
+              </term>
+              <listitem>
+                <para>
+                  This argument must be set accordingly to the position of this module
+                  instance in the PAM stack.
+                </para>
+                <para>
+                  The <emphasis>preauth</emphasis> argument must be used when the module
+                  is called before the modules which ask for the user credentials such
+                  as the password. The module just examines whether the user should
+                  be blocked from accessing the service in case there were anomalous
+                  number of failed consecutive authentication attempts recently. This
+                  call is optional if <emphasis>authsucc</emphasis> is used.
+                </para>
+                <para>
+                  The <emphasis>authfail</emphasis> argument must be used when the module
+                  is called after the modules which determine the authentication outcome,
+                  failed. Unless the user is already blocked due to previous authentication
+                  failures, the module will record the failure into the appropriate user
+                  tally file.
+                </para>
+                <para>
+                  The <emphasis>authsucc</emphasis> argument must be used when the module
+                  is called after the modules which determine the authentication outcome,
+                  succeeded. Unless the user is already blocked due to previous authentication
+                  failures, the module will then clear the record of the failures in the
+                  respective user tally file. Otherwise it will return authentication error.
+                  If this call is not done, the pam_faillock will not distinguish between
+                  consecutive and non-consecutive failed authentication attempts. The
+                  <emphasis>preauth</emphasis> call must be used in such case. Due to
+                  complications in the way the PAM stack can be configured it is also
+                  possible to call <emphasis>pam_faillock</emphasis> as an account module.
+                  In such configuration the module must be also called in the
+                  <emphasis>preauth</emphasis> stage.
+                </para>
+              </listitem>
+            </varlistentry>
+            <varlistentry>
+               <term>
+                 <option>conf=/path/to/config-file</option>
+               </term>
+               <listitem>
+                 <para>
+                   Use another configuration file instead of the default
+                   <filename>/etc/security/faillock.conf</filename>.
+                 </para>
+               </listitem>
+            </varlistentry>
+        </variablelist>
+        <para>
+          The options for configuring the module behavior are described in the
+          <citerefentry><refentrytitle>faillock.conf</refentrytitle><manvolnum>5</manvolnum>
+          </citerefentry> manual page. The options specified on the module command
+          line override the values from the configuration file.
+        </para>
+  </refsect1>
+
+  <refsect1 id="pam_faillock-types">
+    <title>MODULE TYPES PROVIDED</title>
+    <para>
+      The <option>auth</option> and <option>account</option> module types are
+      provided.
+    </para>
+  </refsect1>
+
+  <refsect1 id='pam_faillock-return_values'>
+    <title>RETURN VALUES</title>
+    <variablelist>
+      <varlistentry>
+        <term>PAM_AUTH_ERR</term>
+        <listitem>
+          <para>
+            An invalid option was given, the module was not able
+            to retrieve the user name, no valid counter file
+            was found, or too many failed logins.
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>PAM_BUF_ERR</term>
+        <listitem>
+          <para>
+            Memory buffer error.
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>PAM_CONV_ERR</term>
+        <listitem>
+          <para>
+            The conversation method supplied by the application
+            failed to obtain the username.
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>PAM_INCOMPLETE</term>
+        <listitem>
+          <para>
+            The conversation method supplied by the application
+            returned PAM_CONV_AGAIN.
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>PAM_SUCCESS</term>
+        <listitem>
+          <para>
+            Everything was successful.
+          </para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term>PAM_IGNORE</term>
+        <listitem>
+          <para>
+            User not present in passwd database.
+          </para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </refsect1>
+
+  <refsect1 id='pam_faillock-notes'>
+    <title>NOTES</title>
+    <para>
+      Configuring options on the module command line is not recommend. The
+      <filename>/etc/security/faillock.conf</filename> should be used instead.
+    </para>
+    <para>
+      The setup of <emphasis>pam_faillock</emphasis> in the PAM stack is different
+      from the <emphasis>pam_tally2</emphasis> module setup.
+    </para>
+    <para>
+      Individual files with the failure records are created as owned by
+      the user. This allows <emphasis remap='B'>pam_faillock.so</emphasis> module
+      to work correctly when it is called from a screensaver.
+    </para>
+    <para>
+      Note that using the module in <option>preauth</option> without the
+      <option>silent</option> option specified in <filename>/etc/security/faillock.conf</filename>
+      or with <emphasis>requisite</emphasis> control field leaks an information about
+      existence or non-existence of an user account in the system because
+      the failures are not recorded for the unknown users. The message
+      about the user account being locked is never displayed for non-existing
+      user accounts allowing the adversary to infer that a particular account
+      is not existing on a system.
+    </para>
+  </refsect1>
+
+  <refsect1 id='pam_faillock-examples'>
+    <title>EXAMPLES</title>
+    <para>
+      Here are two possible configuration examples for <filename>/etc/pam.d/login</filename>.
+      They make <emphasis>pam_faillock</emphasis> to lock the account after 4 consecutive
+      failed logins during the default interval of 15 minutes. Root account will be locked
+      as well. The accounts will be automatically unlocked after 20 minutes.
+    </para>
+    <para>
+      In the first example the module is called only in the <emphasis>auth</emphasis>
+      phase and the module does not print any information about the account being blocked
+      by <emphasis>pam_faillock</emphasis>. The <emphasis>preauth</emphasis> call can
+      be added to tell users that their logins are blocked by the module and also to abort
+      the authentication without even asking for password in such case.
+    </para>
+    <para>
+      <filename>/etc/security/faillock.conf</filename> file example:
+    </para>
+    <programlisting>
+deny=4
+unlock_time=1200
+silent
+    </programlisting>
+    <para>
+      /etc/pam.d/config file example:
+    </para>
+    <programlisting>
+auth     required       pam_securetty.so
+auth     required       pam_env.so
+auth     required       pam_nologin.so
+# optionally call: auth requisite pam_faillock.so preauth
+# to display the message about account being locked
+auth     [success=1 default=bad] pam_unix.so
+auth     [default=die]  pam_faillock.so authfail
+auth     sufficient     pam_faillock.so authsucc
+auth     required       pam_deny.so
+account  required       pam_unix.so
+password required       pam_unix.so shadow
+session  required       pam_selinux.so close
+session  required       pam_loginuid.so
+session  required       pam_unix.so
+session  required       pam_selinux.so open
+    </programlisting>
+    <para>
+      In the second example the module is called both in the <emphasis>auth</emphasis>
+      and <emphasis>account</emphasis> phases and the module informs the authenticating
+      user when the account is locked if <option>silent</option> option is not
+      specified in the <filename>faillock.conf</filename>.
+    </para>
+    <programlisting>
+auth     required       pam_securetty.so
+auth     required       pam_env.so
+auth     required       pam_nologin.so
+auth     required       pam_faillock.so preauth
+# optionally use requisite above if you do not want to prompt for the password
+# on locked accounts
+auth     sufficient     pam_unix.so
+auth     [default=die]  pam_faillock.so authfail
+auth     required       pam_deny.so
+account  required       pam_faillock.so
+# if you drop the above call to pam_faillock.so the lock will be done also
+# on non-consecutive authentication failures
+account  required       pam_unix.so
+password required       pam_unix.so shadow
+session  required       pam_selinux.so close
+session  required       pam_loginuid.so
+session  required       pam_unix.so
+session  required       pam_selinux.so open
+    </programlisting>
+  </refsect1>
+
+  <refsect1 id="pam_faillock-files">
+    <title>FILES</title>
+    <variablelist>
+      <varlistentry>
+        <term><filename>/var/run/faillock/*</filename></term>
+        <listitem>
+          <para>the files logging the authentication failures for users</para>
+        </listitem>
+      </varlistentry>
+      <varlistentry>
+        <term><filename>/etc/security/faillock.conf</filename></term>
+        <listitem>
+          <para>the config file for pam_faillock options</para>
+        </listitem>
+      </varlistentry>
+    </variablelist>
+  </refsect1>
+
+  <refsect1 id='pam_faillock-see_also'>
+    <title>SEE ALSO</title>
+    <para>
+      <citerefentry>
+        <refentrytitle>faillock</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>faillock.conf</refentrytitle><manvolnum>5</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam.conf</refentrytitle><manvolnum>5</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam.d</refentrytitle><manvolnum>5</manvolnum>
+      </citerefentry>,
+      <citerefentry>
+        <refentrytitle>pam</refentrytitle><manvolnum>8</manvolnum>
+      </citerefentry>
+    </para>
+  </refsect1>
+
+  <refsect1 id='pam_faillock-author'>
+    <title>AUTHOR</title>
+      <para>
+        pam_faillock was written by Tomas Mraz.
+      </para>
+  </refsect1>
+
+</refentry>
--- /dev/null
+++ b/modules/pam_faillock/pam_faillock.c
@@ -0,0 +1,774 @@
+/*
+ * Copyright (c) 2010, 2017, 2019 Tomas Mraz <tmraz@redhat.com>
+ * Copyright (c) 2010, 2017, 2019 Red Hat, Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, and the entire permission notice in its entirety,
+ *    including the disclaimer of warranties.
+ * 2. 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.
+ * 3. The name of the author may not be used to endorse or promote
+ *    products derived from this software without specific prior
+ *    written permission.
+ *
+ * ALTERNATIVELY, this product may be distributed under the terms of
+ * the GNU Public License, in which case the provisions of the GPL are
+ * required INSTEAD OF the above restrictions.  (This clause is
+ * necessary due to a potential bad interaction between the GPL and
+ * the restrictions contained in a BSD-style copyright.)
+ *
+ * THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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 "config.h"
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <time.h>
+#include <pwd.h>
+#include <syslog.h>
+#include <ctype.h>
+
+#ifdef HAVE_LIBAUDIT
+#include <libaudit.h>
+#endif
+
+#include <security/pam_modules.h>
+#include <security/pam_modutil.h>
+#include <security/pam_ext.h>
+
+#include "faillock.h"
+
+#define FAILLOCK_ACTION_PREAUTH  0
+#define FAILLOCK_ACTION_AUTHSUCC 1
+#define FAILLOCK_ACTION_AUTHFAIL 2
+
+#define FAILLOCK_FLAG_DENY_ROOT		0x1
+#define FAILLOCK_FLAG_AUDIT		0x2
+#define FAILLOCK_FLAG_SILENT		0x4
+#define FAILLOCK_FLAG_NO_LOG_INFO	0x8
+#define FAILLOCK_FLAG_UNLOCKED		0x10
+#define FAILLOCK_FLAG_LOCAL_ONLY	0x20
+
+#define MAX_TIME_INTERVAL 604800 /* 7 days */
+#define FAILLOCK_CONF_MAX_LINELEN 1023
+
+#define PATH_PASSWD "/etc/passwd"
+
+static const char default_faillock_conf[] = FAILLOCK_DEFAULT_CONF;
+
+struct options {
+	unsigned int action;
+	unsigned int flags;
+	unsigned short deny;
+	unsigned int fail_interval;
+	unsigned int unlock_time;
+	unsigned int root_unlock_time;
+	char *dir;
+	const char *user;
+	char *admin_group;
+	int failures;
+	uint64_t latest_time;
+	uid_t uid;
+	int is_admin;
+	uint64_t now;
+	int fatal_error;
+};
+
+static int read_config_file(
+	pam_handle_t *pamh,
+	struct options *opts,
+	const char *cfgfile
+);
+
+static void set_conf_opt(
+	pam_handle_t *pamh,
+	struct options *opts,
+	const char *name,
+	const char *value
+);
+
+static int
+args_parse(pam_handle_t *pamh, int argc, const char **argv,
+		int flags, struct options *opts)
+{
+	int i;
+	int rv;
+	const char *conf = default_faillock_conf;
+
+	memset(opts, 0, sizeof(*opts));
+
+	opts->dir = strdup(FAILLOCK_DEFAULT_TALLYDIR);
+	opts->deny = 3;
+	opts->fail_interval = 900;
+	opts->unlock_time = 600;
+	opts->root_unlock_time = MAX_TIME_INTERVAL+1;
+
+	for (i = 0; i < argc; ++i) {
+		const char *str;
+
+		if ((str = pam_str_skip_prefix(argv[i], "conf=")) != NULL)
+			conf = str;
+	}
+
+	if ((rv = read_config_file(pamh, opts, conf)) != PAM_SUCCESS) {
+		pam_syslog(pamh, LOG_ERR,
+					"Configuration file missing or broken");
+		return rv;
+	}
+
+	for (i = 0; i < argc; ++i) {
+		if (strcmp(argv[i], "preauth") == 0) {
+			opts->action = FAILLOCK_ACTION_PREAUTH;
+		}
+		else if (strcmp(argv[i], "authfail") == 0) {
+			opts->action = FAILLOCK_ACTION_AUTHFAIL;
+		}
+		else if (strcmp(argv[i], "authsucc") == 0) {
+			opts->action = FAILLOCK_ACTION_AUTHSUCC;
+		}
+		else {
+			char buf[FAILLOCK_CONF_MAX_LINELEN + 1];
+			char *val;
+
+			strncpy(buf, argv[i], sizeof(buf) - 1);
+			buf[sizeof(buf) - 1] = '\0';
+
+			val = strchr(buf, '=');
+			if (val != NULL) {
+				*val = '\0';
+				++val;
+			}
+			else {
+				val = buf + sizeof(buf) - 1;
+			}
+			set_conf_opt(pamh, opts, buf, val);
+		}
+	}
+
+	if (opts->root_unlock_time == MAX_TIME_INTERVAL+1)
+		opts->root_unlock_time = opts->unlock_time;
+	if (flags & PAM_SILENT)
+		opts->flags |= FAILLOCK_FLAG_SILENT;
+
+	if (opts->dir == NULL) {
+		pam_syslog(pamh, LOG_CRIT, "Error allocating memory: %m");
+		opts->fatal_error = 1;
+	}
+
+	if (opts->fatal_error)
+		return PAM_BUF_ERR;
+	return PAM_SUCCESS;
+}
+
+/* parse a single configuration file */
+static int
+read_config_file(pam_handle_t *pamh, struct options *opts, const char *cfgfile)
+{
+	FILE *f;
+	char linebuf[FAILLOCK_CONF_MAX_LINELEN+1];
+
+	f = fopen(cfgfile, "r");
+	if (f == NULL) {
+		/* ignore non-existent default config file */
+		if (errno == ENOENT && cfgfile == default_faillock_conf)
+			return PAM_SUCCESS;
+		return PAM_SERVICE_ERR;
+	}
+
+	while (fgets(linebuf, sizeof(linebuf), f) != NULL) {
+		size_t len;
+		char *ptr;
+		char *name;
+		int eq;
+
+		len = strlen(linebuf);
+		/* len cannot be 0 unless there is a bug in fgets */
+		if (len && linebuf[len - 1] != '\n' && !feof(f)) {
+			(void) fclose(f);
+			return PAM_SERVICE_ERR;
+		}
+
+		if ((ptr=strchr(linebuf, '#')) != NULL) {
+			*ptr = '\0';
+		} else {
+			ptr = linebuf + len;
+		}
+
+		/* drop terminating whitespace including the \n */
+		while (ptr > linebuf) {
+			if (!isspace(*(ptr-1))) {
+				*ptr = '\0';
+				break;
+			}
+			--ptr;
+		}
+
+		/* skip initial whitespace */
+		for (ptr = linebuf; isspace(*ptr); ptr++);
+		if (*ptr == '\0')
+			continue;
+
+		/* grab the key name */
+		eq = 0;
+		name = ptr;
+		while (*ptr != '\0') {
+			if (isspace(*ptr) || *ptr == '=') {
+				eq = *ptr == '=';
+				*ptr = '\0';
+				++ptr;
+				break;
+			}
+			++ptr;
+		}
+
+		/* grab the key value */
+		while (*ptr != '\0') {
+			if (*ptr != '=' || eq) {
+				if (!isspace(*ptr)) {
+					break;
+				}
+			} else {
+				eq = 1;
+			}
+			++ptr;
+		}
+
+		/* set the key:value pair on opts */
+		set_conf_opt(pamh, opts, name, ptr);
+	}
+
+	(void)fclose(f);
+	return PAM_SUCCESS;
+}
+
+static void
+set_conf_opt(pam_handle_t *pamh, struct options *opts, const char *name, const char *value)
+{
+	if (strcmp(name, "dir") == 0) {
+		if (value[0] != '/') {
+			pam_syslog(pamh, LOG_ERR,
+				"Tally directory is not absolute path (%s); keeping default", value);
+		} else {
+			free(opts->dir);
+			opts->dir = strdup(value);
+		}
+	}
+	else if (strcmp(name, "deny") == 0) {
+		if (sscanf(value, "%hu", &opts->deny) != 1) {
+			pam_syslog(pamh, LOG_ERR,
+				"Bad number supplied for deny argument");
+		}
+	}
+	else if (strcmp(name, "fail_interval") == 0) {
+		unsigned int temp;
+		if (sscanf(value, "%u", &temp) != 1 ||
+			temp > MAX_TIME_INTERVAL) {
+			pam_syslog(pamh, LOG_ERR,
+				"Bad number supplied for fail_interval argument");
+		} else {
+			opts->fail_interval = temp;
+		}
+	}
+	else if (strcmp(name, "unlock_time") == 0) {
+		unsigned int temp;
+
+		if (strcmp(value, "never") == 0) {
+			opts->unlock_time = 0;
+		}
+		else if (sscanf(value, "%u", &temp) != 1 ||
+			temp > MAX_TIME_INTERVAL) {
+			pam_syslog(pamh, LOG_ERR,
+				"Bad number supplied for unlock_time argument");
+		}
+		else {
+			opts->unlock_time = temp;
+		}
+	}
+	else if (strcmp(name, "root_unlock_time") == 0) {
+		unsigned int temp;
+
+		if (strcmp(value, "never") == 0) {
+			opts->root_unlock_time = 0;
+		}
+		else if (sscanf(value, "%u", &temp) != 1 ||
+			temp > MAX_TIME_INTERVAL) {
+			pam_syslog(pamh, LOG_ERR,
+				"Bad number supplied for root_unlock_time argument");
+		} else {
+			opts->root_unlock_time = temp;
+		}
+	}
+	else if (strcmp(name, "admin_group") == 0) {
+		free(opts->admin_group);
+		opts->admin_group = strdup(value);
+		if (opts->admin_group == NULL) {
+			opts->fatal_error = 1;
+			pam_syslog(pamh, LOG_CRIT, "Error allocating memory: %m");
+		}
+	}
+	else if (strcmp(name, "even_deny_root") == 0) {
+		opts->flags |= FAILLOCK_FLAG_DENY_ROOT;
+	}
+	else if (strcmp(name, "audit") == 0) {
+		opts->flags |= FAILLOCK_FLAG_AUDIT;
+	}
+	else if (strcmp(name, "silent") == 0) {
+		opts->flags |= FAILLOCK_FLAG_SILENT;
+	}
+	else if (strcmp(name, "no_log_info") == 0) {
+		opts->flags |= FAILLOCK_FLAG_NO_LOG_INFO;
+	}
+	else if (strcmp(name, "local_users_only") == 0) {
+		opts->flags |= FAILLOCK_FLAG_LOCAL_ONLY;
+	}
+	else {
+		pam_syslog(pamh, LOG_ERR, "Unknown option: %s", name);
+	}
+}
+
+static int
+check_local_user (pam_handle_t *pamh, const char *user)
+{
+	struct passwd pw, *pwp;
+	char buf[16384];
+	int found = 0;
+	FILE *fp;
+	int errn;
+
+	fp = fopen(PATH_PASSWD, "r");
+	if (fp == NULL) {
+		pam_syslog(pamh, LOG_ERR, "unable to open %s: %m",
+			   PATH_PASSWD);
+		return -1;
+	}
+
+	for (;;) {
+		errn = fgetpwent_r(fp, &pw, buf, sizeof (buf), &pwp);
+		if (errn == ERANGE) {
+			pam_syslog(pamh, LOG_WARNING, "%s contains very long lines; corrupted?",
+				   PATH_PASSWD);
+			break;
+		}
+		if (errn != 0)
+			break;
+		if (strcmp(pwp->pw_name, user) == 0) {
+			found = 1;
+			break;
+		}
+	}
+
+	fclose (fp);
+
+	if (errn != 0 && errn != ENOENT) {
+		pam_syslog(pamh, LOG_ERR, "unable to enumerate local accounts: %m");
+		return -1;
+	} else {
+		return found;
+	}
+}
+
+static int
+get_pam_user(pam_handle_t *pamh, struct options *opts)
+{
+	const char *user;
+	int rv;
+	struct passwd *pwd;
+
+	if ((rv=pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS) {
+		return rv == PAM_CONV_AGAIN ? PAM_INCOMPLETE : rv;
+	}
+
+	if (*user == '\0') {
+		return PAM_IGNORE;
+	}
+
+	if ((pwd=pam_modutil_getpwnam(pamh, user)) == NULL) {
+		if (opts->flags & FAILLOCK_FLAG_AUDIT) {
+			pam_syslog(pamh, LOG_NOTICE, "User unknown: %s", user);
+		}
+		else {
+			pam_syslog(pamh, LOG_NOTICE, "User unknown");
+		}
+		return PAM_IGNORE;
+	}
+	opts->user = user;
+	opts->uid = pwd->pw_uid;
+
+	if (pwd->pw_uid == 0) {
+		opts->is_admin = 1;
+		return PAM_SUCCESS;
+	}
+
+	if (opts->admin_group && *opts->admin_group) {
+		opts->is_admin = pam_modutil_user_in_group_uid_nam(pamh,
+			pwd->pw_uid, opts->admin_group);
+	}
+
+	return PAM_SUCCESS;
+}
+
+static int
+check_tally(pam_handle_t *pamh, struct options *opts, struct tally_data *tallies, int *fd)
+{
+	int tfd;
+	unsigned int i;
+	uint64_t latest_time;
+	int failures;
+
+	opts->now = time(NULL);
+
+	tfd = open_tally(opts->dir, opts->user, opts->uid, 0);
+
+	*fd = tfd;
+
+	if (tfd == -1) {
+		if (errno == EACCES || errno == ENOENT) {
+			return PAM_SUCCESS;
+		}
+		pam_syslog(pamh, LOG_ERR, "Error opening the tally file for %s: %m", opts->user);
+		return PAM_SYSTEM_ERR;
+	}
+
+	if (read_tally(tfd, tallies) != 0) {
+		pam_syslog(pamh, LOG_ERR, "Error reading the tally file for %s: %m", opts->user);
+		return PAM_SYSTEM_ERR;
+	}
+
+	if (opts->is_admin && !(opts->flags & FAILLOCK_FLAG_DENY_ROOT)) {
+		return PAM_SUCCESS;
+	}
+
+	latest_time = 0;
+	for (i = 0; i < tallies->count; i++) {
+		if ((tallies->records[i].status & TALLY_STATUS_VALID) &&
+			tallies->records[i].time > latest_time)
+			latest_time = tallies->records[i].time;
+	}
+
+	opts->latest_time = latest_time;
+
+	failures = 0;
+	for (i = 0; i < tallies->count; i++) {
+		if ((tallies->records[i].status & TALLY_STATUS_VALID) &&
+			latest_time - tallies->records[i].time < opts->fail_interval) {
+			++failures;
+		}
+	}
+
+	opts->failures = failures;
+
+	if (opts->deny && failures >= opts->deny) {
+		if ((!opts->is_admin && opts->unlock_time && latest_time + opts->unlock_time < opts->now) ||
+			(opts->is_admin && opts->root_unlock_time && latest_time + opts->root_unlock_time < opts->now)) {
+#ifdef HAVE_LIBAUDIT
+			if (opts->action != FAILLOCK_ACTION_PREAUTH) { /* do not audit in preauth */
+				char buf[64];
+				int audit_fd;
+				const void *rhost = NULL, *tty = NULL;
+
+				audit_fd = audit_open();
+				/* If there is an error & audit support is in the kernel report error */
+				if ((audit_fd < 0) && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
+					errno == EAFNOSUPPORT))
+					return PAM_SYSTEM_ERR;
+
+				(void)pam_get_item(pamh, PAM_TTY, &tty);
+				(void)pam_get_item(pamh, PAM_RHOST, &rhost);
+				snprintf(buf, sizeof(buf), "pam_faillock uid=%u ", opts->uid);
+				audit_log_user_message(audit_fd, AUDIT_RESP_ACCT_UNLOCK_TIMED, buf,
+					rhost, NULL, tty, 1);
+			}
+#endif
+			opts->flags |= FAILLOCK_FLAG_UNLOCKED;
+			return PAM_SUCCESS;
+		}
+		return PAM_AUTH_ERR;
+	}
+	return PAM_SUCCESS;
+}
+
+static void
+reset_tally(pam_handle_t *pamh, struct options *opts, int *fd)
+{
+	int rv;
+
+	if (*fd == -1) {
+		*fd = open_tally(opts->dir, opts->user, opts->uid, 1);
+	}
+	else {
+		while ((rv=ftruncate(*fd, 0)) == -1 && errno == EINTR);
+		if (rv == -1) {
+			pam_syslog(pamh, LOG_ERR, "Error clearing the tally file for %s: %m", opts->user);
+		}
+	}
+}
+
+static int
+write_tally(pam_handle_t *pamh, struct options *opts, struct tally_data *tallies, int *fd)
+{
+	struct tally *records;
+	unsigned int i;
+	int failures;
+	unsigned int oldest;
+	uint64_t oldtime;
+	const void *source = NULL;
+
+	if (*fd == -1) {
+		*fd = open_tally(opts->dir, opts->user, opts->uid, 1);
+	}
+	if (*fd == -1) {
+		if (errno == EACCES) {
+			return PAM_SUCCESS;
+		}
+		pam_syslog(pamh, LOG_ERR, "Error opening the tally file for %s: %m", opts->user);
+		return PAM_SYSTEM_ERR;
+	}
+
+	oldtime = 0;
+	oldest = 0;
+	failures = 0;
+
+	for (i = 0; i < tallies->count; ++i) {
+		if (oldtime == 0 || tallies->records[i].time < oldtime) {
+			oldtime = tallies->records[i].time;
+			oldest = i;
+		}
+		if (opts->flags & FAILLOCK_FLAG_UNLOCKED ||
+			opts->now - tallies->records[i].time >= opts->fail_interval ) {
+			tallies->records[i].status &= ~TALLY_STATUS_VALID;
+		} else {
+			++failures;
+		}
+	}
+
+	if (oldest >= tallies->count || (tallies->records[oldest].status & TALLY_STATUS_VALID)) {
+		oldest = tallies->count;
+
+		if ((records=realloc(tallies->records, (oldest+1) * sizeof (*tallies->records))) == NULL) {
+			pam_syslog(pamh, LOG_CRIT, "Error allocating memory for tally records: %m");
+			return PAM_BUF_ERR;
+		}
+
+		++tallies->count;
+		tallies->records = records;
+	}
+
+	memset(&tallies->records[oldest], 0, sizeof (*tallies->records));
+
+	tallies->records[oldest].status = TALLY_STATUS_VALID;
+	if (pam_get_item(pamh, PAM_RHOST, &source) != PAM_SUCCESS || source == NULL) {
+		if (pam_get_item(pamh, PAM_TTY, &source) != PAM_SUCCESS || source == NULL) {
+			if (pam_get_item(pamh, PAM_SERVICE, &source) != PAM_SUCCESS || source == NULL) {
+				source = "";
+			}
+		}
+		else {
+			tallies->records[oldest].status |= TALLY_STATUS_TTY;
+		}
+	}
+	else {
+		tallies->records[oldest].status |= TALLY_STATUS_RHOST;
+	}
+
+	strncpy(tallies->records[oldest].source, source, sizeof(tallies->records[oldest].source));
+	/* source does not have to be null terminated */
+
+	tallies->records[oldest].time = opts->now;
+
+	++failures;
+
+	if (opts->deny && failures == opts->deny) {
+#ifdef HAVE_LIBAUDIT
+		char buf[64];
+		int audit_fd;
+
+		audit_fd = audit_open();
+		/* If there is an error & audit support is in the kernel report error */
+		if ((audit_fd < 0) && !(errno == EINVAL || errno == EPROTONOSUPPORT ||
+			errno == EAFNOSUPPORT))
+			return PAM_SYSTEM_ERR;
+
+		snprintf(buf, sizeof(buf), "pam_faillock uid=%u ", opts->uid);
+		audit_log_user_message(audit_fd, AUDIT_ANOM_LOGIN_FAILURES, buf,
+			NULL, NULL, NULL, 1);
+
+		if (!opts->is_admin || (opts->flags & FAILLOCK_FLAG_DENY_ROOT)) {
+			audit_log_user_message(audit_fd, AUDIT_RESP_ACCT_LOCK, buf,
+				NULL, NULL, NULL, 1);
+		}
+		close(audit_fd);
+#endif
+		if (!(opts->flags & FAILLOCK_FLAG_NO_LOG_INFO)) {
+			pam_syslog(pamh, LOG_INFO, "Consecutive login failures for user %s account temporarily locked",
+				opts->user);
+		}
+	}
+
+	if (update_tally(*fd, tallies) == 0)
+		return PAM_SUCCESS;
+
+	return PAM_SYSTEM_ERR;
+}
+
+static void
+faillock_message(pam_handle_t *pamh, struct options *opts)
+{
+	int64_t left;
+
+	if (!(opts->flags & FAILLOCK_FLAG_SILENT)) {
+		if (opts->is_admin) {
+			left = opts->latest_time + opts->root_unlock_time - opts->now;
+		}
+		else {
+			left = opts->latest_time + opts->unlock_time - opts->now;
+		}
+
+		pam_info(pamh, _("The account is locked due to %u failed logins."),
+			(unsigned int)opts->failures);
+		if (left > 0) {
+			left = (left + 59)/60; /* minutes */
+
+			pam_info(pamh, _("(%d minutes left to unlock)"), (int)left);
+		}
+	}
+}
+
+static void
+tally_cleanup(struct tally_data *tallies, int fd)
+{
+	if (fd != -1) {
+		close(fd);
+	}
+
+	free(tallies->records);
+}
+
+static void
+opts_cleanup(struct options *opts)
+{
+	free(opts->dir);
+	free(opts->admin_group);
+}
+
+/*---------------------------------------------------------------------*/
+
+int
+pam_sm_authenticate(pam_handle_t *pamh, int flags,
+		    int argc, const char **argv)
+{
+	struct options opts;
+	int rv, fd = -1;
+	struct tally_data tallies;
+
+	memset(&tallies, 0, sizeof(tallies));
+
+	rv = args_parse(pamh, argc, argv, flags, &opts);
+	if (rv != PAM_SUCCESS)
+		goto err;
+
+	pam_fail_delay(pamh, 2000000);	/* 2 sec delay on failure */
+
+	if ((rv=get_pam_user(pamh, &opts)) != PAM_SUCCESS) {
+		goto err;
+	}
+
+	if (!(opts.flags & FAILLOCK_FLAG_LOCAL_ONLY) ||
+		check_local_user (pamh, opts.user) != 0) {
+		switch (opts.action) {
+			case FAILLOCK_ACTION_PREAUTH:
+				rv = check_tally(pamh, &opts, &tallies, &fd);
+				if (rv == PAM_AUTH_ERR && !(opts.flags & FAILLOCK_FLAG_SILENT)) {
+					faillock_message(pamh, &opts);
+				}
+				break;
+
+			case FAILLOCK_ACTION_AUTHSUCC:
+				rv = check_tally(pamh, &opts, &tallies, &fd);
+				if (rv == PAM_SUCCESS) {
+					reset_tally(pamh, &opts, &fd);
+				}
+				break;
+
+			case FAILLOCK_ACTION_AUTHFAIL:
+				rv = check_tally(pamh, &opts, &tallies, &fd);
+				if (rv == PAM_SUCCESS) {
+					rv = PAM_IGNORE; /* this return value should be ignored */
+					write_tally(pamh, &opts, &tallies, &fd);
+				}
+				break;
+		}
+	}
+
+	tally_cleanup(&tallies, fd);
+
+err:
+	opts_cleanup(&opts);
+
+	return rv;
+}
+
+/*---------------------------------------------------------------------*/
+
+int
+pam_sm_setcred(pam_handle_t *pamh UNUSED, int flags UNUSED,
+	       int argc UNUSED, const char **argv UNUSED)
+{
+	return PAM_SUCCESS;
+}
+
+/*---------------------------------------------------------------------*/
+
+int
+pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
+		 int argc, const char **argv)
+{
+	struct options opts;
+	int rv, fd = -1;
+	struct tally_data tallies;
+
+	memset(&tallies, 0, sizeof(tallies));
+
+	rv = args_parse(pamh, argc, argv, flags, &opts);
+
+	if (rv != PAM_SUCCESS)
+		goto err;
+
+	opts.action = FAILLOCK_ACTION_AUTHSUCC;
+
+	if ((rv=get_pam_user(pamh, &opts)) != PAM_SUCCESS) {
+		goto err;
+	}
+
+	if (!(opts.flags & FAILLOCK_FLAG_LOCAL_ONLY) ||
+		check_local_user (pamh, opts.user) != 0) {
+		check_tally(pamh, &opts, &tallies, &fd); /* for auditing */
+		reset_tally(pamh, &opts, &fd);
+	}
+
+	tally_cleanup(&tallies, fd);
+
+err:
+	opts_cleanup(&opts);
+
+	return rv;
+}
+
+/*-----------------------------------------------------------------------*/
--- /dev/null
+++ b/modules/pam_faillock/tst-pam_faillock
@@ -0,0 +1,2 @@
+#!/bin/sh
+../../tests/tst-dlopen .libs/pam_faillock.so
--- a/modules/Makefile.am
+++ b/modules/Makefile.am
@@ -3,7 +3,7 @@
 #
 
 SUBDIRS = pam_access pam_cracklib pam_debug pam_deny pam_echo \
-	pam_env pam_exec pam_extrausers pam_faildelay pam_filter pam_ftp \
+	pam_env pam_exec pam_extrausers pam_faildelay pam_faillock pam_filter pam_ftp \
 	pam_group pam_issue pam_keyinit pam_lastlog pam_limits \
 	pam_listfile pam_localuser pam_loginuid pam_mail \
 	pam_mkhomedir pam_motd pam_namespace pam_nologin \
