Given only $p,$ $g,$ $A = g^a\pmod{p}$ and $B = g^b\pmod{p},$ the possible values for the shared secret are all the unique values of $A^b\pmod{p}$, where b is some integer. The shared secret is also equal to $B^a\pmod{p}$, where a is some integer.
So, we can check each one of these possible values for the shared secret. My question is, how do we check if a number is the correct shared secret?
My guess is this:
Usually the shared secret is used in a symmetric encryption scheme, the overall terms of which must logically be agreed upon in the public channel. So from our vantage point, we would know what type of symmetric encryption is being used, and therefore how the shared secret is being used, and could therefore try decrypting a given message with each possible shared secret until we find one that gives us the original, unencrypted message. But then we would have to know what the original unencrypted message should look like.