Du kan kigge lidt på det her:
[/pre]
#include <stdio.h>
#include <string.h>
#include <mysql.h>
int main (int argc, char ** argv)
{
MYSQL mysql;
MYSQL_RES * res = NULL;
MYSQL_ROW row;
int i;
char sql[1024];
if (argc != 3) {
printf("Usage: %s username password\\n", argv[0]);
return 0;
}
snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM Users WHERE username='%s' AND password='%s'", argv[1], argv[2]);
if (mysql_init(&mysql) == NULL) {
fprintf(stderr, "mysql_init: %s\\n", mysql_error(&mysql));
exit(-1);
}
if (mysql_real_connect(&mysql, "localhost", "robert", "keumgang", "test", 3306, NULL, 0) == NULL) {
fprintf(stderr, "mysql_real_connect: %s\\n", mysql_error(&mysql));
mysql_close(&mysql);
exit(-1);
}
printf("Executing: %s\\n", sql);
if (mysql_real_query(&mysql, sql, strlen(sql)) != 0) {
fprintf(stderr, "mysql_real_query: %s\\n", mysql_error(&mysql));
mysql_close(&mysql);
exit(-1);
}
res = mysql_store_result(&mysql);
if (res) {
if ((row = mysql_fetch_row(res))) {
if (strcmp(row[0], "1") == 0) {
printf("User is authenticated\\n");
} else {
printf("BAD user\\n");
}
}
}
mysql_free_result(res);
res = NULL;
mysql_close(&mysql);
return 0;
}
[/pre]
Jeg beder databasen om at tælle antallet af brugere som har et bestemt brugernavn OG password. Hvis antallet er "1" så er brugeren ok...ellers ikke.
robert@robert:~/code/Sudoku$ ./test BadUserName BadPassWord
Executing: SELECT COUNT(*) FROM Users WHERE username='BadUserName' AND password='BadPassWord'
BAD user
robert@robert:~/code/Sudoku$ ./test someuser somepassword
Executing: SELECT COUNT(*) FROM Users WHERE username='someuser' AND password='somepassword'
User is authenticated
robert@robert:~/code/Sudoku$
Dette er kun et eksempel og et meget dårligt et af slagsen for det tillader en angriber at benytte sig af SQL injection. F.eks.:
robert@robert:~/code/Sudoku$ ./test blar "' OR 'blar'='blar"
Executing: SELECT COUNT(*) FROM Users WHERE username='blar' AND password='' OR 'blar'='blar'
User is authenticated
robert@robert:~/code/Sudoku$
For at undgå dette skal man escape al input. Dvs. erstate tegnene:
"
'
\
med
\\"
\\'
\\\
Måske også andre.