static int reset_password()

in ad-joining/ksetpwd/ksetpwd.c [66:162]


static int reset_password(
    /* [IN] */ krb5_context context,
    /* [IN] */ krb5_principal agent_principal,
    /* [IN, OPT] */ char *agent_principal_password,
    /* [IN] */ krb5_principal target_principal,
    /* [IN] */ char* new_password)
{
    krb5_error_code ret;
    krb5_creds agent_creds;
    int result;

    char* message = NULL;
    int server_result = 0;
    krb5_data server_result_string = {0};
    krb5_data server_result_code_string = {0};

    const int RESULT_SUCCESS = 0;
    const int RESULT_FAIL_AUTH_AGENT = 1;
    const int RESULT_FAIL_SET_PWD_KERBEROS_ERROR = 2;
    const int RESULT_FAIL_SET_PWD_SERVER_ERROR = 3;

    // Get initial credentials for agent.
    result = authenticate_agent(context, agent_principal, agent_principal_password, &agent_creds);
    if (result != 0)
    {
        if (result == KRB5KRB_AP_ERR_BAD_INTEGRITY)
        {
            com_err(NAME, 0, "Invalid password for agent principal");
        }
        else if (result == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
        {
            com_err(NAME, 0, "Agent principal does not exist in Active Directory");
        }
        else
        {
            com_err(NAME, ret, "Authenticating agent principal failed with code %d", result);
        }

        result = RESULT_FAIL_AUTH_AGENT;
        goto cleanup;
    }

    // Reset password of target principal.
    result = krb5_set_password(
        context,
        &agent_creds,
        new_password,
        target_principal,
        &server_result,
        &server_result_code_string,
        &server_result_string);
    if (result != 0)
    {
        result = RESULT_FAIL_SET_PWD_KERBEROS_ERROR;
        com_err(NAME, ret, "Resetting password failed");
        goto cleanup;
    }

    if (server_result)
    {
        if (krb5_chpw_message(context, &server_result_string, &message) != 0)
        {
            message = NULL;
        }

        fprintf(stderr, "%.*s%s%s (error code %d)\n",
            (int)server_result_code_string.length,
            server_result_code_string.data,
            message ? ": " : "",
            message ? message : NULL,
            server_result);

        result = RESULT_FAIL_SET_PWD_SERVER_ERROR;
        goto cleanup;
    }

    result = RESULT_SUCCESS;
    printf("Password changed.\n");

cleanup:
    if (message != NULL)
    {
        krb5_free_string(context, message);
    }

    if (server_result_string.data != NULL)
    {
        free(server_result_string.data);
    }

    if (server_result_code_string.data != NULL)
    {
        free(server_result_code_string.data);
    }

    return result;
}