68
40-491 Adv. UNIX: info/19 Advanced UNIX Advanced UNIX Objectives Objectives examine a few system data files examine a few system data files (and their C interfaces) which (and their C interfaces) which record user and system information record user and system information 240-491 Special Topics in Comp. Eng. 2 Semester 2, 2000-2001 19. User and System Information

240-491 Adv. UNIX: info/191 Advanced UNIX v Objectives –examine a few system data files (and their C interfaces) which record user and system information

Embed Size (px)

Citation preview

240-491 Adv. UNIX: info/19 1

Advanced UNIXAdvanced UNIX

ObjectivesObjectives– examine a few system data files (and their examine a few system data files (and their

C interfaces) which record user and C interfaces) which record user and system informationsystem information

240-491 Special Topics in Comp. Eng. 2Semester 2, 2000-2001

19. User and SystemInformation

240-491 Adv. UNIX: info/19 2

OverviewOverview

1. 1. /etc/passwd/etc/passwd

2. 2. /etc/group/etc/group

3. Other Data Files3. Other Data Files

4. 4. /etc/hosts/etc/hosts

5. 5. /etc/protocols/etc/protocols

continued

240-491 Adv. UNIX: info/19 3

6. 6. /etc/services/etc/services

7. Login Accounting7. Login Accounting

8. The System Log: 8. The System Log: syslogsyslog

9. Process Information9. Process Information

10. System Information10. System Information

240-491 Adv. UNIX: info/19 4

1. 1. /etc/passwd/etc/passwd

The password file:The password file:root:jheVopR58x9Fx:0:1:The superuser:/:/bin/shnobody:*:65534:65534::/:stevens:3hKVD8R58r9Fx:224:100:

Richard Stevens:/home/stevens:/bin/ksh

: :

More details on the More details on the passwdpasswd file format: file format:– $ man 5 passwd$ man 5 passwd

240-491 Adv. UNIX: info/19 5

NotesNotes rootroot has the user ID 0 has the user ID 0

The password is encrypted using The password is encrypted using crypt()crypt()

– one-wayone-way: there is no known way to decrypt : there is no known way to decrypt (decode) a password(decode) a password

nobodynobody cannot login, but programs can run cannot login, but programs can run as as nobodynobody

– can only access world readable or writable filescan only access world readable or writable files

240-491 Adv. UNIX: info/19 6

FingerFinger

fingerfinger accesses the GECOS field: accesses the GECOS field:stevens:3hKVD8R58r9Fx:224:100:stevens:3hKVD8R58r9Fx:224:100:

Richard &, B232, 555-1111, 555-Richard &, B232, 555-1111, 555-22222222::

/home/stevens:/bin/ksh/home/stevens:/bin/ksh

– different fields are separated by commas: different fields are separated by commas: user name, office, work and home phone numbersuser name, office, work and home phone numbers

– && is replaced by the capitalised user name is replaced by the capitalised user name

240-491 Adv. UNIX: info/19 7

struct passwdstruct passwd

struct passwd{ char *pw_name; /* user name */ char *pw_passwd; /* encrypted passwd */ uid_t pw_uid; /* user ID */ uid_t pw_gid; /* group ID */ char *pw_gecos; /* comment field */ char *pw_dir; /* initial working dir */ char *pw_shell; /* initial shell */}

Located in pwd.h

240-491 Adv. UNIX: info/19 8

Get a User’s DetailsGet a User’s Details #include <sys/types.h>#include <sys/types.h>#include <pwd.h>#include <pwd.h>

struct passwd *getpwuid(uid_t uid);struct passwd *getpwuid(uid_t uid);struct passwd *getpwnam(char *name);struct passwd *getpwnam(char *name);

Return a pointer to the password structure for the Return a pointer to the password structure for the specified user, or specified user, or NULLNULL on error. on error.

For long term use, the struct should be copied, For long term use, the struct should be copied, since it will be over-written on the next call.since it will be over-written on the next call.

240-491 Adv. UNIX: info/19 9

Search the Search the passwdpasswd file file

#include <sys/types.h>#include <sys/types.h>#include <pwd.h>#include <pwd.h>

struct passwd *getpwent(void);struct passwd *getpwent(void);

void setpwent(void); // openvoid setpwent(void); // openvoid endpwent(void); // closevoid endpwent(void); // close

getpwent()getpwent() returns a pointer if ok, returns a pointer if ok, NULLNULL on on error or end of file.error or end of file.

240-491 Adv. UNIX: info/19 10

Search for Stupid PasswordsSearch for Stupid Passwords

