Write two library functions in C programming language for system calls (A setter
ID: 3912372 • Letter: W
Question
Write two library functions in C programming language for system calls (A setter method for setting the security tag value in Linux) and (A getter method for getting the security tag value in Linux)
int set_security_tag(const char *filename, int new_tag)
{
// Invokes the system call which attempts to change the file's Security_Tag to new_tag
// Returns the changed Security_Tag on success, otherwise it returns "-1"
}
int get_security_tag(const char *filename)
{
// Invokes a system call which reads the security tag of the input file
// It will return Security_Tag upon success; otherwise it will return a value of "-1"
}
Explanation / Answer
Answer: See the code below:
----------------------------------------------------
#include <sys/types.h>
#include <sys/xattr.h>
#include <stdio.h>
#include <stdlib.h>
//set_security_tag function
int set_security_tag(const char *filename, int new_tag)
{
int status;
status=setxattr(filename, "Security_Tag", &new_tag, sizeof(new_tag), 0);
if (status==0)
return new_tag;
else
return -1;
}
//get_security_tag function
int get_security_tag(const char *filename)
{
ssize_t sz; //size of value of attribute
int* value; //value of attribute
//determine size of value of attribute
sz=getxattr(filename,"Security_Tag",NULL,0);
//check if ok
if (sz == -1)
fprintf(stderr,"error in extracting size. ");
//allocate space for value of attribute
if (sz > 0)
{
value = (int*)malloc(sizeof(int));
//get value of attribute
sz = getxattr(filename, "Security_Tag", value, sz);
if (sz == -1)
return -1;
else
return *value;
}
}
//main function
int main()
{
char* filename = "./tlpi_hdr.h"; //example file
int new_tag = 2; //value of security tag
//setting security tag
new_tag = set_security_tag(filename,new_tag);
if(new_tag!=-1)
printf("Security tag set successfully ");
else
printf("Security tag not set successfully ");
//getting security tag
new_tag = get_security_tag(filename);
if(new_tag!=-1)
printf("Security tag retrieved successfully: %d ",new_tag);
else
printf("Security tag not retrieved successfully: %d ",new_tag);
return EXIT_SUCCESS;
}
------------------------------------------
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.