Let $\xi:E\rightarrow M$ be a vector bundle, $\xi^+:E^+\rightarrow M$ its adjoint bundle, defined as $E^+=E^\ast\otimes\Lambda^m(M)$ (where $m=\dim M$), whose sections are interpreted as the set of all vector bundle morphisms $E\rightarrow \Lambda^m(M)$.
Let $D:\Gamma(E)\rightarrow\Gamma(E^+)$ be a linear differential operator. Due to its signature, its formal adjoint $D^+:\Gamma(E)\rightarrow\Gamma(E^+)$ has the same signature, so it makes sense to talk about $D$ being formally selfadjoint.
It is well-known that the linear differential equation $D(\phi)=0$ admits a Lagrangian description if and only if $D$ is formally selfadjoint. A corresponding Lagrangian is given by $$ L[\phi]=\langle D(\phi),\phi\rangle, $$ where $\langle -,-\rangle$ is the pairing of $E^+$ and $E$ (it is $\Lambda^m(M)$-valued, so this is a Lagrangian $m$-form).
It is fairly easy to prove that this is the case. Take the variation $$ \delta L[\phi]=\langle D(\phi),\delta\phi\rangle + \langle D(\delta\phi),\phi\rangle, $$ and in the second term we use $$ \langle D(\delta\phi),\phi\rangle=\langle\delta\phi, D^+(\phi)\rangle + dB(\phi,\delta\phi) = \langle \delta\phi, D(\phi)\rangle + dB(\phi,\delta\phi), $$ where at the first equality we used the definition of the formal adjoint ($B$ is an $m-1$-form valued bidifferential operator whose exact form is not relevant now), and at the second equality we used the fact that $D$ is self-adjoint. Since $E^{++}=E$, the pair bracket $\langle-,-\rangle$ can be regarded as symmetric, so we get $$ \delta L = 2\langle D(\phi),\delta\phi\rangle + d(\cdots), $$ so the Euler--Lagrange derivative is $2D(\phi)$, i.e. the EL equation is equivalent to $D(\phi)=0$.
Now in the case in the OP it is sufficient to recognize that the linear differential operator $g^{ij}\partial^2-\partial^i\partial^j$ is formally selfadjoint.
This also explains why essentially all "free field" equations have Lagrangians of this form.
Edit: Let $D:\Gamma(E)\rightarrow\Gamma(F)$ be a linear differential operator between vector bundles $E,F\rightarrow M$. The formal adjoint of $D$ is the unique linear differential operator $D^+:\Gamma(E^+)\rightarrow\Gamma(F^+)$ such that the equation $$ \langle \psi,D(\phi)\rangle-\langle D^+(\psi),\phi\rangle = dB(\phi,\psi) $$holds, where $\phi\in\Gamma(E)$, $\psi\in\Gamma(F^+)$, and $B:\Gamma(E)\times\Gamma(F^+)\rightarrow\Omega^{m-1}(M)$ is any bivariate linear differential operator with values in $m-1$-forms. So the formal adjoint is defined such that $D$ and $D^+$ are adjoint with respect to the bracket $\langle -,-\rangle$ "up to an exact term".
The thing is that $B$ is not uniquely defined as $B^\prime = B + dC$ - where $C:\Gamma(E)\times\Gamma(F^+)\rightarrow\Omega^{m-2}$ is any bivariate differential operator - is also an equivalently good $B$.
So the answer can be understood simply as "$dB$ is some surface term".