#include <stdio.h>#include <string.h>#include <pwd.h>#include <unistd.h> /* for crypt() */

int main(){ struct passwd *pw; char *cry;

setpwent(); while ((pw = getpwent()) != NULL) { printf(“Trying %s\n”, pw->pw_name); :

continued

240-491 Adv. UNIX: info/19 11

if (pw->pw_passwd[0] == ‘\0’)if (pw->pw_passwd[0] == ‘\0’) printf(“**%s has no password\n”, printf(“**%s has no password\n”, pw->pw_name); pw->pw_name); else { else { cry = cry = crypt(pw->pw_name, pw->pw_passwd);(pw->pw_name, pw->pw_passwd); if (strcmp(cry, pw->passwd) == 0) if (strcmp(cry, pw->passwd) == 0) printf(“##%s used as own passwd\n”, printf(“##%s used as own passwd\n”,

pw->pw_name);pw->pw_name); } } } } endpwent();; return 0; return 0;}}

240-491 Adv. UNIX: info/19 12

crypt()crypt()

#include <unistd.h>#include <unistd.h>char *crypt(char *text, char *salt);char *crypt(char *text, char *salt);

Returns a pointer to the encrypted version of Returns a pointer to the encrypted version of the text or the text or NULLNULL on error. on error.

saltsalt is a string. is a string. crypt()crypt() takes the first two takes the first two chars and treats them as a 12-bit number chars and treats them as a 12-bit number between 0 and 4095 to slightly modify things.between 0 and 4095 to slightly modify things.

240-491 Adv. UNIX: info/19 13

The salt is stored at the start of the encrypted The salt is stored at the start of the encrypted password:password:

e.g. e.g. “mi”“mi” in in “miqkFWCm1fNJI”“miqkFWCm1fNJI”

When the encrypted password is first created, When the encrypted password is first created, /bin/passwd/bin/passwd uses the time of day as salt. uses the time of day as salt.

Salt means that the same (original) password Salt means that the same (original) password will be encrypted in different ways on will be encrypted in different ways on different machines.different machines.

240-491 Adv. UNIX: info/19 14

The The ShadowShadow Password File Password File /etc/shadow/etc/shadow stores encrypted password strings stores encrypted password strings

– only readable by only readable by rootroot

– /etc/passwd/etc/passwd contains only ‘ contains only ‘xx’s in its password fields’s in its password fields

This prevents password cracking by copying This prevents password cracking by copying /etc/passwd/etc/passwd and then using ‘guess and test’ and then using ‘guess and test’– some some crypt()crypt()’s can generate 50,000 encrypted ’s can generate 50,000 encrypted

strings/secondstrings/second– many passwords are very simple!many passwords are very simple!

240-491 Adv. UNIX: info/19 15

2. 2. /etc/group/etc/group

Lists every group on the system, an optional Lists every group on the system, an optional password, its group ID, and the users who password, its group ID, and the users who are members:are members:

wheel:*:0:root, rachelwheel:*:0:root, racheluucp:*:10:uucpuucp:*:10:uucpvision:AweHG67Ket4Ds:101:keith, arlinvision:AweHG67Ket4Ds:101:keith, arlinusers:*:100:users:*:100:

$ man 5 group

240-491 Adv. UNIX: info/19 16

Joining GroupsJoining Groups

/etc/group/etc/group lists group users lists group users in addition to the in addition to the onesones who are members because of their who are members because of their /etc/passwd/etc/passwd group ID. group ID.– e.g. e.g. stevensstevens is in is in usersusers because he has because he has

group ID 100group ID 100

A user can change group with A user can change group with newgrpnewgrp

– usually must be a member of that groupusually must be a member of that group– some groups have passwords (e.g. some groups have passwords (e.g. visionvision))

240-491 Adv. UNIX: info/19 17

Accessing Accessing /etc/group/etc/group

Use struct Use struct groupgroup and its operations in and its operations in <grp.h><grp.h>::

struct group {struct group { char *gr_name; char *gr_name; /* group name */ /* group name */ char *gr_passwd; char *gr_passwd; /* encrypted passwd */ /* encrypted passwd */ int gr_gid; int gr_gid; /* group id */ /* group id */ char **gr_mem; char **gr_mem; /* array of names */ /* array of names */}}

gr_memgr_mem is terminated by is terminated by NULLNULL..

240-491 Adv. UNIX: info/19 18

Fetch Group DetailsFetch Group Details #include <sys/types.h>#include <sys/types.h>#include <grp.h>#include <grp.h>

struct group *getgrgid(gid_t gid);struct group *getgrgid(gid_t gid);struct group *getgrnam(char *name);struct group *getgrnam(char *name);

