Search in sources :

Example 6 with Account

use of com.sun.jna.platform.win32.Advapi32Util.Account in project gitblit by gitblit.

the class WindowsAuthProvider method authenticate.

@Override
public UserModel authenticate(String username, char[] password) {
    String defaultDomain = settings.getString(Keys.realm.windows.defaultDomain, null);
    if (StringUtils.isEmpty(defaultDomain)) {
        // ensure that default domain is null
        defaultDomain = null;
    }
    if (defaultDomain != null) {
        // sanitize username
        if (username.startsWith(defaultDomain + "\\")) {
            // strip default domain from domain\ username
            username = username.substring(defaultDomain.length() + 1);
        } else if (username.endsWith("@" + defaultDomain)) {
            // strip default domain from username@domain
            username = username.substring(0, username.lastIndexOf('@'));
        }
    }
    IWindowsIdentity identity = null;
    try {
        if (username.indexOf('@') > -1 || username.indexOf('\\') > -1) {
            // manually specified domain
            identity = waffle.logonUser(username, new String(password));
        } else {
            // no domain specified, use default domain
            identity = waffle.logonDomainUser(username, defaultDomain, new String(password));
        }
    } catch (Win32Exception e) {
        logger.error(e.getMessage());
        return null;
    }
    if (identity.isGuest() && !settings.getBoolean(Keys.realm.windows.allowGuests, false)) {
        logger.warn("Guest account access is disabled");
        identity.dispose();
        return null;
    }
    UserModel user = userManager.getUserModel(username);
    if (user == null) {
        // create user object for new authenticated user
        user = new UserModel(username.toLowerCase());
    }
    // create a user cookie
    setCookie(user);
    // update user attributes from Windows identity
    user.accountType = getAccountType();
    String fqn = identity.getFqn();
    if (fqn.indexOf('\\') > -1) {
        user.displayName = fqn.substring(fqn.lastIndexOf('\\') + 1);
    } else {
        user.displayName = fqn;
    }
    user.password = Constants.EXTERNAL_ACCOUNT;
    Set<String> groupNames = new TreeSet<String>();
    for (IWindowsAccount group : identity.getGroups()) {
        groupNames.add(group.getFqn());
    }
    if (settings.getBoolean(Keys.realm.windows.permitBuiltInAdministrators, true)) {
        if (groupNames.contains("BUILTIN\\Administrators")) {
            // local administrator
            user.canAdmin = true;
        }
    }
    // TODO consider mapping Windows groups to teams
    // push the changes to the backing user service
    updateUser(user);
    // cleanup resources
    identity.dispose();
    return user;
}
Also used : UserModel(com.gitblit.models.UserModel) TreeSet(java.util.TreeSet) IWindowsAccount(waffle.windows.auth.IWindowsAccount) IWindowsIdentity(waffle.windows.auth.IWindowsIdentity) Win32Exception(com.sun.jna.platform.win32.Win32Exception)

Example 7 with Account

use of com.sun.jna.platform.win32.Advapi32Util.Account in project jna by java-native-access.

the class Advapi32Util method getCurrentUserGroups.

/**
	 * Return the group memberships of the currently logged on user.
	 *
	 * @return An array of groups.
	 */
