Thursday, July 14, 2005

Terminal Locker

Well, I finally had some free time on my hands and thought it would be fruitful to invest it on some useful coding. I ended up writing this nifty little and outrageously simple "terminal lock" kinda utility for Linux. It doggedly does one thing and one thing alone. LOCK YOUR TERMINAL. Without further ado, here's the code:

#include "pwd.h"

#include "signal.h"
#include "sys/types.h"
#include "fcntl.h"
#include "unistd.h"
#include "ncurses.h"
#include "shadow.h"
#include "errno.h"
#include "stdio.h"

#define MAX_PWD_LEN 512

int main(int argc,char* argv[])
{
int pwdCorrect=0;
uid_t thisUserId;
char *encPwd,plainPwd[MAX_PWD_LEN],*thisUserName;
struct passwd* pEntry;
struct spwd* sEntry;
sigset_t allSIG;

sigfillset(&allSIG);
sigprocmask(SIG_BLOCK,&allSIG,NULL);

initscr();
cbreak();
noecho();
clearok(curscr,TRUE);

thisUserId=getuid();
pEntry=getpwuid(thisUserId);
if(!pEntry) goto bad_exit;
thisUserName=pEntry->pw_name;
sEntry=getspnam(thisUserName);
if(!sEntry) goto bad_exit;

while(!pwdCorrect)
{
getnstr(plainPwd,MAX_PWD_LEN);
encPwd=crypt(plainPwd,sEntry->sp_pwdp);
if(!encPwd) goto bad_exit;
if(!strcmp(encPwd,sEntry->sp_pwdp))
pwdCorrect=1;
move(0,0);
wrefresh(curscr);
}
good_exit:
endwin();
return 0;
bad_exit:
endwin();
perror("");
return errno;
}

The following steps require you to be root.
Compile it with -lncurses and -lcrypt.
Set the s bit on the executable with "chmod a+s a.out". This is because any other user must also be able to run this application.
Copy it under a suitable directory(which appears in $PATH) as tlock(or any other name that appeals to your whims and fancies ) and you're done.
Just run the program and watch that dumb terminal lock up.

No comments: