Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 27/08/20 in all areas

  1. After a worrying discussion on Discord last night regarding password storage and remember me functionality I've decided to write a tutorial on how it should be done. This guide assumes you are not using MTA's built in account system, but a custom one. Any code shown in this tutorial is purely for illustrative purposes, and is not finished code, you should use it as a guideline, not a solution. The following topics will be discussed in this tutorial: How to hash and salt passwords (register) How to validate a hashed password (login) How to add "remember-me" functionality How to offer password recovery How to migrate from an older hashing algorithm, to a newer one Using a password policy (Extra) How to handle database leaks (Extra) What even is hashing and salting? For the purpose of this tutorial we expect a database structure which is somewhat similar to this: How to hash and salt passwords When you have a user register on your service, that user expects of you to keep their password safe. Whilst it is generally bad practice to use the same password for multiple services there are many users that still do so. Because of this it's crucial that you save the user's passwords in a way that an attacker will be unable to find out the original password the user typed. This includes if they have full access to your database. In order to do this we do what is called "Password hashing" When a user registers, your server receives the user's intended username, (email) and password. Before you save that password to the database you have to hash and salt this, luckily MTA has a function that takes care of this. If you wish to know more about what exactly it does, there's more information at the end of this tutorial. In order to hash this password you use the passwordHash function. This function is relatively slow (by design), so it is highly recommended you pass a callback to this function, so your entire script doesn't wait for it to complete. https://wiki.multitheftauto.com/wiki/PasswordHash local mysqlHandle -- we're assuming this value is set somewhere else in code function register(username, email, password) local player = client passwordHash(password, "bcrypt", {}, function(hashedPassword) -- callback function for hashing the password local handle = dbExec(function(handle) -- callback function for storing the user in the database if (handle) then triggerClientEvent(player, "registrationSuccess") -- inform the user that registration was successful else triggerClientEvent(player, "registrationFailed") end end,mysqlHandle, "INSERT INTO users (email, username, password) VALUES (?, ?, ?)", email, username, hashedPassword) end) end addEvent("passwordTutorial:register", true) addEventHandler("passwordTutorial:register", getRootElement(), register) How to validate a hashed password Once you've saved the hashed pasword to your database you need to do a little bit of additional work when authenticating the user. Luckily MTA offers a passwordVerify() function, which is the counterpart of the previously discussed passwordHash(). What this function does it basically hashes the password in the same way, resulting in the same output hash. https://wiki.multitheftauto.com/wiki/passwordVerify In order to get the account the user is trying to log in to you have to do a query for an account which has the user submitted username, and of which the password matches through passwordVerify. PasswordVerify is also a relatively slow function, thus you should use a callback. function login(username, password) local player = client dbQuery(function (handle) -- callback for the query selecting the user by username local results = dbPoll(handle, -1) if (#results == 0) then triggerClientEvent(player, "loginFailed") return end passwordVerify(password, results[1].password, {}, function(matches) -- callback function for the password verify if (matches) then -- Do anything you wish with the database result to log the player in with the rest of your scripts triggerClientEvent(player, "loginSuccess") else triggerClientEvent(player, "loginFailed") end end) end, mysqlHandle, "SELECT * FROM users WHERE username = ?", username) end addEvent("passwordTutorial:login", true) addEventHandler("passwordTutorial:login", getRootElement(), login) How to add "remember me" functionality When users on your server log in, they often do not want to have to enter their username and password every time they want to log in. In order to satisfy this need you can implement a "remember me" function. What I've seen happen in the past, is people would store the user's password (encrypted) on the client. This is NOT safe, and should never be done! In order to properly use remember me functionality what you would do is upon login in, generate a random string. The longer the better. This random string is what we call an access token. You would then allow the user to log in with such an access token, preferably only once generating a new access token each time one is used. To implement this you would generate that token every time the user logs in, whilst they have "remember me" enabled. You will have to save this token in your database alongside your user. For extra security you could also store the user's serial alongside the access token, you can then validate that the access token is being used from the same device. https://wiki.multitheftauto.com/wiki/Filepath function login(username, password) -- This code should be put in the callback to the dbQuery function, but to keep the example clean that's not shown here if (rememberMe) then local token = generateRandomToken() dbExec(function() triggerClientEvent(player, "loginSuccess", token) end,mysqlHandle, "INSERT INTO access_tokens (user_id, token) VALUES (?, ?)", results[1].id, token) end end function rememberMeLogin(username, accessToken) -- this function handles a user's login attempt dbQuery(function(handle) local result = dbPoll(handle, -1) if (#result == 0) then triggerClientEvent(player, "loginFailed") else -- Do anything you wish with the database result to log the player in with the rest of your scripts triggerClientEvent(player, "loginSuccess") end end,mysqlHandle, "SELECT users.* FROM access_tokens JOIN users ON users.id = access_tokens.user_id WHERE users.username = ?", username) end addEvent("passwordTutorial:loginRememberMe", true) addEventHandler("passwordTutorial:loginRememberMe", getRootElement(), login) How to offer password recovery Offering password recovery requires a little bit more than just your MTA server. Generally password recovery is done with emails. So you would need access to an email server / service which you can use to send an email from an HTTP request. (Like you can do with fetchRemote()). When a user requests a password reset, have them enter the email you registered with. You then fetch a user from the database with this email address. You would then store a password recovery token for this user. This token, just like the remember me token, is a random string. Ideally, you would send the user a link with a password reset form that goes to a webpage where the user can reset their password. You could do this with an external service, like a webserver. Or you could use MTA's Resource web access for it, but if you do make sure you handle permissions properly for anything else that uses this. However another option would be to have the user copy paste the generated token from the email into you server's login window. Which of the two solutions you pick is up to you, my personal preference goes to the one with the link in the email. But in either case the server side logic is the same. When the user attempts to perform password recovery, verify that the token they give you belongs to a user, and then change the password to the newly requested password. Make sure you hash this password the same way you do in your login. function requestPasswordRecovery(email) dbQuery(function (handle)) local result = dbPoll(handle, -1) if (#result == 0) then triggerClientEvent(player, "passwordTutorial:passwordRecoveryRequestFailed") else local token = generateRandomToken() dbExec(mysqlHandle, "UPDATE user_data SET recovery_token = ?", token) -- mail the token to the user, mail implementation depends on the mail server/service you use triggerClientEvent(player, "passwordTutorial:passwordRecoveryRequestSuccess") end end, mysqlHandle, "SELECT * FROM users WHERE email = ?", email) end function recoverPassword(recoveryToken, password) dbQuery(function (handle) local result = dbPoll(handle, -1) if (#result == 0) then -- this is only valid if you have the user request password recovery from ingame triggerClientEvent(player, "passwordTutorial:passwordRecoveryFailed") else passwordHash(password, "bcrypt", {}, function(hashedPassword) -- callback function for hashing the password local handle = dbExec(function(handle) -- callback function for storing the new password in the database if (handle) then -- this is only valid if you have the user request password recovery from ingame triggerClientEvent(player, "passwordTutorial:passwordRecoverySuccess") -- inform the user that registration was successful else -- this is only valid if you have the user request password recovery from ingame triggerClientEvent(player, "passwordTutorial:passwordRecoveryFailed") end end,mysqlHandle, "UPDATE user_data SET password = ? WHERE recovery_token = ?", username, recoveryToken) end) end end, "SELECT * FROM users WHERE recovery_token = ?", recoveryToken) end Besides changing the password, it's important you also delete any access tokens that user might have if you're using remember me functionality. It is also good practice to make recovery tokens expiry after a certain amount of times, and not allow a recovery token to be created whilst one is already in prgoress. This prevents a user from sending a large number of emails from your service. How to migrate from an older hashing algorithm, to a newer one Maybe after reading this topic you realise that your password security is not what it should be. So you want to change your old password hashing / validation logic to the ones explained in this topic. And due to the nature that hashes can not be "unhashed", you can't simply migrate your passwords over. So in order to migrate the passwords what you have to do is when a user logs in, first validate their password with the old hashing algorithm. If this matches, then hash (and salt) it with your new hashing algorithm and save it in your database. Make sure to delete the old password otherwise your password security is not any better than before. Using a password policy Passwords policies are important to prevent your users from picking a password that is too easily cracked / brute forced. Many password policies come in the form of "Must have at least one capital letter, one digit and one number". But that discards that fact that the best way to make your password more difficult to crack, is making your password longer. So in the code snippet below is a function that measures the 'search space' of a password. The search space of a password is the amount of possible passwords there are with a certain combination of characters. In order to use this, you would have to set a minimum password search space when a user registers for an account. This minimum is up for you to set, but be reasonable, you shouldn't expect a user's password to be impossible to remember / create. I recomend playing with the function a bit to see what values you get out of it, and pick something you believe is sensible. function getPasswordSearchSpace(password) local lowerCase = password:find("%l") and 26 or 0 local upperCase = password:find("%u") and 26 or 0 local digits = password:find("%d") and 10 or 0 local symbols = password:find("%W") and 32 or 0 local length = password:len() return (lowerCase + upperCase + digits + symbols) ^ length end -- The below function calls are to indicate the difference in search space for a set of passwords print(getPasswordSearchSpace("a")) print(getPasswordSearchSpace("abc")) print(getPasswordSearchSpace("Abc")) print(getPasswordSearchSpace("Ab!")) print(getPasswordSearchSpace("Ab!0")) print(getPasswordSearchSpace("Mu#9A0h.")) print(getPasswordSearchSpace("This is a demonstration of how easy an incredibly strong password is to remember")) How to handle database leaks If you have reason to believe that your database has been leaked or otherwise compromised, it is important that your first course of action is removing any access tokens stored in your database. Once you have done that you have to inform your users. Whilst when properly hashed and salted it's extremely difficult / time consuming to find out a user's password it is still a possibilty. So you should inform your users of the breach, tell them that their passwords were properly hashed, and they do not need to fear for their passwords immediately. However you should suggest to your users that they change their password either way, just in case. What even is hashing and salting? Hashing has been brought up several times in this tutorial, whilst you do not need to know what it is / does, you might be interested in knowing regardless. I won't be going too far in depth as I simply do not have the knowledge, but the basic idea of hashing is this: When you hash anything, you turn it into a string of characters (or other value) that has no relation to the original input, other than when you hash the original input again, it will always generate the same hash. For example, when you hash the stirng 'banana' using the sha512 hashing algorithm, it will always yield the output: "F8E3183D38E6C51889582CB260AB825252F395B4AC8FB0E6B13E9A71F7C10A80D5301E4A949F2783CB0C20205F1D850F87045F4420AD2271C8FD5F0CD8944BE3" Now hashing can not be reverted, you can not "unhash" a hash, so in order to verify someone's password you hash it again, and see if the two hashes are the exact same. Now this is great, passwords are safely stored. However there is still more to do, salting. Salting is adding some random data to your password prior to hashing it. This prevents when two users (on the same service, or on others) have the same password, that their hashes are also the same. Meaning if one password is compromised, the other password is not. It is important that a salt is random for every user in your application, not one salt for your entire application. Now you might think we didn't do any salting in the code / tutorial above. This is not true, we just didn't do it ourselves. MTA's passwordHash function actually hashes the passwords and salts it, this salt is then stored in the output hash it self, just before the actual password hash. In the case of bcrypt it actually stores a little bit more info in the resulting hash, but you need not worry about that.
    1 point
  2. OK so after many requests from people asking me to install discord bots to their servers I have decided to make the simplest tutorial on setting up a bot for your servers. [NOTE]: THIS IS A VPS TUTORIAL. IF YOUR SERVER ISN'T RUNNING ON A VPS THIS WILL NOT WORK FOR YOU UNLESS YOU UNDERSTAND HOW NODE.JS WORKS. Part 1: Bot creation Part 2: Files Configuration Part 3: SSH commands That should be all now go have fun annoying players in your server. Some feedback would be appreciated Good luck
    1 point
  3. GetAttachedElements doesn't work with the bone_attach resource since the attached objects aren't attached with attachElements
    1 point
  4. Start sistemi ve özellikleri: Login Kısmı: İlk animasyonda ekran 360 derece dönüyor ve düzeliyor diğer animasyonlarda öyle birşey olmuyor. Resim: Birlik seçme kısmı: Fotoğraftaki birliğin önemli misyonları kısmını birlik lideri admin-system scriptinden ayarlıyor. Birlik lideri şuanda olmadığından lider kısmı boş. Fotoğraf: Eğitim Kısmı: Tamamen yapay zekaya bağlı. Oyuncu kendi kendine oyuna giriyor, fiziksel eğitimi tamamladıktan sonra yazılı eğitime geçiyor eğer onda 50 puan üstü alırsa başarılı oluyor ve birliğine giriyor. Fotoğraflar:
    1 point
  5. It's worth mentioning you can carjack a dead ped, if you are looking to make a workaround. However it's almost impossible to create a workaround that looks good and works well. I've considered a lot of approaches for a workaround, but it's ridiculous for such a basic mechanic that should just work. Better to focus our efforts on fixing it in MTA.
    1 point
  6. So I've been working on this little thing for a while now. I wanted to write my own MTA script editor - this started out as an experiment to see if I could get a decent autocomplete system up and running. As it turns out, I could. I've also managed to implement a rather neat guide for the MTA functions - the idea is that you won't have to alt-tab to the wiki just to check function arguments all the time. Instead, you can just start typing, and the program happily steps in to offer you a helping hand. Current features (click for screenshots) Tabbed editor with Lua and XML syntax highlighting - MTA functions are highlighted depending on "domain" (client/server/both) Autocompleted MTA functions Function parameter reminders One-key wiki lookup And of course, the "obvious" stuff for a text editor. These are just a few of the features I've planned, there's more on the way. Want to help? If you know C# (preferably with a bit of experience with WPF) and would like to help, that'd be great. I might also need a few testers - the project is currently considered 'pre-alpha', but I plan to have closed alpha tests and a public beta. If you're interested, PM me or post here, but be aware that we're "not quite there yet". I also don't have entirely reliable data on the MTA functions - before starting on the editor proper, I wrote a small-ish program to get function data off the wiki. Unfortunately, the wiki is not too consistently formatted, and this makes automatic scraping a bit difficult. If you want to help fill in missing data, I'd really appreciate it. Edit: function data has been graciously provided by Cadu12, thanks! Questions, ideas, suggestions Post away!
    1 point
  7. É vrdd, desculpa, eu n prestei atenção nessa parte quando fui colocar o script aqui, eu tinha colocado o limite de 59 min mas esqueci que as horas só vao ate 23 e n 24, foi um vacilo msm, coisa de principiante nos proximos eu vo me esforçar mais pra n deixar passar esses erros bobos ?
    1 point
  8. 1 point
  9. Ah, isso sim, entendi, porem, se o jogador vier a executar a hora 24 e o minuto 60, será verificado e passado para 0
    1 point
  10. 1. Mosaic Download: https://community.multitheftauto.com/index.php?p=resources&s=details&id=18254 Video: 2. Speed Box Download: https://community.multitheftauto.com/index.php?p=resources&s=details&id=16184 Video: 3. Up Up Up Download: https://community.multitheftauto.com/index.php?p=resources&s=details&id=16176 Video:
    1 point
  11. ATTENTION! First thing you must do before starting to script for MTA is to learn Lua. If you don't learn the basics of Lua language, it will be hard for you to script anything. I've compiled this list of tutorials and manuals, which should be useful for scripting beginners. http://www.lua.org/manual/5.1/ ( recommended ) http://www.lua.org/pil/index.html ( recommended ) http://lua-users.org/wiki/TutorialDirectory ( recommended ) http://lua-users.org/wiki/LuaFaq http://nixstaller.sourceforge.net/manua ... ler_9.html http://en.wikipedia.org/wiki/Lua_(programming_language) ( recommended ) http://lua.gts-stolberg.de/en/index.php http://www.luxinia.de/index.php/Tutorials/Lua http://forum.toribash.com/showthread.php?t=74001 http://lua-av.mat.ucsb.edu/blog/?p=39 ( recommended ) http://www.ozone3d.net/tutorials/lua_coding.php http://luatut.com/ ( recommended ) http://nixstaller.sourceforge.net/manua ... ler_9.html ( recommended ) http://wiki.roblox.com/index.php/Beginn ... Coroutines ( recommended ) Lua demo: http://www.lua.org/demo.html codepad.org: http://codepad.org/ ideone.com: http://ideone.com/ MTA scripting IRC channel: #mta.scripting List will be updated. If you have any other useful tutorial/manual links — post it.
    1 point
×
×
  • Create New...