Return a pointer to a group structure, Return a pointer to a group structure, NULLNULL on on error.error.

For long term use, the structure should be copied For long term use, the structure should be copied since it is over-written on the next call.since it is over-written on the next call.

240-491 Adv. UNIX: info/19 19

Search the Search the groupgroup file file

#include <sys/types.h>#include <sys/types.h>#include <grp.h>#include <grp.h>

struct group *getgrent(void);struct group *getgrent(void);

void setgrent(void); // openvoid setgrent(void); // openvoid endgrent(void); // closevoid endgrent(void); // close

getgrent()getgrent() returns a pointer if ok, returns a pointer if ok, NULLNULL on on error.error.

240-491 Adv. UNIX: info/19 20

Supplementary Group IDsSupplementary Group IDs

In earlier UNIXs, each user belonged to one group at a In earlier UNIXs, each user belonged to one group at a time. time. – change was possible with change was possible with newgrpnewgrp

Some UNIXs now have supplementary group IDs:Some UNIXs now have supplementary group IDs:– a user can belong to up to 16 additional groupsa user can belong to up to 16 additional groups

– no longer need to use no longer need to use newgrpnewgrp (so much) (so much)

240-491 Adv. UNIX: info/19 21

Supplementary Group FunctionsSupplementary Group Functions

#include <unistd.h>#include <unistd.h>

int getgroups(int gidsetsize, int getgroups(int gidsetsize, gid_t grouplist[]);gid_t grouplist[]);

int setgroups(int ngroups, int setgroups(int ngroups, gid_t grouplist[]);gid_t grouplist[]);

int initgroups(char *username, int initgroups(char *username, gid_t basegid);gid_t basegid);

240-491 Adv. UNIX: info/19 22

getgroups()getgroups() returns the number of returns the number of supplementary group IDs if ok, -1 on error.supplementary group IDs if ok, -1 on error.

Both Both setgroups()setgroups() and and initgroups()initgroups() return 0 if return 0 if ok, -1 on error.ok, -1 on error.

initgroups()initgroups() is called at login, and makes use of is called at login, and makes use of setgroups(setgroups()) to initialise a user’s supplementary to initialise a user’s supplementary group IDs by examining group IDs by examining /etc/group/etc/group..

240-491 Adv. UNIX: info/19 23

3. Other Data Files3. Other Data Files Most UNIX data files have similar interfaces to those Most UNIX data files have similar interfaces to those

used to access/change used to access/change /etc/passwd/etc/passwd and and /etc/group/etc/group..

At least three ‘search’ functions:At least three ‘search’ functions:– set??()set??() Opens the file and rewinds it.Opens the file and rewinds it.– get??()get??() Reads next record. Returns a pointerReads next record. Returns a pointer

to a struct which will be over-writtento a struct which will be over-writtenon the next call.on the next call.

– end??()end??() Close the file.Close the file.

$ man 5 <data>

240-491 Adv. UNIX: info/19 24

““Lookup a record” functions:Lookup a record” functions:– uses keys to identify the record of interestuses keys to identify the record of interest– e.g. user name, service IDe.g. user name, service ID

The next three sections illustrate these The next three sections illustrate these patterns used with the files:patterns used with the files:– /etc/hosts/etc/hosts– /etc/protocols/etc/protocols– /etc/services/etc/services

240-491 Adv. UNIX: info/19 25

Keeps track of the network addresses for Keeps track of the network addresses for every host on the local network.every host on the local network.

Often incomplete since the system can also Often incomplete since the system can also ask address servers on other machines.ask address servers on other machines.

Typical Typical /etc/hosts/etc/hosts::127.0.0.1 localhost127.0.0.1 localhost192.100.77.3 ratree.psu.ac.th ratree loghost192.100.77.3 ratree.psu.ac.th ratree loghost192.100.77.5 ns.psu.ac.th ns192.100.77.5 ns.psu.ac.th ns203.154.130.11 ratree2.psu.ac.th ratree2203.154.130.11 ratree2.psu.ac.th ratree2

4. 4. /etc/hosts/etc/hosts

240-491 Adv. UNIX: info/19 26

Accessing Accessing /etc/hosts/etc/hosts

Header: Header: <netdb.h><netdb.h>

C structure: C structure: hostenthostent

Keyed lookup functions:Keyed lookup functions:– gethostbyname()gethostbyname()– gethostbyaddr()gethostbyaddr()

240-491 Adv. UNIX: info/19 27

5. 5. /etc/protocols/etc/protocols

