Firebase Security Open Access - firebase

My android wallpaper app is connected to Firebase Cloud Firestore. It doesn't have any user authentication because I want the user to be able to use it without fuss. To do this, it must be in open access, meaning, the user is allowed to read and write. This is dangerous as he can also edit and modify the data if he knows the project id. The project id is visible in the url of the app so this is not really a good choice. Closed access is also not an option for obvious reasons.
Is there anything I can do to protect my data without need of a user authentication? I would love to see the code needed for the Cloud Firestore and Storage to protect the data. I want the user to read only and I, as the owner, should be the only one who could write. Please refer to the images attached. Thanks a lot for taking time to answer my questions.
My data structure in Firebase Cloud Firestore:

Securing your data with Security Rules
Firebase Cloud Firestore, Firebase Realtime Database and Firebase Cloud Storage are secured by their own Security Rules. They provide access control and data validation in a simple yet expressive format and allow you to control access to documents and collections in your database.
To build user-based and role-based access systems that keep your users' data safe, you need to use Firebase Authentication with Cloud Firestore Security Rules.
Your specific use case
I assume that you store your data in Firebase Cloud Firestore and the wallpapers in Firebase Cloud Storage. The user then gets a document with a link to download a wallpaper and maybe also can upload their own wallpapers to the database.
The dangers of an open database
As you mentioned allowing all reads and writes to your database in a production app is very dangerous. Obviously, anyone with your database reference will be able to read or write data to your database. Unauthorized users could destroy your backend and there are also possibilities that costs could increase exponentially. Therefore this is not recommended. There always should be some mechanisms preventing these scenarios.
Recommendation: Using anonymous authentication first and connect later with existing Identity Providers
I recommend that you use Firebase Authentication to create and use temporary anonymous accounts to authenticate with Firebase. These temporary anonymous accounts can be used to allow users who haven't yet signed up to your app to work with data protected by security rules while not being in the way of your user experience. If an anonymous user later decides to sign up to your app, you can link their sign-in credentials to the anonymous account so that they can continue to work with their protected data in future sessions.
You could also enable Google-Sign-In, Facebook Login, Twitter, GitHub, Microsoft, Yahoo, etc. to let users authenticate in a very fast and easy way without compromising on a security standpoint if using regular password authentication is not what you want (from a UX standpoint). FirebaseUI makes it really easy to add these to your existing app. Check out the official documentation on this topic.
Implementing Cloud Firestore Security Rules
The official documentation on this is really great on how to get started with Cloud Firestore Security Rules.
However these security rules could work for you:
Allow read access to all users to the root (Not recommended because this can create huge costs in production). Users don't have write (create, update, delete) access. In this case you can edit your data via the Firebase Console. Choose either option 1 or option 2 for your project.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Option 1: Matches any document in the 'root' collection.
match /root/{rumiXYZ} {
allow read: if true;
allow write: if false;
}
// Option 2: Matches any document in the 'root' collection or subcollections.
match /root/{document=**} {
allow read: if true;
allow write: if false;
}
}
}
The {document=**} path in the rules above can be used to match any document in the collection/subcollections or in the entire database. This should however not be necessary for your use case. Continue on to the guide for structuring security rules to learn how to match specific data paths and work with hierarchical data.
Don't forget to secure your Firebase Cloud Storage too!

Related

Firebase storage: check if user is admin

I have a folder in Firebase storage that only the admin service account should be able to write to. (More particularly, that admin service account will only write to the storage from a cloud function).
I'd like to figure out how to create a rule that prevents any other user from writing to the storage bucket. Does anyone know how one can accomplish this goal?
I thought I could create a rule that forbid writing unless the writing agent's uid matched the admin uid, but I haven't been able to find the admin uid yet. I tried logging into my service account like so:
import firebase_admin, os
from firebase_admin import credentials, initialize_app
if not len(firebase_admin._apps):
cert = os.path.join('src', 'secrets', 'service-account.json')
initialize_app(credentials.Certificate(cert), {
'databaseURL': 'https://womp.firebaseio.com/',
'storageBucket': 'womp.appspot.com/',
})
then digging through the firebase_admin._apps[0] object to see if I could dig out a uid for the user, but no dice.
If others know how to create a rule that prevents any but admin users from writing to a storage instance, I'd be grateful for any insights they can offer!
It's not possible to limit access to service account using security rules. Service accounts always bypass security rules.
Once you start working with service accounts, their access is controlled by Google Cloud IAM, which is completely different. You can use IAM to limit which service accounts are allow to access a bucket, and that's going to operate completely independently of whatever security rules you write for end users going through the Firebase SDK.
If you don't want any users to write directly to a bucket, and only allow service account, the security rules for the bucket should simply reject all access.
match /{document=**} {
allow read, write: if false;
}

