Firebase RealTime Database Security Rules for personal app - flutter

I have created an application in Flutter and I will be the only one to use it since it makes my work easier. It uses Firebase Realtime Database to synchronize data between my devices. When I read the Firebase documentation, I realized I needed to protect my database to prevent access from strangers, so I looked for a way to import some kind of password to pass as a payload when requesting and writing data. But there doesn't seem to be anything like that, I would have to implement Firebase Auth to do that as well. So I opted to create my own dataset with a very particular name, and set the read and write rules only to that particular path. My rules look like this:
{
"rules": {
"dataset-verylong32charstringwithalphanumericvalue":{
".read": "true",
".write": "true",
}
}
}
So in theory any other access attempts should be blocked. Since this is a bit of an odd method and not described in the documentation. Can I consider this method safe?
Obviously I know that if some malicious person gets wind of my string they will have full access to my data, but since the chances are low of that happening, I just needed superficial protection against abuse of the service
I have tried making REST requests and all attempts seem to be blocked.
So I expect it to be secure. However, I fear there may be a method to map all the paths in my database and then easily derive my string

What you're using is known as a shared secret. If it meets your needs then that's a valid way of securing access to the data. There is no way through the client-side SDKs and API to read the root of the database, and thus to learn your secret path that way.
For example, download URLs generated by Firebase for Cloud Storage depend on a shared secret to make files publicly readable by everyone who has that secret (it's the token parameter in the URL).
I also used this approach myself when dealing with the data for an events web site. The site was statically regenerated when the data in the database changed, so the shared secret never ended up in the published site.
The problem you need to figure out is how you're going to get the shared secret to the consumers of the data. In the above examples we expect either everyone to at possibly get the secret, but then not do any hard (since download URLs are read-only); or we expect only trusted services to know the secret and it never to reach anyone else. If your use-case is different than these, finding a way to share the secret out of band may become your next problem to solve.
A simple alternative is to implement anonymous authentication, which allows the app to sign in without requiring any credentials from the user and with a single line of code. With that you can then restrict access to the data to just the UID(s) that you know in your database's security rules. I usually hard-code the UID in the rules, until I get tired of adding/updating them, at which point I switch over to storing an allow-list of them in the database itself.

This is not a safe or efficient method.
If you are the only one who will use this app and can create user accounts, then you could just check if the user is authenticated or not, e.g.
service cloud.firestore {
match /databases/{database}/documents {
allow read, write, update, delete: if request.auth != null;
}
}
If you need to add another layer of security, then you can add custom user claims to the authentication token: https://firebase.google.com/docs/auth/admin/custom-claims
You can then securely access those extra claim fields in the rules (e.g. "request.auth.customField"), and compare them to some other data in your database.
Adding the claims is typically done on a secure backend to keep the Firebase admin details private - but if you are the only user on the frontend app(s), it shouldn't be a security concern to do it on the front end too.

Related

Flutter App: Firebase Credentials viewable in Source Code (apk / web) = unsecure database? [duplicate]

The Firebase Web-App guide states I should put the given apiKey in my Html to initialize Firebase:
// TODO: Replace with your project's customized code snippet
<script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
</script>
By doing so, the apiKey is exposed to every visitor.
What is the purpose of that key and is it really meant to be public?
The apiKey in this configuration snippet just identifies your Firebase project on the Google servers. It is not a security risk for someone to know it. In fact, it is necessary for them to know it, in order for them to interact with your Firebase project. This same configuration data is also included in every iOS and Android app that uses Firebase as its backend.
In that sense it is very similar to the database URL that identifies the back-end database associated with your project in the same snippet: https://<app-id>.firebaseio.com. See this question on why this is not a security risk: How to restrict Firebase data modification?, including the use of Firebase's server side security rules to ensure only authorized users can access the backend services.
If you want to learn how to secure all data access to your Firebase backend services is authorized, read up on the documentation on Firebase security rules. These rules control access to file storage and database access, and are enforced on the Firebase servers. So no matter if it's your code, or somebody else's code that uses you configuration data, it can only do what the security rules allow it to do.
For another explanation of what Firebase uses these values for, and for which of them you can set quotas, see the Firebase documentation on using and managing API keys.
If you'd like to reduce the risk of committing this configuration data to version control, consider using the SDK auto-configuration of Firebase Hosting. While the keys will still end up in the browser in the same format, they won't be hard-coded into your code anymore with that.
Update (May 2021): Thanks to the new feature called Firebase App Check, it is now actually possible to limit access to the backend services in your Firebase project to only those coming from iOS, Android and Web apps that are registered in that specific project.
You'll typically want to combine this with the user authentication based security described above, so that you have another shield against abusive users that do use your app.
By combining App Check with security rules you have both broad protection against abuse, and fine gained control over what data each user can access, while still allowing direct access to the database from your client-side application code.
Building on the answers of prufrofro and Frank van Puffelen here, I put together this setup that doesn't prevent scraping, but can make it slightly harder to use your API key.
Warning: To get your data, even with this method, one can for example simply open the JS console in Chrome and type:
firebase.database().ref("/get/all/the/data").once("value", function (data) {
console.log(data.val());
});
Only the database security rules can protect your data.
Nevertheless, I restricted my production API key use to my domain name like this:
https://console.developers.google.com/apis
Select your Firebase project
Credentials
Under API keys, pick your Browser key. It should look like this: "Browser key (auto created by Google Service)"
In "Accept requests from these
HTTP referrers (web sites)", add the URL of your app (exemple: projectname.firebaseapp.com/* )
Now the app will only work on this specific domain name. So I created another API Key that will be private for localhost developement.
Click Create credentials > API Key
By default, as mentioned by Emmanuel Campos, Firebase only whitelists localhost and your Firebase hosting domain.
In order to make sure I don't publish the wrong API key by mistake, I use one of the following methods to automatically use the more restricted one in production.
Setup for Create-React-App
In /env.development:
REACT_APP_API_KEY=###dev-key###
In /env.production:
REACT_APP_API_KEY=###public-key###
In /src/index.js
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
// ...
};
I am not convinced to expose security/config keys to client. I would not call it secure, not because some one can steal all private information from first day, because someone can make excessive request, and drain your quota and make you owe to Google a lot of money.
You need to think about many concepts from restricting people not to access where they are not supposed to be, DOS attacks etc.
I would more prefer the client first will hit to your web server, there you put what ever first hand firewall, captcha , cloudflare, custom security in between the client and server, or between server and firebase and you are good to go. At least you can first stop suspect activity before it reaches to firebase. You will have much more flexibility.
I only see one good usage scenario for using client based config for internal usages. For example, you have internal domain, and you are pretty sure outsiders cannot access there, so you can setup environment like browser -> firebase type.
The API key exposure creates a vulnerability when user/password sign up is enabled. There is an open API endpoint that takes the API key and allows anyone to create a new user account. They then can use this new account to log in to your Firebase Auth protected app or use the SDK to auth with user/pass and run queries.
I've reported this to Google but they say it's working as intended.
If you can't disable user/password accounts you should do the following:
Create a cloud function to auto disable new users onCreate and create a new DB entry to manage their access.
Ex: MyUsers/{userId}/Access: 0
exports.addUser = functions.auth.user().onCreate(onAddUser);
exports.deleteUser = functions.auth.user().onDelete(onDeleteUser);
Update your rules to only allow reads for users with access > 1.
On the off chance the listener function doesn't disable the account fast enough then the read rules will prevent them from reading any data.
I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
}
}
}
No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains.
One can read more about it on
Firebase Security rules
While the original question was answered (that the api key can be exposed - the protection of the data must be set from the DB rulles), I was also looking for a solution to restrict the access to specific parts of the DB.
So after reading this and some personal research about the possibilities, I came up with a slightly different approach to restrict data usage for unauthorised users:
I save my users in my DB too, under the same uid (and save the profile data in there). So i just set the db rules like this:
".read": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()",
".write": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()"
This way only a previous saved user can add new users in the DB so there is no way anyone without an account can do operations on DB.
Also adding new users is posible only if the user has a special role and edit only by admin or by that user itself (something like this):
"userdata": {
"$userId": {
".write": "$userId === auth.uid || root.child('/userdata/'+auth.uid+'/userRole').val() === 'superadmin'",
...
EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.
Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.
You can always restrict you firebase project keys to domains / IP's.
https://console.cloud.google.com/apis/credentials/key
select your project Id and key and restrict it to Your Android/iOs/web App.
It is oky to include them, and special care is required only for Firebase ML or when using Firebase Authentication
API keys for Firebase are different from typical API keys:
Unlike how API keys are typically used, API keys for Firebase services are not used to control access to backend resources; that can only be done with Firebase Security Rules. Usually, you need to fastidiously guard API keys (for example, by using a vault service or setting the keys as environment variables); however, API keys for Firebase services are ok to include in code or checked-in config files.
Although API keys for Firebase services are safe to include in code, there are a few specific cases when you should enforce limits for your API key; for example, if you're using Firebase ML or using Firebase Authentication with the email/password sign-in method. Learn more about these cases later on this page.
For more informations, check the offical docs
I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.
I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable.
Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase.
Go to https://console.developers.google.com/apis
and perfrom a security steup.
You should not expose this info. in public, specially api keys.
It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
Complex coding/hiding
Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere

Firebase/Firestore - database has insecure rules?

I have a SwiftUI application, which uses Firebase as a back end, and my rules are something like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// This rule allows anyone on the internet to view, edit, and delete
// all data in your Firestore database. It is useful for getting
// started, but it is configured to expire after 30 days because it
// leaves your app open to attackers. At that time, all client
// requests to your Firestore database will be denied.
//
// Make sure to write security rules for your app before that time, or else
// your app will lose access to your Firestore database
match /{document=**} {
allow read, write: if request.time < timestamp.date(2020, 10, 28);
}
}
}
I understand that these rules allow anyone to read and write to the database. However, as long as they are only using the API provided to the them in the application, how is this insecure? For instance, I could understand the danger, if, say, someone took the xcode project from my laptop and created a button that deleted all users in the database. But, no one will have access to this code.
I do want users to be able to read and write to/from the database, so I was just wondering if these rules are insecure, and, if so why? Like what is an example of how a hacker with malicious intent could exploit these rules to gain unauthorized access to user information and/or somehow modify the database in a way that the API provided in my application does not allow?
Thank you.
as long as they are only using the API provided to the them in the application
This is precisely the problem.
Your app contains all the configuration needed to connect to the database (and other resources in your Firebase project). A malicious user can take this configuration data, and call the API themselves - thus bypassing any of your client-side logic.
While you can configure Firebase App Check to help only allow access to the database is coming from your code, that is no guarantee and somebody else's might still use their code with your configuration data.
That's why it's crucial that you also encode your business logic in your security rules. Say that your application code only allows the user to delete their own account from the database, you'll then also want to encode that logic in your security rules so that they're enforced on the server. This is a variation of what the Firebase documentation on securing your database describes as content-owner only access.

