I originally misread the question and thought you wanted $A\subset f^{-1}(0)$ and $B\subset f^{-1}(1)$. This can be arranged, as I suggested, with a simple partition of unity argument:
Let $\{\phi_i\}$ be a partition of unity subordinate to the open cover $\mathscr U = \{X-A,X-B\}$ of $X$. Let $$\phi_A = \sum_{i: \,\text{supp }\phi_i\subset X-B} \phi_i \qquad\text{and}\qquad \phi_B = \sum_{i:\, \text{supp }\phi_i\subset X-A} \phi_i.$$
Note that $\phi_B(x)=0$ when $x\in A$, $\phi_B(x)=1$ when $x\in B$ (since $\phi_A+\phi_B=1$), and, of course, $0\le\phi_B\le 1$. Thus, the function $f=\phi_B$ will do.
To get the full result you seek we need to be a bit trickier. As @zhw suggested, it will suffice to find a smooth function $g$ with $g^{-1}(0)=A$ and $g\ge 0$. For then we similarly find a smooth function $h$ with $h^{-1}(0)=B$ and $h\ge 0$ and take $f=g/(g+h)$.
Here's a sketch of how you can obtain $g$. Let $\{U_i\}$ be a countable open cover of $M-A$ by sets diffeomorphic to an open ball with the property that sub-balls $U'_i\subset \overline{U'_i}\subset U_i$ also cover $M-A$. Let $g_i\colon M\to [0,1]$ be a smooth function with $g_i>0$ on $U'_i$ and $g_i=0$ on $M-U'_i$. Then the partial derivatives of $g_1,g_2,\dots,g_i$ of all orders $\le i$ are bounded (in magnitude) above on $M$, say, by $k_i>0$. Define
$$g = \sum_i \frac{g_i}{k_i2^i},$$
and check that $g\in C^\infty$ and $g^{-1}(0)=A$.