How to check password on macOS? - c

The following C program can check the password of a user on Linux.
But it does not work on macOS because some functions are Linux specific.
Could anybody show me how to revise the program so that it works on macOS?
#include <unistd.h>
#include <pwd.h>
#include <shadow.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
char *username = argv[1];
struct passwd *pwd = getpwnam(username);
if (pwd == NULL) {
fputs("couldn't get password record", stderr);
return 1;
}
struct spwd *spwd = getspnam(username);
if (spwd == NULL) {
if(errno == EACCES) {
fputs("no permission to read shadow password file", stderr);
return 1;
}
fputs("No such username", stderr);
return 1;
}
char *password = getpass("Password: ");
printf("spwd->sp_pwdp: %s\n", spwd->sp_pwdp);
char *encrypted = crypt(password, spwd->sp_pwdp);
for (char *p = password; *p != '\0'; ++p)
*p = '\0';
if (encrypted == NULL) {
perror("crypt");
return 1;
}
if (strcmp(encrypted, spwd->sp_pwdp) != 0) {
fputs("Incorrect password\n", stderr);
return 1;
}
printf("Successfully authenticated: UID=%d\n", pwd->pw_uid);
return 0;
}
$ sudo ./checkpass "$USER"
Password:
spwd->sp_pwdp: $y$j9T$F5Jx5fExrKuPp53xLKQ..1$X3DX6M94c7o.9agCG9G317fhZg9SqC.5i5rd.RhAtQ7
Successfully authenticated: UID=504

Both Linux and macOS use PAM for authentication; Linux uses Linux-PAM, and MacOS and BSDs OpenPAM.
To authenticate via PAM:
/*
This is a variant of the Linux-PAM example at
http://www.linux-pam.org/Linux-PAM-html/adg-example.html
modified to use the 'login' PAM service.
That program was contributed by Shane Watts
[modifications by AGM and kukuk]
Save as ex_login.c, compile using (for Linux-PAM):
gcc -Wall -Wextra -O2 ex_login.c -lpam -lpam_misc -o ex_login
or (for OpenPAM):
gcc -DOPENPAM -Wall -Wextra -O2 ex_login.c -lpam -o ex_login
and run
./ex_login username
to authenticate the specified user.
*/
#include <stdlib.h>
#include <security/pam_appl.h>
#ifdef OPENPAM
#include <security/openpam.h>
#define USE_CONV_FUNC openpam_ttyconv
#else
#include <security/pam_misc.h>
#define USE_CONV_FUNC misc_conv
#endif
#include <stdio.h>
static struct pam_conv conv = {
USE_CONV_FUNC,
NULL
};
int main(int argc, char *argv[])
{
const char *arg0 = (argc > 0 && argv && argv[0] && argv[0][0] != '\0') ? argv[0] : "(this)";
pam_handle_t *pamh = NULL;
int retval;
const char *user;
if (argc != 2) {
fprintf(stderr, "\nUsage: %s USERNAME\n\n", arg0);
exit(EXIT_FAILURE);
}
user = argv[1];
retval = pam_start("login", user, &conv, &pamh);
if (retval == PAM_SUCCESS)
retval = pam_authenticate(pamh, 0); /* is user really user? */
if (retval == PAM_SUCCESS)
retval = pam_acct_mgmt(pamh, 0); /* permitted access? */
/* This is where we have been authorized or not. */
if (retval == PAM_SUCCESS) {
fprintf(stdout, "Authenticated\n");
} else {
fprintf(stdout, "Not Authenticated\n");
}
if (pam_end(pamh,retval) != PAM_SUCCESS) { /* close Linux-PAM */
pamh = NULL;
fprintf(stderr, "%s: failed to release authenticator\n", arg0);
exit(EXIT_FAILURE);
}
return ( retval == PAM_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE );
}

Related

How to pass argument values in the program implementing the shell