Secure Firestore database using rules. Check authentication. Is it enough?

I'm new to Firebase and trying to understand database rules. I'm using Firestore.
I have a database that basically needs to be read by all users, and also write. All users can see the documents in the database, and with certain actions they change certain fields. In certain cases they will detele certain old expired documents.
Now, I understand that I cannot leave read and write open to all, since this is not secure. So I am using authentication, I will anonymously authenticate the users, so that only authenticated users have access.
I understand this does the job:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
Now, my question is, is this enough? I'm not a hacker, so I don't exacly know how a hacker would or could hack and detele/change stuff in my database, but does this mean that only changes can be made to the database through using the app? Could someone still hack this if they aren't using the app, and authenticate in some other illegal way.
Thanks so much for the help, I've tried to read to get to the bottom of this, but haven't managed.
Firebase security rules can't limit access to a single app. All of the APIs are all available for public use for anyone who has an internet connection. They are all documented right here: https://firebase.google.com/docs/reference/rest/auth
The purpose of Firebase Authentication is to make sure that individual users have their individual access controlled appropriately. As soon as you let users create accounts using anonymous or email auth, they will have full access to all documents in the database with these rules. So, what you have right now is not really "secure" by most definitions of that word. You will have to decide if this is "secure" enough for your purposes.
You are also likely to get an email from Firebase saying that your rules are insecure. It's not a good idea to use /{document=**} like this, which matches all documents, which might not be what you intend. Minimally, you should call out the individual collections that you want users to access instead of using this global wildcard.
Does this mean that only changes can be made to the database through
using the app?
Anyone that can get your Firebase config elements could write a simple HTML page using the JavaScript SDK and try to interact with your Firestore backend. Note that it is not difficult to get your Firebase config elements, see at the bottom for more details.
This is why it is of upmost importance to implement a set of security rules if you want to protect your data.
Now, it is important to note the following point about Firebase Authentication and “registered“ users:
You should note that anyone can “create a new user in your Firebase project by calling the createUserWithEmailAndPassword() method or by signing in a user for the first time using a federated identity provider, such as Google Sign-In or Facebook Login” (if these identity providers are activated, of course). See the doc.
So, again, with your Firebase config elements, someone can easily build an HTML page that calls the createUserWithEmailAndPassword() method.
This means that if you want to limit the access of your app to some specific users just by using allow read, write: if request.auth.uid != null in your Firestore security rules, it is not sufficient.
One possible approach is to use Custom Claims. You can for example, set a specific claim to all your authorized users (e.g. authorized = true) and adapt your security rules to check the existence of this claim in the user token.
Note: How to find the Firebase config elements of a web app?
It is not really difficult to find the Firebase config object. Just look in all the HTML or JS files composing the app for the apiKey string.

Trying to make app secure with API key, but it isn't being used

I've created a web application that displays data from my cloud firestore. I'm about to release it to the public, but I don't want just anyone to be able to read/write to my database.
I have currently restricted my API key to only allow requests from my website's url, but it doesn't seem to be doing anything. I've even deleted it from the app entirely and it is still able to access the database.
Is there a rule I need to set up in my firestore to make it require an API key? I've googled plenty of things, but all I can find are articles on why it's ok to have your key be available to the public.
It's not possible to restrict access to Firestore based on some plaintext API key or web site domain. If you're publishing an app that provides direct access to Cloud Firestore (or Cloud Storage, or Realtime Database), the only way to secure it is with a combination of Firebase Authentication and security rules. The security rules allow you to express who can read and write which collections and document.
If you aren't using Firebase Authentication, and your default security rules allow universal read/write access, then anyone with an internet connection will be able to read and write every document.
A slight variation on Doug's excellent answer is to allow all users to write to specific documents that pre-exist and that have impossible to guess names. These document names then essentially become your own API keys, that you share (out of band) with the users of your app.
The security rules for this can be as simple as:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow create: if false;
allow update: if exists(resource['__name__']);
allow get: if true;
allow list: if false;
}
}
}
So: anyone can get/update any existing document that they know the name of, but they can't create a document, nor get a list of all documents.
This prevents the need for using Firebase Authentication. On the other hand it means you can't lock down access on a per user basis. Any user that somehow gets access to the document name, can now read/write it at will.