Stores details about network protocols Stores details about network protocols supported by the system.supported by the system.

Fragment of Fragment of /etc/protocols/etc/protocols::tcp 6 TCP tcp 6 TCP

# transmission control protocol# transmission control protocol::

udp 17 UDP udp 17 UDP # user datagram protocol# user datagram protocol

: :

240-491 Adv. UNIX: info/19 28

Accessing Accessing /etc/protocols/etc/protocols

Header: Header: netdb.hnetdb.h

C structure: C structure: protoentprotoent

Keyed lookup functions:Keyed lookup functions:– getprotobyname()getprotobyname()– getprotobynumber()getprotobynumber()

240-491 Adv. UNIX: info/19 29

6. 6. /etc/services/etc/services

Stores details on the network services Stores details on the network services supported by the systemsupported by the system– built on top of network protocolsbuilt on top of network protocols

Fragment of Fragment of /etc/services/etc/servicesftpftp 21/tcp21/tcpsmtpsmtp 25/tcp25/tcp mailmail

::ircirc 194/tcp194/tcp # internet relay chat# internet relay chatircirc 194/udp194/udp ::

240-491 Adv. UNIX: info/19 30

Accessing Accessing /etc/services/etc/services

Header: Header: netdb.hnetdb.h

C structure: C structure: serventservent

Keyed lookup functions:Keyed lookup functions:– getservbyname()getservbyname()– getservbyport()getservbyport()

240-491 Adv. UNIX: info/19 31

7. Login Accounting7. Login Accounting

/var/run/utmp/var/run/utmp

– records which users are currently logged inrecords which users are currently logged in– used by used by whowho, , usersusers, , fingerfinger, , psps– may be located in may be located in /var/adm//var/adm/

/var/log/wtmp/var/log/wtmp

– records all logins, logouts, shutdowns, rebootsrecords all logins, logouts, shutdowns, reboots– used by used by lastlast

– may be located in may be located in /var/adm//var/adm/

240-491 Adv. UNIX: info/19 32

File FormatFile Format

Both files are binary files Both files are binary files (unlike all the previous examples). (unlike all the previous examples).

Each record has the basic form:Each record has the basic form:struct utmp {struct utmp { char ut_line[8]; char ut_line[8];

/* ttty line: ttyp0, etc. */ /* ttty line: ttyp0, etc. */ char ut_name[8]; char ut_name[8]; /* login name */ /* login name */ long ut_time; long ut_time;

/* secs since 1st Jan 1970 */ /* secs since 1st Jan 1970 */}}

240-491 Adv. UNIX: info/19 33

At login:At login:– create a create a utmputmp struct, add to struct, add to utmputmp and and wtmpwtmp files files

At logout:At logout:– entry in entry in utmputmp is wiped (filled with 0s) is wiped (filled with 0s)– new entry added to new entry added to wtmpwtmp, with, with ut_nameut_name filled with filled with ‘\0’‘\0’ characters characters

At shutdown, reboot, time change:At shutdown, reboot, time change:– special entries added to special entries added to wtmpwtmp

240-491 Adv. UNIX: info/19 34

Linux Linux utmputmp & & wtmpwtmp (non-standard) (non-standard)

struct utmp { short ut_type; /* login type */ pid_t ut_pid; /* process pid */ char ut_line[UT_LINESIZE];

/* device name */ char ut_id[2]; /* abbrev ttyname */ time_t ut_time; /* login time */ char ut_user[UT_NAMESIZE]; /* uname */ char ut_host[UT_HOSTSIZE]; /* host nm */ long ut_addr; /* host address */

:}

$ man 5 utmp

240-491 Adv. UNIX: info/19 35

String fields String fields maymay end with end with ‘\0’‘\0’ if there is enough if there is enough space!space!

Some login types:Some login types:– UT_UNKNOWNUT_UNKNOWN unknownunknown– BOOT_TIMEBOOT_TIME started at system bootstarted at system boot– INIT_PROCESSINIT_PROCESS started at system initstarted at system init– LOGIN_PROCESSLOGIN_PROCESS login processlogin process– USER_PROCESSUSER_PROCESS user-created processuser-created process– DEAD_PROCESSDEAD_PROCESS dead (zombie)dead (zombie)

240-491 Adv. UNIX: info/19 36

Accessing Accessing utmp/wtmputmp/wtmp Entries Entries

#include <utmp.h>

void utmpname(char *file);void setutent(void);void endutent(void);

struct utmp *getutent(void);struct utmp *getutid(struct utmp *ut);struct utmp *getutline(struct utmp *ut);

void pututline(struct utmp *ut);

