I'm using ulog2 with mysql for gathering nf_conntrack values to DB in my bridge machine.
All things are works well, but I want to prevent to insert specific value which has "right(hex(orig_ip_saddr),8)='7f000001'".
I just execute query as "delete from ulog2_ct where right(hex(orig_ip_saddr),8)='7f000001' " periodically but its not good solution.
ulog2 provide queries to make and insert into the specific DB as https://github.com/inliniac/ulogd2/blob/master/doc/mysql-ulogd2-flat.sql
But I can't fully understand because I'm not sql expert.
I think some additional query would resolve what I want but I don't know how.
Insert query of mysql-ulogd2-flat.sql is as below: (line 435)
BEGIN
INSERT INTO ulog2_ct (oob_family, orig_ip_saddr, orig_ip_daddr, orig_ip_protocol,
orig_l4_sport, orig_l4_dport, orig_bytes, orig_packets,
reply_ip_saddr, reply_ip_daddr, reply_ip_protocol,
reply_l4_sport, reply_l4_dport, reply_bytes, reply_packets,
icmp_code, icmp_type, ct_mark,
flow_start_sec, flow_start_usec,
flow_end_sec, flow_end_usec)
VALUES (_oob_family, _orig_ip_saddr, _orig_ip_daddr, _orig_ip_protocol,
_orig_l4_sport, _orig_l4_dport, _orig_bytes, _orig_packets,
_reply_ip_saddr, _reply_ip_daddr, _reply_ip_protocol,
_reply_l4_sport, _reply_l4_dport, _reply_bytes, _reply_packets,
_icmp_code, _icmp_type, _ct_mark,
_flow_start_sec, _flow_start_usec,
_flow_end_sec, _flow_end_usec);
RETURN LAST_INSERT_ID();
END
Seo.
Just create a trigger on ulog2_ct
(check for syntax validation , as I have just typed it here)
CREATE TRIGGER trig_ulog2_ct
BEFORE INSERT ON ulog2_ct
FOR EACH ROW
BEGIN
DECLARE msg VARCHAR(255);
IF (right(hex(new.orig_ip_saddr),8)='7f000001') THEN
SIGNAL 'your error message Not to insert'
END IF;
END
Let us know
Related
I am working on an API in Node/JavaScript with a MySQL database. I think this is a question not related to Node/JavaScript, just SQL, but I'm not sure about that.
Here I have a minimal example. Lets say I have a stored procedure to create an user:
DROP PROCEDURE IF EXISTS users_create;
CREATE PROCEDURE users_create(
IN user JSON
)
BEGIN
-- Retrieve values from JSON
SET #name = JSON_EXTRACT(user, '$.name');
SET #email = JSON_EXTRACT(user, '$.email');
SET #password = JSON_EXTRACT(user, '$.password');
SET #uuid = uuid();
-- Insert new user
INSERT INTO user (`id`, `name`, `email`, `password`) VALUES (
#uuid,
JSON_UNQUOTE(#name),
JSON_UNQUOTE(#email),
JSON_UNQUOTE(#password)
);
-- Retrieve created user
SELECT `id`, `name`, `email`, `status`, `createdAt` FROM user
WHERE id = #uuid;
END
Now I have a new user object —Javascript—:
const newUser = {
name: "This is me",
email: "me#example.com",
password: "strong_password",
}
And I call the procedure:
const createUserQuery = `CALL users_create('${JSON.stringify(newUser)}')`;
My question is: given that I'm using JSON to pass the data, and I'm using JSON_EXTRACT and JSON_UNQUOTE, am I prone to SQL injection here?
No, you are not prone to SQL injection. You might have other problems with the code. And your code might be unsafe if -- say -- the password is not encrypted.
However, the only SQL code that will run is the SQL in the stored procedure.
SQL injection is associated with dynamic SQL. That is SQL that is constructed from a string. A SQL injection account alters ("enhances"?) the string to do dangerous things. Your code is just assigning values in an insert. These might be wrong, but they will not cause any other statements to run.
The main program is based on PyQt5 client and stores information on a MySql DB. The issue is that I need to import data from an MS Access DB (done by a QSqlQuery using the QODBC) load in a query (qryImport). I set a temporary table using a new connection (self.tempDb) to transfer the information to MySQL and I'm running a store procedure on a while loop to insert the data into MySql one record at a time. The problem is that we get the infamous "commands out of sync..."error when running the second while cycle, or in debug mode (PyCharm) as soon as I speed up the process. Could not find an answer to the problem over the net but the "Commands out of sync" form of the MySql Reference Manual https://dev.mysql.com/doc/refman/8.0/en/commands-out-of-sync.html that in my case was not very helpful.
I also try to close the connection and open the connection and clear the query after executing each cycle which takes care of the out of sync issue, but deletes the temporary tables on the connection in both cases besides not being very efficient.
Most of the information I found about it is referring either to PHP or python's MSQLDB, so I was not able to implement the manual´s recommendation of using msql_free_result() or msql_store_result() since I couldn't figure out how to do it.
I would appreciate any advise addressing this issue.
In the mean time I will try to use a permanent table as a workaround - that I don't like - or to export the query from MS Access to MySql eventually.
# ............................................
qryImport.seek(-1)
qry = QSqlQuery(self.tempDb)
qry.prepare("CALL importhorses_loaddata(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
while qryImport.next():
qry.addBindValue(QVariant(qryImport.value(0))) # accessid
qry.addBindValue(QVariant(qryImport.value(1))) # name
qry.addBindValue(QVariant(qryImport.value(2))) #rp
qry.addBindValue(QVariant(qryImport.value(3).toString("yyyy-MM-dd"))) #BirthDate
qry.addBindValue(QVariant(qryImport.value(4))) #sexid
qry.addBindValue(QVariant(qryImport.value(5))) #coatid
qry.addBindValue(QVariant(qryImport.value(6))) #isbreakable
qry.addBindValue(QVariant(qryImport.value(7))) #isBroke
qry.addBindValue(QVariant(qryImport.value(8))) #isPlayer
qry.addBindValue(QVariant(qryImport.value(9))) #Father
qry.addBindValue(QVariant(qryImport.value(10))) #Mother
qry.addBindValue(QVariant(qryImport.value(11))) #UbicacionID
qry.addBindValue(QVariant(self.importDate.date().toString("yyyy-MM-dd"))) #ImportDate
qry.exec()
if qry.lastError().type() != 0:
raise DataError("importHorses", qry.lastError().text())
if qry.first():
print(qry.value(0))
# .....................................```
Stored Procedure:
CREATE PROCEDURE importhorses_loaddate(IN p_accessid INT,........., IN p_inputdate DATE)
BEGIN
DECLARE code CHAR(5) DEFAULT '00000';
DECLARE msg TEXT;
DECLARE _horsebaseid INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
code = RETURNED_SQLSTATE, msg = MESSAGE_TEXT;
SELECT code, msg;
ROLLBACK;
END;
START TRANSACTION;
SELECT horsebaseid FROM horses WHERE horsebaseid = p:accessid INTO _horsebaseid;
IF _horsebaseid != p_accessid THEN
INSERT INTO importedhorses(horsebaseid, ..........., inputdate)
VALUES(p_accessid, ......................, p_inputdate);
END IF;
COMMIT;
END
Can you help me resolve the error 'Truncated incorrect DOUBLE value' (Error Code 1292) in MySQL 6.3? I've searched for a solid hour and can't find a suitable answer in all the similar questions:
My task is to insert triggers into a database of movies. If someone tries to update an existing value or insert a new value into the schema 'made_money', then it is to be assured that the category falls into one of four base categories (see code). If it doesn't, default to "Action". I built and executed two triggers for this (because I don't know how to put UPDATE and INSERT into a single trigger):
delimiter //
CREATE TRIGGER movie_categories_A BEFORE UPDATE ON made_money
FOR EACH ROW
BEGIN
IF NEW.Category NOT IN ("Romantic", "Comedy", "Drama", "Action") THEN
SET NEW.Category = "Action";
END IF;
END;//
delimiter ;
delimiter //
CREATE TRIGGER movie_categories_B AFTER INSERT ON made_money
FOR EACH ROW
BEGIN
IF Category NOT IN ("Romantic", "Comedy", "Drama", "Action") THEN
SET Category = "Action";
END IF;
END;//
delimiter ;
Also, a new entry into 'log_data' has to be made when a new value is inserted into 'made_money', containing only the 'Movie' and 'Category' values.
delimiter //
CREATE TRIGGER condensed_test AFTER INSERT ON made_money
FOR EACH ROW
BEGIN
INSERT INTO log_data
SET Movie = NEW.Movie AND Category=NEW.Category;
END;//
delimiter ;
The three triggers all executed, although I'm not sure whether they are erroneous. Now my task is to insert a new entry into 'made_money':
INSERT INTO made_money (MOVIE,HOW_MUCH,DAY_OPENED,Category)
VALUES ('Iron Man', 1000000, '2008-05-02', 'ACTON');
I know that 'ACTON' is misspelled (I guess this is part of the exercise), yet unfortunately, this results in the following error:
Error Code: 1292. Truncated incorrect DOUBLE value: 'Iron Man'
The same happens if I spell 'Action' correctly. Please let me know if you have any ideas.
Best,
Jan
Try to change datatype for Movie, try by making it Text,
you can refer Similar issue
Please check the datatype 'made_money.Movie' and 'log_data.Movie'.
Please check the collation.
I am trying to use Database trigger and procedure to send sms I have create the table and I can insert data by:
use sms;
INSERT INTO sms_out (id, sender,receiver,msg)
VALUES ('','MyName','25578200000',"test");
I have created trigger as;
use sms;
CREATE TRIGGER push_message_trigger AFTER INSERT ON sms_out
FOR EACH ROW
CALL push_message(NEW.sender, NEW.receiver, NEW.msg);
and I have created procedure as;
use sms;
DELIMITER $$
CREATE PROCEDURE push_message
(p1 TEXT,
p2 DOUBLE,
p3 TEXT)
BEGIN
DECLARE cmd CHAR(255);
DECLARE result CHAR(255);
SET cmd = CONCAT('curl "http://www.sms.co.tz/api.php?do=sms&username=Myusername&password=MyPassword&senderid=MyName&dest=25571500000&msg=test"');
SET result = sys_eval(cmd);
END$$;
The above does not work but if I replace
SET cmd = CONCAT('curl "http://www.sms.co.tz/api.php?do=sms&username=Myusername&password=MyPassword&senderid=MyName&dest=25571500000&msg=test"');
With
SET cmd = CONCAT('touch /var/lib/mysql/Advo');
It works!!
Whats wrong with curl??
I guess the problem it's not the curl literal is how are you using mysql CONCAT funcion.
To concat strings you should do something like (if you don't use commas you aren't concatening strings):
CONCAT(str1, str2, ....);
Seems that the problem are the quotes, try to escape the double quotes like this \"
* Show the error if you want people to know what's really happening
I have successfully created an insert before trigger on a table using the innodb engine which "throws" an error by performing an insert on a non-existent table. The problem is that as I try to run the database create script on the production server it fails because the insert table does not exist. However, the same script runs fine on my workstation which makes me think that there is a MySQL config setting which is causing the create script to fail.
The question my issue brings up is whether the production server is compiling the trigger and my workstation is not (or compiling at runtime). On a production environment I would prefer to have the SQL compiled when created.
My method for simulating raising an error in a trigger is to DECLARE an integer variable and store a string in it. If you have SQL_MODE = STRICT_ALL_TABLES, this raises an error. Otherwise it raises a warning.
use test;
drop table if exists foo;
create table foo (id serial primary key, bar varchar(10));
drop trigger if exists RaiseError;
delimiter //
create trigger RaiseError before insert on foo
for each row
begin
declare bar int;
if new.bar = 'boom' then
set bar = 'You cannot store that value!';
end if;
end //
delimiter ;
set sql_mode = strict_all_tables;
insert into foo (bar) values ('boom');
Notice I named my local variable the same as the column bar that I want to test. That way the name of the variable appears in the error message, it's the same as the column:
ERROR 1366 (HY000): Incorrect integer value: 'You cannot store that value!' for column 'bar' at row 1
It turns out the length of the table name was causing the problem. The two server versions were from different releases with the server being a previous release (5.0 vs 5.1).
As for raising errors in triggers I have taken a different approach, however one that may be flawed depending on how MySQL handles the create trigger statement. If the trigger statements are verified on creation then this will fail.
Once an error is encountered (expected error) I set a session variable (variable name prefixed by an #) with the error message to display. Once the error message is set I do an insert into the non-existing table Die to raise an error in MySQL.
The application then catches the database error and performs a query on the error session variable. Based on the result I either throw an exception with the error message, the database error message or have the query quietly fail leaving the calling code to handle the failed query.
MySQL Trigger:
CREATE TRIGGER Error_Trigger
BEFORE INSERT ON Fubar
FOR EACH ROW
BEGIN
if DataIsBad then
set #Err = 'The data is fubared.';
insert into Die values (1);
end if;
END$$
Application side Code:
public function getDatabaseErrorMessage($AdminMessage = false){
if ($this->db->_error_number() != 0){
$AdminError = $this->db->_error_message();
$Query = $this->db->query("select #Err");
if ($Query){
$Error = $Query->row_array();
}
if (isset($Error["#Err"]) && $Error["#Err"] != ""){
$Error = $Error["#Err"];
$this->db->query("set #Err = ''");
} else {
if ($AdminMessage){
$Error = $AdminError;
} else {
return false;
}
}
throw new Exception($Error);
}
}