DB에서 값을 받아와 iptables를 적용할려고 합니다. 도움요청이요~

huhspunk의 이미지

원격지 DB에 있는 IP값을 받아와서 이것이 1이면 iptables를 적용할려고 하고 있습니다.
그리고 매 5초마다 while을 돌려 select를 하고 있는데요..여기서 문제가
select를 할때마다 iptables에 적용되어버려 중복 되고 맙니다-_-
하루죙일 씨름중인데 어떻게 헤쳐나가야 할까요?;

#include
#include
#include
#include
#include
#include

#define NAME_SIZE 50
#define BUFSIZE 30
#define LINE_SIZE 256
#define LINE_BUF 10000

pthread_mutex_t mutx;

MYSQL mysql;
MYSQL_RES *res_ptr;
MYSQL_ROW row;

int db_init();
int mysql_mutx_query(char *query, int size);
void select_ipdrop();
char ipdrop(char *s1,char *s2);
char * mystrcat(char * dest, char * src);

int main(int argc, char **argv)
{
db_init();
mysql_close(&mysql);
return 0;
}
int mysql_mutx_query(char *query, int size)
{
int result;
/* 뮤텍스 lock */
pthread_mutex_lock(&mutx);
if(mysql_real_query(&mysql, query, size))
{
result = 1;
}
else
{
result = 0;
}
/* 뮤텍스 unlock */
pthread_mutex_unlock(&mutx);
return result;
}
int db_init()
{
char db_name[NAME_SIZE];
char db_user[NAME_SIZE];
char db_passwd[NAME_SIZE];

memset(db_name,'\0', NAME_SIZE);
memset(db_user,'\0',NAME_SIZE);
memset(db_passwd,'\0',NAME_SIZE);

const char del_line[] = "=\t";
int size,str_len;
char *token;
char file_buf[LINE_BUF];
char send_msg[10240];
memset(send_msg,'\0',10240);

int res;

FILE* fp;
if((fp = fopen("sams1.ini", "r")) == NULL)
{
printf("125 Can't read sams.ini file\n");
exit(1);
}

while(!feof(fp))
{
memset(file_buf,'\0',LINE_BUF);
fgets(file_buf,LINE_BUF,fp);
//주석넘김
if(strchr(file_buf,'#')==NULL) // '#'문자가 있는지 검사한다.
{
/* 데이터 베이스 이름 갖고 오기*/
if(strstr(file_buf,"db_name")) // 문자열내에 db_name이 있는지 판단한다.
{
strtok(file_buf,del_line);
token = strtok(NULL,del_line); // '\t'로 자른다.
size = strlen(token);

if(size > NAME_SIZE)
{
printf("126 db_user value is very long\n");
exit(1);
}
else
{
strncpy(db_user,token,size); // size수값으로 token의 내용을 db_user에게 대입한다.
}
strncpy(db_name,token,NAME_SIZE); //토큰의 끝이 '\' 문자인지 체크
if(db_name[size-1] == '\n') // 토큰의 끝이 '\' 문자인지 체크
{
db_name[size-1] = '\0';
}
}
/* 데이터베이스 사용자 이름 갖고 오기 */
else if(strstr(file_buf,"db_user"))
{
strtok(file_buf,del_line);
token = strtok(NULL,del_line);
size = strlen(token);

if(size > NAME_SIZE)
{
printf("126 db_user value is very long\n");
exit(1);
}
else
{
strncpy(db_user,token,size);
}
if(db_user[size-1] == '\n')
{
db_user[size-1] = '\0';
}
}
/* 데이터베이스 사용자 비번 갖고오기 */
else if(strstr(file_buf,"db_passwd"))
{
strtok(file_buf,del_line);
token = strtok(NULL,del_line);
size = strlen(token);

if(size > NAME_SIZE)
{
printf("126 db_passwd value is very long\n");
exit(1);
}
else
{
strncpy(db_passwd,token,size);
}
if(db_passwd[size-1] == '\n')
{
db_passwd[size-1] = '\0';
}

}
}
}

fclose(fp);
mysql_init(&mysql);

if(!(mysql_real_connect(&mysql,"192.168.0.1",db_user,db_passwd,db_name,0,(char*)NULL,0)))
{
fprintf(stderr," connecting db failed : %s\n",mysql_error(&mysql));
return -1;
}
else
{
printf("Connection Success!!\n");
}
select_ipdrop();
return 0;
}
void select_ipdrop()
{
unsigned int cnt;
int res, i, str_len;
char str[LINE_BUF];
char str1[LINE_BUF];
char str2[LINE_BUF];
char query[LINE_BUF];
char err_msg[LINE_BUF];
str[0] = '\0';
while(1)
{
sprintf(query,"select ip,attention from ipdrop;");
if(mysql_mutx_query(query,strlen(query)))
{
memset(err_msg,'\0',LINE_BUF);
}
else
{
res_ptr = mysql_store_result(&mysql);
if(res_ptr)
{
printf("검색row %lu rows\n",(unsigned int) mysql_num_rows(res_ptr));
while((row = mysql_fetch_row(res_ptr)) != NULL)
{
strcpy(str1,str);
sprintf(str,"%s\n",row[0]);
sprintf(str1,"%s\n",row[1]);
strcpy(str2,str);
ipdrop(str,str1);
}
}
}
sleep(5);
}
mysql_free_result(res_ptr);
}

//iptables 적용부분
char ipdrop(char *s1, char *s2)
{
char ip[10][10], attention[10];
char buffer[LINE_BUF];
char cmp[1] = "1";
int i;

sscanf(s1,"%s",ip);
sscanf(s2,"%s",attention);

printf("%s %s\n",ip,attention);
if(attention[0] == cmp[0])
{
sprintf(buffer,"iptables -A INPUT -s %s -j DROP",ip);
system(buffer);
}
else
{
sprintf(buffer,"iptables -D INPUT -s %s -j DROP",ip);
system(buffer);
}

}

huhspunk의 이미지

꼼수지만;
void select_ipdrop()함수안에
iptables -F <이것을 삽입해주어서 해결했습니다.
sleep(5)이부분 뒤에 system함수로 명령어를 실행시켰습니다.
다른 방법도 찾아봤지만 가령 우분투에서는 iptables-save > /etc/iptables.rules를 생성시켜서
파일로 접근할려고 했는데 도무지 안되더군요; 문제는 많은 양의 차단 ip들을 파일 중간에 삽입시키기가 영 어렵더군요.
제 실력부족탓이죠; 파일 끝에 삽입은 가능하나 중간에 삽입하면 마지막 하나만 삽입되는 경우가 있어서 답이 나오질 않았습니다.
그나마 문자열배열에 대해 많이 배웠네요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.