It's the 22nd Amendment. The operative language is the first part of Section 1 (the rest and Section 2 basically just describe who it will/will not apply to based on when/how it's ratified and established; it essentially no longer matters since that day is well past already) is as follows;
No person shall be elected to the office of the President more than twice, and no person who has held the office of President, or acted as President, for more than two years of a term to which some other person was elected President shall be elected to the office of President more than once.
There's two clauses in there;
1> No person shall be elected to the office of the President more than twice, and
2> No person who has held the office, or acted as President, for more than two years of a term someone else was elected president, shall be elected as President more than once.
Clause 1 is easy. You can't be
elected more than twice.
Clause 2 adds the complication, and describes how it works if, say, a Vice President has to step into the role because the President has died. If they end up President with more than two years remaining in that term, it basically "counts" as a term for themselves, and they can't be elected more than once.
However, it
clearly makes a distinction between people who have "held the office", or "acted as President", and who were "elected to the office". They're not the same thing, or we wouldn't
need a second clause. And Clause 2 only prevents such individuals being
elected to another term, as President.
So you're right; Obama can be elected as a VP. And then if his President has a heart attack a week after taking up the office, Obama could be President again for another nearly full term. He can't run for President for 2024, because he's already been elected twice and Clause 1 prevents that, but he
could run as VP again, forever, theoretically. And keep taking up additional terms as President because the elected President dies early. That would be crazy and conspiracy theorists would run wild, but it would be
legally justifiable, and there wouldn't be any grounds to oppose Obama's position as VP, or his taking over the Presidency in the aftermath of a tragic Presidential death.
SCOTUS would need grounds to oppose this, and the 22nd Amendment is
really clear. You can't be
elected as President again, if you've been elected twice, or once plus filling the role for more than 2 years of a term. By making that distinction in the second clause, that clearly means that's something other than being elected to the office, so such an event cannot be construed as breaching the two-term rule, which
only applies to elections.