What the other answers are missing is a clear explanation of why it is dangerous for a sub to enter a harbor.
The reason why a sub cannot normally enter a harbor, like Boston Harbor or New York Harbor, is that they are shallow, confined areas. New York Harbor is about 50 feet deep. Boston Harbor is even more shallow, less than 20 feet in many places. It has to be constantly dredged, just to maintain 40 ft deep channels. A WW2 submarine is about 30-40 feet high including masts. So, a sub would be practically sticking out of the water in such a harbor and easily visible as a shadow from the air.
Also, if a sub entered a harbor and was spotted it would be trapped, because the ways in and out are so limited.
There is a very famous harbor attack: the sinking of the HMS Royal Oak in Scapa Flow on 14 October 1939. This was only possible because Scapa Flow is very large, deep harbor. Even so, it was very daring and dangerous for the U-boat to have entered.