Implement setgid/setuid support.

Fixes #3841
Set group before user.