Set an object permission for the given user sid

def set_user_perm(obj, perm, sid):
    '''
    Set an object permission for the given user sid
    '''
    info = (
        win32security.OWNER_SECURITY_INFORMATION |
        win32security.GROUP_SECURITY_INFORMATION |
        win32security.DACL_SECURITY_INFORMATION
    )
    sd = win32security.GetUserObjectSecurity(obj, info)
    dacl = sd.GetSecurityDescriptorDacl()
    ace_cnt = dacl.GetAceCount()
    found = False
    for idx in range(0, ace_cnt):
        (aceType, aceFlags), ace_mask, ace_sid = dacl.GetAce(idx)
        ace_exists = (
            aceType == ntsecuritycon.ACCESS_ALLOWED_ACE_TYPE and
            ace_mask == perm and
            ace_sid == sid
        )
        if ace_exists:
            # If the ace already exists, do nothing
            break
    else:
        dacl.AddAccessAllowedAce(dacl.GetAclRevision(), perm, sid)
        sd.SetSecurityDescriptorDacl(1, dacl, 0)
        win32security.SetUserObjectSecurity(obj, info, sd)