public static Account[] getCurrentUserGroups() {
    HANDLEByReference phToken = new HANDLEByReference();
    Win32Exception err = null;
    try {
        // open thread or process token
        HANDLE threadHandle = Kernel32.INSTANCE.GetCurrentThread();
        if (!Advapi32.INSTANCE.OpenThreadToken(threadHandle, TOKEN_DUPLICATE | TOKEN_QUERY, true, phToken)) {
            int rc = Kernel32.INSTANCE.GetLastError();
            if (rc != W32Errors.ERROR_NO_TOKEN) {
                throw new Win32Exception(rc);
            }
            HANDLE processHandle = Kernel32.INSTANCE.GetCurrentProcess();
            if (!Advapi32.INSTANCE.OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_QUERY, phToken)) {
                throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
            }
        }
        return getTokenGroups(phToken.getValue());
    } catch (Win32Exception e) {
        err = e;
        // re-throw in order to invoke finally block
        throw err;
    } finally {
        HANDLE hToken = phToken.getValue();
        if (!WinBase.INVALID_HANDLE_VALUE.equals(hToken)) {
            try {
                Kernel32Util.closeHandle(hToken);
            } catch (Win32Exception e) {
                if (err == null) {
                    err = e;
                } else {
                    err.addSuppressed(e);
                }
            }
        }
        if (err != null) {
            throw err;
        }
    }
}
Also used : HANDLEByReference(com.sun.jna.platform.win32.WinNT.HANDLEByReference) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Example 8 with Account

use of com.sun.jna.platform.win32.Advapi32Util.Account in project jna by java-native-access.

the class Advapi32Util method getTokenGroups.

/**
	 * This function returns the groups associated with a security token, such
	 * as a user token.
	 *
	 * @param hToken
	 *            Token.
	 * @return Token groups.
	 */
public static Account[] getTokenGroups(HANDLE hToken) {
    // get token group information size
    IntByReference tokenInformationLength = new IntByReference();
    if (Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, null, 0, tokenInformationLength)) {
        throw new RuntimeException("Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
    }
    int rc = Kernel32.INSTANCE.GetLastError();
    if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
        throw new Win32Exception(rc);
    }
    // get token group information
    WinNT.TOKEN_GROUPS groups = new WinNT.TOKEN_GROUPS(tokenInformationLength.getValue());
    if (!Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenGroups, groups, tokenInformationLength.getValue(), tokenInformationLength)) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    ArrayList<Account> userGroups = new ArrayList<Account>();
    // make array of names
    for (SID_AND_ATTRIBUTES sidAndAttribute : groups.getGroups()) {
        Account group = null;
        try {
            group = Advapi32Util.getAccountBySid(sidAndAttribute.Sid);
        } catch (Exception e) {
            group = new Account();
            group.sid = sidAndAttribute.Sid.getBytes();
            group.sidString = Advapi32Util.convertSidToStringSid(sidAndAttribute.Sid);
            group.name = group.sidString;
            group.fqn = group.sidString;
            group.accountType = SID_NAME_USE.SidTypeGroup;
        }
        userGroups.add(group);
    }
    return userGroups.toArray(new Account[0]);
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) ArrayList(java.util.ArrayList) SID_AND_ATTRIBUTES(com.sun.jna.platform.win32.WinNT.SID_AND_ATTRIBUTES) IOException(java.io.IOException)

Example 9 with Account

use of com.sun.jna.platform.win32.Advapi32Util.Account in project jna by java-native-access.

the class Advapi32Util method getAccountByName.

/**
	 * Retrieves a security identifier (SID) for a given account.
	 *
	 * @param systemName
	 *            Name of the system.
	 * @param accountName
	 *            Account name.
	 * @return A structure containing the account SID.
	 */