SOURCE::
#include <stdio.h> // printf()
#include <stdlib.h> // exit()
#include <string.h> // string
#include <dirent.h> // microsoft base compiler. _chdir, _getcwd
#include <unistd.h> // unix base complier. getcwd, chdir
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FILE_SIZE 1024
#define MAX 255
#define ERROR (-1)
void cmd_mkdir(int argc, char *argv);
void cmd_ls()
{
char * cwd = (char *)malloc(sizeof(char) * 1024);
DIR * dir = NULL;
struct dirent * entry = NULL;
getcwd(cwd, 1024);
if( (dir = opendir(cwd)) == NULL)
{
printf("current directory error\n");
exit(1);
}
while( (entry = readdir(dir)) != NULL)
{
printf("%s\n", entry->d_name);
}
free(cwd);
closedir(dir);
}
void cmd_pwd() {
char buf[MAX];
getcwd(buf, MAX);
printf("%s\n", buf);
}
int main(int argc, char *argv[])
{
char cBuf[MAX];
char *arg;
while(1) {
printf(">> ");
arg = fgets(cBuf, MAX, stdin);
if(argc < 2){
// printf("1111\n"); -- check
if(strncmp(arg, "ls", 2) == 0)
cmd_ls();
else if(strncmp(arg, "pwd", 3) == 0)
cmd_pwd();
else if(strncmp(arg, "exit", 4) == 0)
break;
} // if END
else {
// printf("2222\n"); -- check
if(strcmp(arg, "mkdir") == 0){
if (argc != 2)
fprintf(stderr, "Usage : jmkdir dirname\n");
if(mkdir(argv[1], 0755))
perror("mkdir error");
}
}// else END
} // while END
} // main END
Desired result::
How to get two input values (mkdir, mini_maked) as parameters after executing ./minishell (executable file implementing the shell)
$ ./minishell
>> mkdir mini_maked
Currently implemented ls, pwd, exit can be implemented because it can be used without options, but a command that requires a "command filename" such as mkdir is not implemented.
If the program itself functions as mkdir, it is solved using the values of argc and argv.
However, since the ./myshell program itself implements the shell program, when you run the program and receive mkdir mini_maked as an input, you are having a hard time executing the command.
If we get two inputs (mkdir, mini_maked) after program execution, how do we get these as parameters?

Getting undefined reference to misc_conv using Debian libpam0g-dev

