I'm thinking about the Flying Fortress style heavy bombers.
This covers a few aspects:
Defensive machine guns. These bombers fly in these dense 3D formations and the defensive gunners must hit high speed targets, so I'd imagine stray bursts hitting other planes. Did that happen a lot and was this managed or trained for? Did enemy fighters actually cross insidethe bomber mass at all?
When dropping bombs, did bombers ever hit each other? I'd say a freefalling metal bomb would make a huge hole into an airframe, taking of a wing easily. The airforce must been aware of this, how was this managed?
Mid-air collisions seem a danger, with some many airplanes in one volume, bad weather, flak etc.
There were incidents of bombers being hit by bombs from above. You can see in the pictures that the bombs hit the tail of the bomber, snapping off the left side of it. The bombs should not have exploded at that point (and they didn't) as so far as I know such bombs universally used air flow to arm themselves on the way down. It was a rare occurrence, but it happened often enough to be photographed on multiple occasions and reported in a number of other occasions.
You are correct in pointing out that there were dangers in flying so close to friendly forces. First, this danger was much less than flying alone (during daylight at least) as you could concentrate your defensive firepower. As to the dangers of friendly fire from machine guns or from planes maneuvering while in formation, that was limited by strict adherence to doctrine. Since the planes stayed in rigid formation, you could reliably predict where all of your friendly planes were and try to cease fire before hitting them. German pilots would seldom risk going within the American bomber formations as it was a high risk tactic, but it did happen. Adherence to doctrine would also mitigate the dangers of your bombs hitting friendlies as well. As to #3, no matter how much you wanted to maneuver to avoid incoming fire, the pilot would not do so unless under extreme conditions. Only being damaged severely would prompt a pilot to fall out of formation, so midair plane collisions were highly rare (but did happen). Famously two bombers had a "piggyback" incident in one of the more bizarre incidents in WWII