aboutsummaryrefslogtreecommitdiff
path: root/pam_naming.c
blob: 75d2ae86f9866021b9206107470a5222f02e526b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* pam_naming module */

/*
 * (c) 2005 Guido Guenther <agx@sigxcpu.org>
 *
 * TODO: threadsafety for pcre functions
 */

#define _BSD_SOURCE

#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pcre.h>

/*
 * here, we make a definition for the externally accessible function
 * in this file (this definition is required for static a module
 * but strongly encouraged generally) it is used to instruct the
 * modules include file to define the function prototypes.
 */

#define PAM_SM_AUTH

#include <security/pam_modules.h>


static void _pam_log(int err, const char *format, ...)
{
    va_list args;

    va_start(args, format);
    openlog("PAM-naming", LOG_CONS|LOG_PID, LOG_AUTH);
    vsyslog(err, format, args);
    va_end(args);
    closelog();
}


static int check_naming(pam_handle_t *pamh, int argc, const char* argv[])
{
  pcre *re = NULL;
  int ret=PAM_SUCCESS, i;
  const char* user;
  const char* regex=NULL;
  const char *error = NULL;
  int erroffset;

  for (i = 0; i < argc; i++) {
    if (!strncmp (argv[i], "regex=", 5))
	regex = argv[i] + 6;
    else
	_pam_log(LOG_ERR, "illegal option %s", argv[i]);
	ret=PAM_SYSTEM_ERR;
  }
  if(regex==NULL) {
	_pam_log(LOG_ERR, "regex argument missing");
	goto out;
  }
  if((ret=pam_get_item(pamh, PAM_USER, (const void **)&user)) != PAM_SUCCESS) {
	_pam_log(LOG_ERR, "Couldnt retrieve username");
	goto out;
  }
  re = pcre_compile(regex, 0, &error, &erroffset, NULL);
  if(!re) {
	_pam_log(LOG_ERR, "Error in regex \"%s\" at %d: %s", regex, erroffset, error);
	ret=PAM_SYSTEM_ERR;
	goto out;
  }
  if(pcre_exec(re, NULL , user, strlen(user), 0, 0, NULL, 0) == -1) {
	_pam_log(LOG_INFO, "%s didn\'t match %s", user, regex);
	ret=PAM_USER_UNKNOWN;
  }
  /* Success */
out:
  if(re)
      pcre_free(re);
  return ret;
}

/* --- authentication management functions (only) --- */

PAM_EXTERN
int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc,
			const char **argv)
{
  return check_naming(pamh, argc, argv);
}

PAM_EXTERN
int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc,
			const char **argv)
{
  return PAM_SUCCESS;
}


#ifdef PAM_STATIC

/* static module data */

struct pam_module _pam_warn_modstruct = {
    "pam_exec",
    pam_sm_authenticate,
    pam_sm_setcred,
};

#endif

/* end of module definition */