public static Account getAccountByName(String systemName, String accountName) {
    IntByReference pSid = new IntByReference(0);
    IntByReference cchDomainName = new IntByReference(0);
    PointerByReference peUse = new PointerByReference();
    if (Advapi32.INSTANCE.LookupAccountName(systemName, accountName, null, pSid, null, cchDomainName, peUse)) {
        throw new RuntimeException("LookupAccountNameW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
    }
    int rc = Kernel32.INSTANCE.GetLastError();
    if (pSid.getValue() == 0 || rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
        throw new Win32Exception(rc);
    }
    Memory sidMemory = new Memory(pSid.getValue());
    PSID result = new PSID(sidMemory);
    char[] referencedDomainName = new char[cchDomainName.getValue() + 1];
    if (!Advapi32.INSTANCE.LookupAccountName(systemName, accountName, result, pSid, referencedDomainName, cchDomainName, peUse)) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }
    Account account = new Account();
    account.accountType = peUse.getPointer().getInt(0);
    account.name = accountName;
    String[] accountNamePartsBs = accountName.split("\\\\", 2);
    String[] accountNamePartsAt = accountName.split("@", 2);
    if (accountNamePartsBs.length == 2) {
        account.name = accountNamePartsBs[1];
    } else if (accountNamePartsAt.length == 2) {
        account.name = accountNamePartsAt[0];
    } else {
        account.name = accountName;
    }
    if (cchDomainName.getValue() > 0) {
        account.domain = Native.toString(referencedDomainName);
        account.fqn = account.domain + "\\" + account.name;
    } else {
        account.fqn = account.name;
    }
    account.sid = result.getBytes();
    account.sidString = convertSidToStringSid(new PSID(account.sid));
    return account;
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) Memory(com.sun.jna.Memory) PointerByReference(com.sun.jna.ptr.PointerByReference) PSID(com.sun.jna.platform.win32.WinNT.PSID)

Example 10 with Account

use of com.sun.jna.platform.win32.Advapi32Util.Account in project jna by java-native-access.

the class Advapi32UtilTest method testGetUserGroups.

public void testGetUserGroups() {
    USER_INFO_1 userInfo = new USER_INFO_1();
    userInfo.usri1_name = "JNANetapi32TestUser";
    userInfo.usri1_password = "!JNAP$$Wrd0";
    userInfo.usri1_priv = LMAccess.USER_PRIV_USER;
    // ignore test if not able to add user (need to be administrator to do this).
    if (LMErr.NERR_Success != Netapi32.INSTANCE.NetUserAdd(null, 1, userInfo, null)) {
        return;
    }
    try {
        HANDLEByReference phUser = new HANDLEByReference();
        try {
            assertTrue(Advapi32.INSTANCE.LogonUser(userInfo.usri1_name.toString(), null, userInfo.usri1_password.toString(), WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phUser));
            Account[] groups = Advapi32Util.getTokenGroups(phUser.getValue());
            assertTrue(groups.length > 0);
            for (Account group : groups) {
                assertTrue(group.name.length() > 0);
                assertTrue(group.sidString.length() > 0);
                assertTrue(group.sid.length > 0);
            }
        } finally {
            HANDLE hUser = phUser.getValue();
            if (!WinBase.INVALID_HANDLE_VALUE.equals(hUser)) {
                Kernel32Util.closeHandle(hUser);
            }
        }
    } finally {
        assertEquals("Error in NetUserDel", LMErr.NERR_Success, Netapi32.INSTANCE.NetUserDel(null, userInfo.usri1_name.toString()));
    }
}
Also used : Account(com.sun.jna.platform.win32.Advapi32Util.Account) HANDLEByReference(com.sun.jna.platform.win32.WinNT.HANDLEByReference) USER_INFO_1(com.sun.jna.platform.win32.LMAccess.USER_INFO_1) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Aggregations

Account (com.sun.jna.platform.win32.Advapi32Util.Account)6 PSID (com.sun.jna.platform.win32.WinNT.PSID)4 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)3 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)3 IntByReference (com.sun.jna.ptr.IntByReference)3 USER_INFO_1 (com.sun.jna.platform.win32.LMAccess.USER_INFO_1)2 PointerByReference (com.sun.jna.ptr.PointerByReference)2 UserModel (com.gitblit.models.UserModel)1 Memory (com.sun.jna.Memory)1 Win32Exception (com.sun.jna.platform.win32.Win32Exception)1 PSIDByReference (com.sun.jna.platform.win32.WinNT.PSIDByReference)1 SID_AND_ATTRIBUTES (com.sun.jna.platform.win32.WinNT.SID_AND_ATTRIBUTES)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 TreeSet (java.util.TreeSet)1 IWindowsAccount (waffle.windows.auth.IWindowsAccount)1 IWindowsIdentity (waffle.windows.auth.IWindowsIdentity)1