240-491 Adv. UNIX: info/19 37

utmpname()utmpname() can be supplied with the default can be supplied with the default pathnames stored in pathnames stored in _PATH_UTMP_PATH_UTMP and and _PATH_WTMP_PATH_WTMP in in <paths.h><paths.h>..

getutline()getutline() is restricted to entries with is restricted to entries with login type login type LOGIN_PROCESSLOGIN_PROCESS and and USER_PROCESSUSER_PROCESS..

Updates can only be done by Updates can only be done by rootroot..

240-491 Adv. UNIX: info/19 38

Example: Example: sw.csw.c, a simple , a simple whowho

#include <stdio.h>#include <string.h>#include <utmp.h>#include <pwd.h>#include <time.h> /* for ctime() */

int main(){ struct utmp *ut; struct passwd *pw; char name[UT_NAMESIZE+1];

utmpname(“/var/run/utmp”); setutent();

:

240-491 Adv. UNIX: info/19 39

while ((ut = while ((ut = getutent()) != NULL) {()) != NULL) { if (ut->ut_user[0] != ‘\0’) { if (ut->ut_user[0] != ‘\0’) { strncpy(name,ut->ut_user,UT_NAMESIZE); strncpy(name,ut->ut_user,UT_NAMESIZE); name[UT_NAMESIZE] = ‘\0’; name[UT_NAMESIZE] = ‘\0’; if ((pw = getpwnam(name)) == NULL) if ((pw = getpwnam(name)) == NULL) printf(“%s has no passwd!\n”,name); printf(“%s has no passwd!\n”,name); else else printf(“%s %s %s %s”, name, printf(“%s %s %s %s”, name,

ut->ut_line, pw->pw_gecos,ut->ut_line, pw->pw_gecos,ctime(&(ut->ut_time)) );ctime(&(ut->ut_time)) );

} } } } endutent();(); return 0; return 0;}}

240-491 Adv. UNIX: info/19 40

UsageUsage $ sw$ sw

reboot has no password!reboot has no password!runlevel has no password!runlevel has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!LOGIN has no password!s4210075 pts/0 ????,,, Thu Feb 15 15:56:33 2001s4210075 pts/0 ????,,, Thu Feb 15 15:56:33 2001ad pts/5 Dr.Andrew DAVISON,,, Thu Feb 15 16:00:17 2001ad pts/5 Dr.Andrew DAVISON,,, Thu Feb 15 16:00:17 2001s4010041 pts/6 MR. Kemarat CHAIYO,,, Thu Feb 15 15:32:36 2001s4010041 pts/6 MR. Kemarat CHAIYO,,, Thu Feb 15 15:32:36 2001s4010237 pts/7 MR. Paween CHOKENUKUL,,, Thu Feb 15 15:58:57 2001s4010237 pts/7 MR. Paween CHOKENUKUL,,, Thu Feb 15 15:58:57 2001s4010041 pts/8 MR. Kemarat CHAIYO,,, Thu Feb 15 15:34:00 2001s4010041 pts/8 MR. Kemarat CHAIYO,,, Thu Feb 15 15:34:00 2001$ $

240-491 Adv. UNIX: info/19 41

““Simple Simple whowho” returns similar information ” returns similar information to to whowho, but also includes details about:, but also includes details about:– system processessystem processes– dead user processesdead user processes

NotesNotes

240-491 Adv. UNIX: info/19 42

lastlast

Displays Displays wtmpwtmp in an understandable form. in an understandable form.

Lists all logins, logouts, etc. since file creation.Lists all logins, logouts, etc. since file creation.

$ last$ lastrich rich ttypbttypb mit.usa mit.usa Tue Aug 19 Tue Aug 19 13:19 still logged in13:19 still logged inzonkzonk ttyp3ttyp3 129.10.1.22 Tue Aug 19 13:12 - 13:14 (00:02)129.10.1.22 Tue Aug 19 13:12 - 13:14 (00:02)rich rich ttypattypa lisa.ac.thlisa.ac.th Tue Aug 19 Tue Aug 19 13:11 still logged in13:11 still logged inzonk zonk ttyp3ttyp3 lennylenny Tue Aug 19 Tue Aug 19 12:06 - 12:21 (00:14)12:06 - 12:21 (00:14)

::

continued

240-491 Adv. UNIX: info/19 43