Security of Firestore Database - SwiftUI

I have a very simple Firestore database for a game I creating. I have a User collection which has documents, each of which specifies a user's username, their email, and their high score.
I would like everyone to be able to read the high score and username's of everyone in the database, since I have a list that lists every user's high score and username.
However, I would only like individuals to be able to write the database (i.e. submit their own high score), if they are logged in.
Thus, I have the following security rules:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
match /Users/{document=**} {
allow read: if true;
}
}
}
My question is, is this secure? I guess this means that technically a user with malicious intent could read the emails of every user. Is there a way to prevent this by somehow specify that only everyone should be able to read the highscore and username properties of each User document?
Also, this set up does prevent malicious users from writing to the database, correct (edit here: I guess this doesn't - I'm looking into this now by reading the docs here https://firebase.google.com/docs/firestore/security/rules-structure)
I'm not new to Firebase but I am new to it's security rules, since I haven't pushed an application to production before and would like to make sure I don't leave anything vulnerable, so any feedback/guidance here is appreciated.
As I explained on your previous question, anyone can take the configuration data from your app, and call the Firebase APIs with that data.
is this secure?
Only you can determine whether your rules are correct for your use-case.
These rules allow anyone to read all documents in the /Users collection. In addition they allow any authenticated user to read and write all documents. If that is the use-case you want to support, the these are the correct rules for you.
So if you've enabled the anonymous authentication provider in Firebase Authentication, anyone can take you configuration data, write a minimal web page and call firebase.auth().signInAnonymously() and then read all user data with firebase.firestore().collection("Users").get().
Securing your database is going to be hard to learn in this question and answer style. I instead recommend you:
Read the Firebase guide on security rules.
Doug's video introduction to security rules.
Watch the series Getting to know Cloud Firestore, and pay special attention to the episode on security rules.
The video Unit testing security rules with the Firebase Emulator Suite and its follow up Intermediate topics in Firebase Security Rules.
The pro-series episode How to build a secure app in Firebase.
The article Patterns for security with Firebase: combine rules with Cloud Functions for more flexibility

Resource-Server for IdentityServer 4

My task is to implement a resource server(RS) for IdentityServer4(IS4). The RS should fetch data from a database and send the necessary information as a json object back to the caller (client). This is needed because we have to return complex objects.
I already setup IS4 succesfully and its already running in Docker for testing purpose. I also setup the needed database.
My understanding of the flow would be, the user requests data from the RS sending the access-token, the RS then validates the token, checking if the caller is allowed to access the api using the IS4, if everything is okay the RS returns the data to the caller.
My problem is, as I'm new to this subject, how would I implement a RS? Do I create an API which is added as a scope to the user? Or is there a RS already implemented in IS4?
So yes you'll need to write your own API to serve your own resources, IdentityServer will only manage your identities for you (as well as handling external logins if that's what you need). I'd recommend going to the IdentityServer docs and working through the quick starts in order as shown below:
This will give you a good start but you'll then need to go away and research APIs more generally, there's a tonne of good info online about building (RESTful) APIs. You may find it useful to sign up to something like PluralSight and work through a couple of their courses, they're often very good.
One other thing to bear in mind is that IdentityServer is for identity, in other words Authentication and not specifically for Authorisation so you may need to add something for this. You can of course use a users identity for authorisation purposes but in most cases you'll probably need to augment the info you store about their identity to authorise them for access. See this link for more info around this topic.

