How can someone inject code on my server without my server credentials?
Using SSH stolen keys, FTP anonymous connection, or server-executed files (ie: PHP files that write in server's FS)
How can I know from where this code was injected?
See logs (bash/FTP/your server code logging system if there is one). You can seek for when it was written (using file's modification date or comparing backups), and check your server's access logs to find out what IP and how they injected code. Also, since servers are now bound to database, maybe it was a two-step injection: inject code in DB, and let another call (CRON or HTTP visit) write the DB content to a file.
How to prevent future injections?
Renew the server's credentials (including DB) and don't write any file from your executed code. Also, don't call any shell-execution function from your server code (ie: a PHP calling exec
may write stuff to files). Favor community work (ie: open-source solutions) rather than custom stuff: they often are more secure.