$ last rich$ last richrich rich ttypbttypb mit.usamit.usa Tue Aug 19 13:19 still logged inTue Aug 19 13:19 still logged inrich rich ttypattypa foo.lisa.ac.th Tue Aug 19 13:11 still logged infoo.lisa.ac.th Tue Aug 19 13:11 still logged inrich rich ttyp0ttyp0 goo.lisa.ac.th Mon Aug 18 11:01 - 11:45 (00:44)goo.lisa.ac.th Mon Aug 18 11:01 - 11:45 (00:44)rich rich ftpftp mit.usamit.usa Sat Aug 16 00:03 - 00:04 (00:01)Sat Aug 16 00:03 - 00:04 (00:01)

::

$ last | grep boot$ last | grep bootreboot System boot Fri Aug 15 22:15reboot System boot Fri Aug 15 22:15reboot System boot Fri Aug 15 15:21reboot System boot Fri Aug 15 15:21reboot System boot Fri Aug 4 17:24reboot System boot Fri Aug 4 17:24reboot System boot Fri Aug 4 15:41reboot System boot Fri Aug 4 15:41

240-491 Adv. UNIX: info/19 44

8. The System Log: 8. The System Log: syslogsyslog

syslogduserprocess

/dev/log UDPport 514

/dev/klog

kernelroutines

Unix domaindatagram socket

Internet domaindatagram socket

TCP/IP network

syslog()

files, consoleor e-mail

Kernel

log()

$ man 8 syslogd

240-491 Adv. UNIX: info/19 45

Logging MessagesLogging Messages Any program can generate log messages.Any program can generate log messages.

A log message should include:A log message should include:– the program name, a facility, a priority, and the the program name, a facility, a priority, and the

message textmessage text

Example:Example:login: Root LOGIN REFUSED on ttyalogin: Root LOGIN REFUSED on ttya

– sent by an authorization facility (sent by an authorization facility (loginlogin); it is critical); it is critical

240-491 Adv. UNIX: info/19 46

Some Some syslogsyslog Facilities Facilities NameName FacilityFacilitykernkern The kernel.The kernel.useruser Regular user processes.Regular user processes.mailmail The mail system.The mail system.lprlpr The printer system.The printer system.

::authauth The authorization system, or The authorization system, or

programs that ask for user names programs that ask for user names and passwords (e.g. and passwords (e.g. loginlogin, , susu, , gettygetty, , ftpftp).).

240-491 Adv. UNIX: info/19 47

Some Syslog Priorities (levels)Some Syslog Priorities (levels)

PriorityPriority MeaningMeaningemergemerg Emergency (e.g. crash).Emergency (e.g. crash).alertalert Fix immediately (e.g. bad db).Fix immediately (e.g. bad db).critcrit Critical (e.g. hardware error).Critical (e.g. hardware error).errerr Ordinary error.Ordinary error.

::noticenotice Not an error, but important.Not an error, but important.

::debugdebug Debug messages.Debug messages.

240-491 Adv. UNIX: info/19 48

Configuring Configuring syslogsyslog

At system start-up, it reads the At system start-up, it reads the /etc/syslog.conf/etc/syslog.conf configuration file. configuration file.

syslog.confsyslog.conf specifies specifies whatwhat messages to log, messages to log, and and wherewhere to log them to log them– see see $ man 5 syslog.conf$ man 5 syslog.conf

240-491 Adv. UNIX: info/19 49

General format of a General format of a syslog.confsyslog.conf line: line:facility.priorityfacility.priority actionaction

facilityfacility and and prioritypriority can be one of the labels listed in can be one of the labels listed in the ealier slides (or the ealier slides (or ** to mean all) to mean all)

actionaction can be: can be:– log to a file / device / programlog to a file / device / program– send message to a usersend message to a user– send message to all users (*)send message to all users (*)– send message to another machinesend message to another machine

240-491 Adv. UNIX: info/19 50

Typical Typical syslog.confsyslog.conf file file

kern.debug /dev/console*.err /dev/consoleauth.notice /usr/adm/messageslpr.* /usr/adm/lpd-errsauth.* root,adauth.*@catsix.coe.psu.ac.thauth.* /dev/console*.emerg *

$ man 5 syslog.conf

240-491 Adv. UNIX: info/19 51

Some Some critical authcritical auth messages messages

ProgramProgram MessageMessagehalt halted by <user>

login ROOT LOGIN REFUSED ON<tty> [FROM <host>]

login REPEATED LOGIN FAILURESON <tty> [FROM <host>]

<user>

su BAD SU <user> ON <tty>

240-491 Adv. UNIX: info/19 52

Some Some notice authnotice auth messages messages

ProgramProgram MessageMessagedate date set by <user>

login ROOT LOGIN <tty>[FROM <host>]

su <user> on <tty>

240-491 Adv. UNIX: info/19 53

The The syslog()syslog() Function Function