Code:
#include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <stdio.h>
static struct pam_conv conv = {
misc_conv,
NULL
};
int main(int argc, char *argv[])
{
pam_handle_t *pamh=NULL;
int retval;
const char *user="nobody";
if(argc == 2) {
user = argv[1];
}
if(argc > 2) {
fprintf(stderr, "Usage: check_user [username]\n");
exit(1);
}
retval = pam_start("check_user", user, &conv, &pamh);
if (retval == PAM_SUCCESS)
retval = pam_authenticate(pamh, 0); /* is user really user? */
if (retval == PAM_SUCCESS)
retval = pam_acct_mgmt(pamh, 0); /* permitted access? */
/* This is where we have been authorized or not. */
if (retval == PAM_SUCCESS) {
fprintf(stdout, "Authenticated\n");
} else {
fprintf(stdout, "Not Authenticated\n");
}
if (pam_end(pamh,retval) != PAM_SUCCESS) { /* close Linux-PAM */
pamh = NULL;
fprintf(stderr, "check_user: failed to release authenticator\n");
exit(1);
}
return ( retval == PAM_SUCCESS ? 0:1 ); /* indicate success */
}
Two libraries I added:
libpam0g-dev
libpam0g
In /usr/include/security/ I have:
_pam_compat.h
_pam_macros.h
_pam_types.h
pam_appl.h
pam_client.h
pam_ext.h
pam_filter.h
pam_misc.h
pam_modules.h
pam_modutil.h
I compile with: gcc -o check_user -lpam check_user.c
And I get:
/usr/bin/ld: /tmp/cc9ldItB.o:(.data.rel+0x0): undefined reference to `misc_conv'
collect2: error: ld returned 1 exit status
So why do I get undefined reference to "misc_conv' when the libpam0g-dev was added?
You should add the -lpam_misc option to the command:
gcc -o check_user -lpam -lpam_misc check_user.c

Authentication error on pam application without asking password

I have an application running on an unprivileged user, but at some point this program needs to run another one as a root, would be nice if I can reuse a configured PAM module, like, su, sudo, login or anyone.
So I am trying to write some code to authenticate the root and run this program using PAM, like sudo does, but I cant ask for password, it needs to be automatic. This unprivileged program in a specific time will have the access to root password.
Tried this example here https://www.netbsd.org/docs/guide/en/chap-pam.html but on pam_authenticate, it always return PAM_AUTH_ERR, I have tried all configured modules on my ubuntu 18.04.
#include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <stdio.h>
#include <sys/wait.h>
#include <err.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <grp.h>
#include <assert.h>
#include <string>
#include <vector>
int converse(int n, const struct pam_message **msg, struct pam_response **resp, void *data)
{
struct pam_response *aresp;
char buf[PAM_MAX_RESP_SIZE];
int i;
data = data;
if (n <= 0 || n > PAM_MAX_NUM_MSG)
return (PAM_CONV_ERR);
if ((aresp = (struct pam_response *) calloc(n, sizeof *aresp)) == NULL)
return (PAM_BUF_ERR);
for (i = 0; i < n; ++i) {
aresp[i].resp_retcode = 0;
aresp[i].resp = NULL;
switch (msg[i]->msg_style) {
case PAM_PROMPT_ECHO_OFF:
//aresp[i].resp = strdup(getpass(msg[i]->msg));
aresp[i].resp = strdup("mypass");
aresp[i].resp_retcode = 0;
if (aresp[i].resp == NULL)
goto fail;
break;
case PAM_PROMPT_ECHO_ON:
fputs(msg[i]->msg, stderr);
if (fgets(buf, sizeof buf, stdin) == NULL)
goto fail;
aresp[i].resp = strdup(buf);
if (aresp[i].resp == NULL)
goto fail;
break;
case PAM_ERROR_MSG:
fputs(msg[i]->msg, stderr);
if (strlen(msg[i]->msg) > 0 &&
msg[i]->msg[strlen(msg[i]->msg) - 1] != '\n')
fputc('\n', stderr);
break;
case PAM_TEXT_INFO:
fputs(msg[i]->msg, stdout);
if (strlen(msg[i]->msg) > 0 &&
msg[i]->msg[strlen(msg[i]->msg) - 1] != '\n')
fputc('\n', stdout);
break;
default:
goto fail;
}
}
*resp = aresp;
return (PAM_SUCCESS);
fail:
for (i = 0; i < n; ++i) {
if (aresp[i].resp != NULL) {
memset(aresp[i].resp, 0, strlen(aresp[i].resp));
free(aresp[i].resp);
}
}
memset(aresp, 0, n * sizeof *aresp);
*resp = NULL;
return (PAM_CONV_ERR);
}
static struct pam_conv conv = {
converse,
//misc_conv,
NULL
};
extern char **environ;
static pam_handle_t *pamh;
static struct pam_conv pamc;
static void
usage(void)
{
fprintf(stderr, "Usage: su [login [args]]\n");
exit(1);
}
int
main(int argc, char *argv[])
{
char hostname[64];
const char *user, *tty;
char **args, **pam_envlist, **pam_env;
struct passwd *pwd;
int o, pam_err, status;
pid_t pid;
while ((o = getopt(argc, argv, "h")) != -1)
switch (o) {
case 'h':
default:
usage();
}
argc -= optind;
argv += optind;
if (argc > 0) {
user = *argv;
--argc;
++argv;
} else {
user = "root";
}
int pam_status = PAM_SUCCESS;
/* initialize PAM */
//pamc.conv = &openpam_ttyconv;
if ((pam_status = pam_start("passwd", user, &conv, &pamh)) != PAM_SUCCESS)
{
assert(false);
}
/* set some items */
gethostname(hostname, sizeof(hostname));
if ((pam_err = pam_set_item(pamh, PAM_RHOST, hostname)) != PAM_SUCCESS)
{
assert(false);
}
user = getlogin();
if ((pam_err = pam_set_item(pamh, PAM_RUSER, user)) != PAM_SUCCESS)
{
assert(false);
}
tty = ttyname(STDERR_FILENO);
if ((pam_err = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS)
{
assert(false);
}
/* authenticate the applicant */
pam_err = pam_authenticate(pamh, PAM_SILENT);
if (pam_err != PAM_SUCCESS)
{
printf("Pam Error (%d)\n", pam_err);
warn("pam_authenticate");
assert(false);
}
printf("AUTHENTICATED ;-)");
assert(false);
if ((pam_err = pam_acct_mgmt(pamh, 0)) == PAM_NEW_AUTHTOK_REQD)
pam_err = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
if (pam_err != PAM_SUCCESS)
{
assert(false);
}
/* establish the requested credentials */
if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS)
{
assert(false);
}
/* authentication succeeded; open a session */
if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS)
{
assert(false);
}
/* get mapped user name; PAM may have changed it */
pam_err = pam_get_item(pamh, PAM_USER, (const void **)&user);
if (pam_err != PAM_SUCCESS || (pwd = getpwnam(user)) == NULL)
{
assert(false);
}
/* export PAM environment */
if ((pam_envlist = pam_getenvlist(pamh)) != NULL) {
for (pam_env = pam_envlist; *pam_env != NULL; ++pam_env) {
putenv(*pam_env);
free(*pam_env);
}
free(pam_envlist);
}
std::vector<std::string> arguments;
arguments.resize(argc + 2);
char * args_ptr [arguments.size()];
arguments[0] = pwd->pw_shell;
args_ptr[argc +1] = NULL;
args_ptr[0] = (char *)arguments[0].c_str();
for (int i = 0; i < argc; i++)
{
arguments[i + 1] = argv[i];
args_ptr[i+1] = (char *)arguments[i+1].c_str();
}
/* set uid and groups */
if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
warn("initgroups()");
_exit(1);
}
if (setgid(pwd->pw_gid) == -1) {
warn("setgid()");
_exit(1);
}
if (setuid(pwd->pw_uid) == -1) {
warn("setuid()");
_exit(1);
}
execve(args_ptr[0], args_ptr, environ);
warn("execve()");
_exit(1);
pamerr:
fprintf(stderr, "Sorry\n");
err:
pam_end(pamh, pam_err);
exit(1);
}
I expect to fork in a elevated child and run my new program, without asking for password.

Why PAM module code isn't working in my ubuntu?

I implemented basic PAM module and test application from this github link.
In the src folder it has a simple PAM module and test code for it.
PAM module code mypam.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <security/pam_appl.h>
#include <security/pam_modules.h>
/* expected hook */
PAM_EXTERN int pam_sm_setcred( pam_handle_t *pamh, int flags, int argc, const char **argv ) {
return PAM_SUCCESS;
}
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv) {
printf("Acct mgmt\n");
return PAM_SUCCESS;
}
/* expected hook, this is where custom stuff happens */
PAM_EXTERN int pam_sm_authenticate( pam_handle_t *pamh, int flags,int argc, const char **argv ) {
int retval;
const char* pUsername;
retval = pam_get_user(pamh, &pUsername, "Username: ");
printf("Welcome %s\n", pUsername);
if (retval != PAM_SUCCESS) {
return retval;
}
if (strcmp(pUsername, "backdoor") != 0) {
return PAM_AUTH_ERR;
}
return PAM_SUCCESS;
}
Test code test.c:
#include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <stdio.h>
const struct pam_conv conv = {
misc_conv,
NULL
};
int main(int argc, char *argv[]) {
pam_handle_t* pamh = NULL;
int retval;
const char* user = "nobody";
if(argc != 2) {
printf("Usage: app [username]\n");
exit(1);
}
user = argv[1];
retval = pam_start("check_user", user, &conv, &pamh);
// Are the credentials correct?
if (retval == PAM_SUCCESS) {
printf("Credentials accepted.\n");
retval = pam_authenticate(pamh, 0);
}
// Can the accound be used at this time?
if (retval == PAM_SUCCESS) {
printf("Account is valid.\n");
retval = pam_acct_mgmt(pamh, 0);
}
// Did everything work?
if (retval == PAM_SUCCESS) {
printf("Authenticated\n");
} else {
printf("Not Authenticated\n");
}
// close PAM (end session)
if (pam_end(pamh, retval) != PAM_SUCCESS) {
pamh = NULL;
printf("check_user: failed to release authenticator\n");
exit(1);
}
return retval == PAM_SUCCESS ? 0 : 1;
}
I built the module according to the github link instructions:
gcc -fPIC -fno-stack-protector -c src/mypam.c
sudo ld -x --shared -o /lib/security/mypam.so mypam.o
sudo ld -x --shared -o /lib/x86_64-linux-gnu/security/mypam.so mypam.o
gcc -o pam_test src/test.c -lpam -lpam_misc
I put below two command into /etc/pam.d/common-auth at the top.
auth sufficient mypam.so
account sufficient mypam.s
According to the site:
To run the test program, just do: pam_test backdoor and you should get
some messages saying that you're authenticated!
But I got following error:
abnormal#abnormal:~/Desktop$ pam_test backdoor
No command 'pam_test' found, did you mean:
Command 'pim_test' from package 'styx' (universe)
pam_test: command not found
abnormal#abnormal:~/Desktop$
what sholud I do now? I am using ubuntu 14,04 LTS. Please help.
There's nothing wrong with the code, but the invocation. You shoud use this:
abnormal#abnormal:~/Desktop$ ./pam_test backdoor
Unlike Windows, the current directory usually is not part of the search PATH on Linux.

Root-SUID C wrapper debugging

I am new to C and this is a simple wrapper I wrote to run execute scripts as different user. I understand I can do visudo in etc/sudoers but, I already did this and I don't want it to go to waste, also it will help me improve writing in C. I seem to ha The problem is I am having errors when I compile it. My operating system is Ubuntu 12.04.03 LTS. Can someone help me fix these errors?
rootsuidwrapper.c: In function ‘trusted’:
rootsuidwrapper.c:60:15: warning: assignment makes pointer from integer without a cast [enabled by default]
rootsuidwrapper.c: In function ‘main’:
rootsuidwrapper.c:116:48: error: too many arguments to function ‘stat’
/usr/include/x86_64-linux-gnu/sys/stat.h:211:12: note: declared here
It would be nice if someone could fix these errors and give me the working code. Also, I would like to know what I did wrong.
* This program must be run as root to work.
*/
#if !defined(lint) && !defined(SABER) || defined(RCS_HDRS)
#endif /* !lint && !SABER || RCS_HDRS */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/stat.h>
#define TRUSTED_GROUP "trusted"
typedef enum { false = 0, true } bool;
#ifdef __STDC__
bool trusted(char *whoami)
#else
bool trusted(whoami)
char *whoami;
#endif /* __STDC__ */
{
char *user;
char host[BUFSIZ + 1];
char domain[BUFSIZ + 1];
struct hostent *hp;
/*
* Figure out whether this user on this host in this domain is
* trusted.
*/
/*
* Determine our domain name
*/
(void) memset(domain, '\0', sizeof(domain));
getdomainname(domain, sizeof(domain) - 1);
/*
* Figure out our fully canonicalized hostname
*/
(void) memset(host, '\0', sizeof(host));
gethostname(host, sizeof(host) - 1);
if ((hp = gethostbyname(host)) == NULL) {
strcat(host, ".");
strcat(host, domain);
fprintf(stderr,
"%s: WARNING: can't canonlicalize hostname; assuming %s.\n",
whoami, host);
}
else {
strcpy(host, hp->h_name);
}
/*
* Get login name of current user
*/
if ((user = cuserid(NULL)) == NULL) {
fprintf(stderr, " %s: You do not seem to be in the passwd file!\n",
whoami);
return(false);
}
/*
* Look this triple up in the trusted netgroup
*/
return ((innetgr(TRUSTED_GROUP, host, user, domain) == 1) ? true : false);
}
#ifdef __STDC__
main(int argc, char *argv[])
#else
main(argc, argv)
int argc;
char *argv[];
#endif /* __STDC__ */
{
char *whoami;
int ouruid; /* uid we set to run chown and chmod */
int proguid; /* uid we are chowning program to */
char *filename;
struct stat statbuf;
int error = 0;
if (whoami = strrchr(argv[0], '/'))
whoami ++;
else
whoami = argv[0];
if (argc == 3)
proguid = atoi(argv[2]);
else if (argc == 2)
proguid = 0;
else {
fprintf(stderr, "usage: %s filename [proguid]\n", whoami);
exit(1);
}
filename = argv[1];
if (trusted(whoami))
ouruid = 0;
else
ouruid = getuid();
if (setuid(ouruid) == -1) {
fprintf(stderr, "%s: Warning: setuid(%d) failed: ", whoami, ouruid);
perror(NULL);
exit(1);
}
if (stat(filename, &statbuf, sizeof(struct stat)) == -1) {
fprintf(stderr, "%s: failure statting %s: ", whoami, filename);
perror(NULL);
exit(1);
}
if (chown(filename, proguid, -1) == -1) {
error++;
fprintf(stderr, "%s: chown %d %s failed: ", whoami, proguid, filename);
perror(NULL);
fprintf(stderr, "continuing...\n");
}
if (chmod(filename, statbuf.st_mode | S_ISUID)) {
error++;
fprintf(stderr, "%s: chmod u+s %s failed: ", whoami, filename);
perror(NULL);
}
return(error);
}
Help is appreciated,
NAME
stat, fstat, lstat - get file status
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int filedes, struct stat *buf);
int lstat(const char *path, struct stat *buf);
Remove your third parameter in the call to stat(). Your code should then be:
if (stat(filename, &statbuf) == -1) {
There is no need to tell stat() the size of the buffer because stat() expects a struct stat * which has a fixed size.
For the compiler warning:
cuserid() returns a pointer to a character (char*). When any function returns a pointer, and you want to place the return value into a buffer, then you have to put the return value into a specific place in the buffer, usually the beginning. Specifically, you should use:
*user = cuserid(NULL);
if(user == NULL)
Remember, cuserid() returns a pointer to a single character. Therefore, the return value of the function should go into a single character - that is, *user or user[0]. When the above code is used, the compiler shouldn't complain. Then you place the result of cuserid(NULL) into user, from the first byte to the rest of the memory allocated.

Resources