Node - request authentication using secret

Lets assume i have REST api with products and i want it to be accessible only for specified users.
The list of users is known for me and i'm looking for some way to give them safe access to my API.
I don't want to create authentication with username and password, generate token and this stuff.
What i can imagine is that i'm giving each of my users some secret string
and they use it in every request.
And what i need is some example/tutorial/name of this kind of solution,
i'm sure there are some standards for that but i don't know it.
I know it's kind of nooby question - sorry for that, i'm just asking ;).
Thanks in advance!!
You are looking for a simple shared-secret authentication. A simple solution in this case is just to check for the secret as a param (or it could be in the request header). For example, the client can call:
https://example.com/valuable-stuff?secret=2Hard2Gue$$
You implement this in your web request handler as:
SECRET = '2Hard2Gue$$'
function showValuableStuff() {
if (params['secret'] != SECRET)
return NotFounderError;
// now retrieve and output the resource
}
Some practical considerations are:
Use a secure connection for this to prevent the secret being leaked (ie a secure HTTPS exposure).
Be careful where you store the source code if you're hard-coding it. A fancier solution is use an environment variable which is set on the server, so you keep this out of the source code. Or at least to encrypt the part of the source that contains the secret.
While this is fine for simple solutions, it violates the basic security principle of accountability because you are sharing the secret with multiple people. You might want to consider allocating each individual their own random string, in which case, you may as well use HTTP Basic Authentication as it's well supported by Apache and other web servers, and still quite a lightweight approach.