Is it valid to modify a student's exam grade if you feel they did not earn it?
Since you ask, specifically, about legality, I'll say that it is unlikely that it would be a matter of criminal law anywhere, though, of course, I can't know the laws of every jurisdiction. But it could well be a matter of civil law and if this were known could easily generate a lawsuit against everyone involved. 

I think that a person would be very hesitant to apply such a "rule" to the child of some powerful person. It depends, I think, on people either not knowing what really occurred or being so powerless as to be completely unable to prevent it. 

But, as I've been saying in comments here, it is a profoundly unethical act and would, in my view be grounds for at least a reprimand, and even termination as an act of moral turpitude if repeated. It turns what should be a well determined process in to a form of chaos where we are just at the mercy of the powers. 

An instructor needs to set a standard before the course begins and needs to make that public. You can make it as hard as you like and you can interpret it as strictly as you like, but you can't deviate from it to the detriment of an individual. I have no complaint about generous interpretations as most of us, I hope, consider generosity to be laudable and to believe that students can learn and improve. 

I won't condemn you personally, however, since you may have had no agency here and may be as much a victim as the student involved. But I will condemn the professor, who should, at a minimum be reported to the dean for this behavior. Especially since the course is a gateway course and changing their grade to make it failing when it was not also denies them the opportunity to go on and, one hopes, improve. 

It was especially pernicious, here, that the induced change in the average was set not only to unethically push the student below the passing grade, but further down so that it would be less likely they could appeal. 

My advice to you personally, is to find a better mentor as soon as you can. This person is teaching you to do harm. 

And, I don't know how you can make it up to the person you damaged. It may be too late, even to request a grade change. But the dean should be informed and if it is only you that knows that the professor is behaving this way, it is probably your responsibility to so inform them. I won't suggest that you do, of course, since it might have too adverse an effect on your own career, but there is an imbalance in justice that hasn't been corrected.