#include <syslog.h>

void openlog(char *ident, int option, int facility);

void syslog(int priority, char *format, ...);

void closelog(void);

$ man 3 syslog

240-491 Adv. UNIX: info/19 54

Some Some openlog()openlog() Options Options

OptionOption MeaningMeaningLOG_CONSLOG_CONS If If syslogdsyslogd is ‘down’, send is ‘down’, send

the message to the console.the message to the console.

LOG_PIDLOG_PID Log the process ID.Log the process ID.

LOG_PERRORLOG_PERROR Print to Print to stderrstderr as well. as well.::

240-491 Adv. UNIX: info/19 55

Some Some openlog()openlog() Facilities Facilities

FacilityFacility MeaningMeaningLOG_USERLOG_USER User-process message.User-process message.

LOG_MAILLOG_MAIL Mail system.Mail system.

LOG_LPRLOG_LPR Printer system.Printer system.

LOG_AUTHLOG_AUTH An authorization program.An authorization program.::

240-491 Adv. UNIX: info/19 56

Some Some syslog()syslog() Priorities Priorities

PriorityPriority MeaningMeaningLOG_EMERGLOG_EMERG EmergencyEmergencyLOG_ALERTLOG_ALERT AlertAlertLOG_CRITLOG_CRIT CriticalCriticalLOG_ERRLOG_ERR ErrorError

::LOG_NOTICELOG_NOTICE NoticeNotice

::LOG_DEBUGLOG_DEBUG DebugDebug

240-491 Adv. UNIX: info/19 57

ExamplesExamples Postscript printer program:Postscript printer program:

openlog(“lprps”, LOG_PID, LOG_LPR);openlog(“lprps”, LOG_PID, LOG_LPR);syslog(LOG_ERR, “open error for %s”, syslog(LOG_ERR, “open error for %s”,

filename);filename);

Without the Without the openlog()openlog() call: call:syslog(LOG_ERR | LOG_LPR, syslog(LOG_ERR | LOG_LPR,

“open error for %s”, filename);“open error for %s”, filename);

combined priorityand facility

240-491 Adv. UNIX: info/19 58

UNIX UNIX loggerlogger loggerlogger

– can specify facility, priority, identifiercan specify facility, priority, identifier– intended for logging in non-interactive shell scriptsintended for logging in non-interactive shell scripts– simple version:simple version:

logger [-p priority] [message]logger [-p priority] [message]

e.g.e.g.$ logger System Rebooted$ logger System Rebooted

$ logger -p auth.notice $ logger -p auth.notice

240-491 Adv. UNIX: info/19 59

9. Process Information9. Process Information

lastcommlastcomm

– displays information on previously executed displays information on previously executed commandscommands

– examples:examples:$ lastcomm$ lastcomm

$ lastcomm ad$ lastcomm ad

$ lastcomm ftp$ lastcomm ftp

$ lastcomm ad ftp$ lastcomm ad ftp

$ lastcomm --strict-match --user ad $ lastcomm --strict-match --user ad --command ftp--command ftp

240-491 Adv. UNIX: info/19 60

ExampleExample

$ lastcomm $ lastcomm croncron FF rootroot ???? 0.08 secs Mon Sep 19 15:060.08 secs Mon Sep 19 15:06datedate martinmartin ttyp7ttyp7 0.02 secs Mon Sep 19 15:060.02 secs Mon Sep 19 15:06shsh smithsmith ttyp3ttyp3 0.05 secs Mon Sep 19 15:040.05 secs Mon Sep 19 15:04cshcsh ngng ttypfttypf 3.45 secs Mon Sep 19 14:533.45 secs Mon Sep 19 14:53calculus Dcalculus D chavez chavez ttyq8ttyq8 0.95 secs Mon Sep 19 15:090.95 secs Mon Sep 19 15:09moremore XX ng ng ttypfttypf 0.17 secs Mon Sep 19 15:030.17 secs Mon Sep 19 15:03ruptimeruptime martin martin console 0.14 secs Mon Sep 19 15:03console 0.14 secs Mon Sep 19 15:03mailmail SS root root ttyp0ttyp0 0.95 secs Fri Sep 16 10:460.95 secs Fri Sep 16 10:46

::

Not working on calvin;fine on fivedots

240-491 Adv. UNIX: info/19 61

On linux, On linux, lastcommlastcomm examines the binary examines the binary file file /var/account/pacct/var/account/pacct

The letter flags meaning:The letter flags meaning:SS command was run by superuser;command was run by superuser;

FF command ran after a fork;command ran after a fork;