Firebase Cloud Firestore restrict user access (Banking Application)

I am working on a banking app using firebase cloud firestore. I have already set the rules like so:
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
My database is structured like this:
/consumers/{consumer_id}/transactions/{transaction_id}
the {consumer_id} will contain the account balance for that consumer along with other details and the {transaction_id} will contain the details about each transaction.
So if any authenticated user wanted to say, withdraw money they can do so using the android app/Web app. The problem is, can that same user access the database (eg: update their account balance) using their credentials with the REST endpoints without my knowledge? If so how do I prevent them from doing so?
There is no way to limit access to Firestore to just users who are using your app. Anyone who has the configuration data for your Firebase project, can call the APIs in that project. And as soon as you publish your app, you're sharing the configuration data with those users. So you'll have to assume that some malicious user(s) will at some point call APIs on your project without using your app.
For this reason you should enforce all business rules that you have in a trusted environment, such as your development machine, a server you control, Cloud Functions, or... server-side security rules. Since no user can access any of these, even if they run their own code, they'll be forced to adhere to your business rules.
Some examples:
Each transaction document probably contains the UID of the user who is posting that transaction, and of course users should only be able to post transactions with their own UID. You can enforce this in security rules with something like:
match /databases/{database}/documents {
match /consumers/{consumer_id}/transactions/{transaction_id}/ {
allow write: if request.resource.data.posted_by == request.auth.uid;
}
}
So now anyone (no matter if they're using your app or not) can only post transactions if that document contains their own UID. You'll probably want to verify a bit more, such as whether there is even a account document for them, and maybe whether you've verified their account in some way. All of these can typically be done from server-side security rules.
For more on this, see the documentation on accessing other documents in security rules, the pro-series video on building secure apps, and this video on security rules.
Since you keep the balance of each account in their parent document under /consumers/{consumer_id}, you'll need to update that document whenever a transaction is posted under it. While this is possible from within security rules, it's going to be quite involved. It's going to be easier to perform this update of the balance in server-side code.
A good solution for this is to run the code that updates the balance as a Cloud Function that gets triggered whenever a transaction is created (and/or updated if you allow that). Since this code runs in a trusted environment, you can be sure only you can modify it, and thus it can safely update the balance for the new/modified transaction.

How to enable access of firestore data to my nativescript app only?

I am developing android/ios app using Nativesript + angular. I want to display a ListView in my app. For that ListView, I want to use firestore database product by Firebase as Backend data provider.
What I want:
1. I don't want users to login or to be authenticated to use the app.
2. I want the data coming from firebase database can only be used by my app. If some other apps or anonymous utilizes the data, is there any way I can block them?
I have tried putting rules like
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
}
}
}
But it allows everyone to access the data.
Is there any other data provider which gives the same functionality?
Update (May 2021):
Thanks to the new feature called Firebase App Check, it is now actually possible to limit calls to Callable Cloud Functions to only those coming from iOS, Android and Web apps that are registered in your Firebase project.
You'll typically want to combine this with the user authentication based security that I described earlier/below, so that you have another shield against abusive users that do use your app.
It is still typically recommend to control access based on authenticating a user (allowing you to identify each individual user), and then ensuring they can only access data they're authorized for (in security rules).
If you don't want your users to have to sign in, you can use anonymous authentication. While this doesn't give you any information about the user, you can still identify them in security rules and thus limit their access based on what they've done.
By combining App Check with security rules, you have both broad protection and fine-grained control over what data everyone can access.

Resources