DD command terminated with a core dump;command terminated with a core dump;

XX command was terminated with a signalcommand was terminated with a signal(e.g. a control-c).(e.g. a control-c).

240-491 Adv. UNIX: info/19 62

Accessing Accessing /var/account/pacct/var/account/pacct

Use Use <linux/acct.h><linux/acct.h>::#define ACCT_COMM 16struct acct { char ac_comm[ACCT_COMM]; /* cmd */ time_t ac_utime; /* user time */ time_t ac_stime; /* sys time */ time_t ac_etime; /* elapsed time */ time_t ac_btime; /* begin time */ uid_t ac_uid; /* user ID */ gid_t ac_gid; /* group ID */ dev_t ac_tty; /* dev. no. */ char ac_flag; /* flags */

:

$ man 5 acct

240-491 Adv. UNIX: info/19 63

ac_flagac_flag Bit Values Bit Values

Bit ConstantBit Constant MeaningMeaning

ASUASU Command was run by superuser.Command was run by superuser.

AFORKAFORK Command ran after a fork.Command ran after a fork.

ACOREACORE Command terminated with Command terminated with a core dump.a core dump.

AXSIGAXSIG Command was terminated with Command was terminated with a signal (e.g. a control-c).a signal (e.g. a control-c).

240-491 Adv. UNIX: info/19 64

Example: Example: slc.cslc.c, a Simple , a Simple lastcommlastcomm

#include <stdio.h>#include <time.h>#include <sys/types.h>#include <linux/acct.h>#define ACC “/var/account/pacct”

int main(){ struct acct ac; FILE *fp; if ((fp = fopen(ACC,”rb”)) == NULL){ printf(“Cannot open %s\n”, ACC); exit(1); }

:

continued

Works on fivedots

240-491 Adv. UNIX: info/19 65

while ((fread(&ac, sizeof(struct acct),while ((fread(&ac, sizeof(struct acct), 1, fp) == 1) 1, fp) == 1)

printf(“%10s %5d %c%c%c%c %s”, printf(“%10s %5d %c%c%c%c %s”,ac.ac_comm, ac.ac_uid,ac.ac_comm, ac.ac_uid,ac.ac_flag & ACORE ? ‘D’ : ‘ ‘,ac.ac_flag & ACORE ? ‘D’ : ‘ ‘,ac.ac_flag & AXSIG ? ‘X’ : ‘ ‘,ac.ac_flag & AXSIG ? ‘X’ : ‘ ‘,ac.ac_flag & AFORK ? ‘F’ : ‘ ‘,ac.ac_flag & AFORK ? ‘F’ : ‘ ‘,ac.ac_flag & ASU ? ‘S’ : ‘ ‘,ac.ac_flag & ASU ? ‘S’ : ‘ ‘,ctime(&(ac.ac_btime)) );ctime(&(ac.ac_btime)) );

fclose(fp); fclose(fp); return 0; return 0;}}

240-491 Adv. UNIX: info/19 66

Usage (on fivedots)Usage (on fivedots)

$ ./slc | more$ ./slc | more accton 0 S Thu Feb 15 06:25:03 2001 accton 0 S Thu Feb 15 06:25:03 2001 acct 0 Thu Feb 15 06:25:03 2001 acct 0 Thu Feb 15 06:25:03 2001 acct 0 Thu Feb 15 06:25:02 2001 acct 0 Thu Feb 15 06:25:02 2001 date 0 Thu Feb 15 06:25:03 2001 date 0 Thu Feb 15 06:25:03 2001 tr 0 Thu Feb 15 06:25:03 2001 tr 0 Thu Feb 15 06:25:03 2001 apache 0 F Thu Feb 15 06:25:03 2001 apache 0 F Thu Feb 15 06:25:03 2001

::

240-491 Adv. UNIX: info/19 67

10. System Information10. System Information

#include <sys/utsname.h>#include <sys/utsname.h>int uname(struct utsname *name);int uname(struct utsname *name);

Return info. on the current host and OS;Return info. on the current host and OS;returns non-negative value if ok, -1 on returns non-negative value if ok, -1 on error.error.

UNIX interface: UNIX interface: unameuname

$ uname --all$ uname --all

240-491 Adv. UNIX: info/19 68

struct utsnamestruct utsname

struct utsname { char sysname[SYS_NMLN]; /* OS name */ char nodename[SYS_NMLN]; /* node name */ char release[SYS_NMLN]; /* OS release */ char version[SYS_NMLN]; /* OS version */ char machine[SYS_NMLN]; /* hdwr name */ char domainname[SYS_NMLN]; }

$ man 2 uname