<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; VB.NET: Авторизация OpenVPN через учётку Windows]]></title>
		<link>https://forum.script-coding.com/viewtopic.php?id=9647</link>
		<atom:link href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=9647&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «VB.NET: Авторизация OpenVPN через учётку Windows».]]></description>
		<lastBuildDate>Mon, 26 May 2014 06:13:16 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[VB.NET: Авторизация OpenVPN через учётку Windows]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=83318#p83318</link>
			<description><![CDATA[<p>Есть в природе OpenVPN, умеющий при авторизации пользователей запускать скрипт для дополнительной авторизации. Под линуксы скриптов навалом, под Windows&nbsp; нашел одну <a href="https://sites.google.com/site/amigo4life2/openvpn">портянку</a> на vbs, которая к тому же не заработала на моей ОС(так как AD там нет и быть не может). <br />Как оказалось, всё гораздо проще можно реализовать воспользовавшись <strong>.NET</strong>. Под данную реализацию потребуется версия 3.5(и выше - требуется наличие System.DirectoryServices.AccountManagement.PrincipalContext).</p><p>Для тех кто не сталкивался с OpenVPN в кратце поясню. При авторизации пользователя(помимо сертификатов и пр.) можно запросить у пользователя логин-пароль и проверить его в системных учётках ОС. Для этого в конфиге указывается скрипт, которому при запуске в виде параметра передаётся имя файла. В файле(временный, на время авторизации) содержится всего две строки - логин и пароль. В результате работы скрипта должен вернуться код завершения 0(успешная авторизация) или 1(не удалось авторизоваться).</p><p>Протестировано на:<br /></p><ul><li><p>Windows XP Pro SP3, VS2008(.NET 3.5)</p></li><li><p>Windows 2003 Server Web Edition, VB.NET 2010 Express(.Net 4.0 - на сайте MS 2008-ую эспресс студию уже не нашел)</p></li></ul><p>Приложение консольное. В проекте нужно добавить ссылку на System.DirectoryServices.AccountManagement.</p><p>Программа умеет:<br />1. Проверять пару логин-пароль.<br />2. Проверять нахождение пользователя в группе(непосредственно, без проверки вхождения через членство в других группах).<br />3. Работает для локальной авторизации и для домена(про домен - вроде работает, но мой комп не в домене и тест нельзя назвать полноценным).<br />4. Пишет лог(в файл).<br />5. Настройки берёт из INI-файла.</p><p>Пути сборок для наглядности не сокращал.</p><p>Основной модуль:<br /></p><div class="codebox"><pre><code>
Module winauth
    Dim logfile As System.IO.StreamWriter
    Dim pwdfile As System.IO.StreamReader
    Dim INI As New Class_ini_ops
    Function Main(ByVal cmdArgs() As String) As Integer
        Dim oContext As System.DirectoryServices.AccountManagement.PrincipalContext
        Dim oGroupUsers As System.DirectoryServices.AccountManagement.GroupPrincipal
        Dim usrName As String
        Dim usrPass As String
        Dim returnValue As Boolean

        Dim ini_file = System.Environment.CurrentDirectory.ToString &amp; &quot;\&quot; &amp; &quot;config.ini&quot;
        Dim ini_section = &quot;Configuration&quot;

        &#039;chk ini file
        If INI.GetSectionParams(ini_file, ini_section) Is Nothing Then
            Echo(&quot;Incorrect INI format.&quot;)
            Return 1
        End If

        Dim GroupName As String
        GroupName = INI.GetParamValue(ini_file, ini_section, &quot;GroupName&quot;)
        If GroupName Is Nothing Then
            Echo(&quot;User target group not set in ini-file.&quot;)
            Return 1
        End If

        &#039;имя(и путь) файла вынести в конфиг
        logfile = My.Computer.FileSystem.OpenTextFileWriter(&quot;winauth.log&quot;, True, _
                                                    System.Text.Encoding.GetEncoding(1251))
        logfile.AutoFlush = True

        &#039;check args
        If cmdArgs.Count &lt;&gt; 1 Then
            Echo(&quot;Wrong parametrs.&quot;)
            Return 1
        Else
            Try
                pwdfile = My.Computer.FileSystem.OpenTextFileReader(cmdArgs(0).ToString, _
                                                    System.Text.Encoding.GetEncoding(1251))
            Catch ex As Exception
                Echo(ex.Message.ToString)
                Echo(&quot;pwdfile not found.&quot;)
            End Try

            Try
                usrName = pwdfile.ReadLine.ToString
            Catch ex As Exception
                Echo(ex.Message.ToString)
                Echo(&quot;No data in pwdfile.&quot;)
                Return 1
            End Try

            Try
                usrPass = pwdfile.ReadLine.ToString
            Catch ex As Exception
                Echo(ex.Message.ToString)
                Echo(&quot;No password in pwdfile.&quot;)
                Return 1
            End Try
        End If
        pwdfile.Close()

        &#039;Get Auth context from INI, default is Local
        Dim iniContext
        iniContext = INI.GetParamValue(ini_file, ini_section, &quot;Context&quot;)
        If iniContext Is Nothing Then
            iniContext = &quot;Local&quot;
        End If

        &#039; Set PrincipalContext
        Dim DN As String = &quot;&quot;
        Dim PDC As String = &quot;&quot;
        Select Case iniContext
            Case &quot;Local&quot;
                oContext = New System.DirectoryServices.AccountManagement.PrincipalContext( _
                            System.DirectoryServices.AccountManagement.ContextType.Machine, _
                            System.Environment.MachineName.ToString)
            Case &quot;Domain&quot;
                PDC = INI.GetParamValue(ini_file, ini_section, &quot;PDC&quot;)
                If PDC Is Nothing Then
                    Echo(&quot;PDC not set in ini-file.&quot;)
                    Return 1
                End If
                DN = INI.GetParamValue(ini_file, ini_section, &quot;DN&quot;)
                If DN Is Nothing Then
                    Echo(&quot;DN not set in ini-file.&quot;)
                    Return 1
                End If
                oContext = New System.DirectoryServices.AccountManagement.PrincipalContext( _
                                System.DirectoryServices.AccountManagement.ContextType.Domain, _
                                PDC, DN)
            Case Else
                Echo(&quot;Context not set in ini-file or incorrect.&quot;)
                Return 1
        End Select

        &#039;Check that the user is a member of the group
        oGroupUsers = System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(oContext, _
                                DirectoryServices.AccountManagement.IdentityType.Name, _
                                GroupName)
        Dim oUsers As System.DirectoryServices.AccountManagement.PrincipalSearchResult(Of  _
                                        System.DirectoryServices.AccountManagement.Principal)
        oUsers = Nothing
        If oGroupUsers Is Nothing Then
            Echo(&quot;No such group [&quot; &amp; GroupName &amp; &quot;] found.&quot;)
            Return 1
        Else
            oUsers = oGroupUsers.GetMembers
        End If

        If oUsers.Contains(System.DirectoryServices.AccountManagement.Principal.FindByIdentity(oContext, usrName)) Then
            Debug.Print(&quot;caught!&quot;)
        Else
            Debug.Print(&quot;shot at milk...&quot;)
            Select Case iniContext
                Case &quot;Local&quot;
                    Echo(&quot;Group check failure: the user is not a member of [&quot; &amp; GroupName &amp; &quot;].&quot;)
                Case &quot;Domain&quot;
                    Echo(&quot;Group check failure: the user is not a member of [&quot; &amp; GroupName &amp; &quot;@{&quot; &amp; DN &amp; &quot;}].&quot;)
            End Select
            Return 1
        End If

        Try
            returnValue = oContext.ValidateCredentials(usrName, usrPass)
        Catch ex As Exception
            Echo(ex.Message.ToString)
            Return 1
            &#039;Error Codes list for Microsoft technologies:
            &#039;http://www.symantec.com/business/support/index?page=content&amp;id=TECH12638
            &#039;&quot;HRESULT: 0x80070533&quot; == &quot;Logon failure: account currently disabled.&quot;
        End Try

        Select Case returnValue
            Case False
                Echo(&quot;Logon failure: username or password incorrect.&quot;)
                Return 1
            Case True
                Echo(&quot;Logon is successful.&quot;)
                Return 0
            Case Else
                Echo(&quot;Unknown Error?&quot;)
                Return 1
        End Select
    End Function
    Sub Echo(ByVal text)
        Console.WriteLine(text)
        Debug.Print(text)
        logfile.WriteLine(Now() &amp; &quot;:&gt; &quot; &amp; text)
    End Sub
End Module
</code></pre></div><p>Клас для работы с INI:<br /></p><div class="codebox"><pre><code>
Public Class Class_ini_ops
    &#039;изначально была копипаста отсюда: http://www.cyberforum.ru/vb-net/thread382768.html
#Region &quot;API Calls&quot;
    Private Declare Unicode Function WritePrivateProfileString Lib &quot;kernel32&quot; _
    Alias &quot;WritePrivateProfileStringW&quot; (ByVal lpApplicationName As String, _
    ByVal lpKeyName As String, ByVal lpString As String, _
    ByVal lpFileName As String) As Integer

    Private Declare Unicode Function GetPrivateProfileString Lib &quot;kernel32&quot; _
    Alias &quot;GetPrivateProfileStringW&quot; (ByVal lpApplicationName As String, _
    ByVal lpKeyName As String, ByVal lpDefault As String, _
    ByVal lpReturnedString As String, ByVal nSize As Int32, _
    ByVal lpFileName As String) As Integer
#End Region
    ReadOnly CallBufferSize As Short = 4096
    Public Function GetSectionsList(ByVal INIfile As String) As Array
        Dim n As Integer
        Dim sData As String
        Dim sb As New System.Text.StringBuilder
        sData = sb.Insert(0, vbNullChar, CallBufferSize).ToString
        n = GetPrivateProfileString(vbNullString, vbNullString, vbNullString, sData, CallBufferSize, INIfile)
        If n &gt; 0 Then
            GetSectionsList = sData.Substring(0, n - 1).Split(vbNullChar)
        Else
            GetSectionsList = Nothing
        End If
    End Function
    Public Function GetSectionParams(ByVal INIfile As String, ByVal SectionName As String) As Array
        Dim n As Integer
        Dim sData As String
        Dim sb As New System.Text.StringBuilder
        sData = sb.Insert(0, vbNullChar, CallBufferSize).ToString
        n = GetPrivateProfileString(SectionName, vbNullString, vbNullString, sData, CallBufferSize, INIfile)
        If n &gt; 0 Then
            GetSectionParams = sData.Substring(0, n - 1).Split(vbNullChar)
        Else
            GetSectionParams = Nothing
        End If
    End Function
    Public Overloads Function GetParamValue(ByVal INIfile As String, ByVal SectionName As String, ByVal ParamName As String) As String
        Dim n As Integer
        Dim sData As String
        Dim sb As New System.Text.StringBuilder
        sData = sb.Insert(0, vbNullChar, CallBufferSize).ToString
        n = GetPrivateProfileString(SectionName, ParamName, vbNullString, sData, CallBufferSize, INIfile)
        If n &gt; 0 Then
            GetParamValue = sData.Substring(0, n)
        Else
            GetParamValue = Nothing
        End If
    End Function
    Public Overloads Function GetParamValue(ByVal INIfile As String, ByVal SectionName As String, ByVal ParamName As String, _
                                            ByVal DefaultValue As String) As String
        Dim n As Integer
        Dim sData As String
        Dim sb As New System.Text.StringBuilder
        sData = sb.Insert(0, vbNullChar, CallBufferSize).ToString
        n = GetPrivateProfileString(SectionName, ParamName, DefaultValue, sData, CallBufferSize, INIfile)
        If n &gt; 0 Then
            GetParamValue = sData.Substring(0, n)
        Else
            GetParamValue = Nothing
        End If
    End Function
    Public Function SetParamValue(ByVal INIfile As String, ByVal SectionName As String, ByVal ParamName As String, _
                                  ByVal ParamValue As String) As Boolean
        Call WritePrivateProfileString(SectionName, ParamName, ParamValue, INIfile)
        If ParamValue = GetParamValue(INIfile, SectionName, ParamName) Then
            SetParamValue = True
        Else
            SetParamValue = False
        End If
    End Function
End Class
</code></pre></div><p>Пример конфига(config.ini, ищется в папке в приложением):<br /></p><div class="codebox"><pre><code>
[Configuration]
;set auth context
;Local - check local credentials(default)
;Domain -  check credentials in Domain
Context = Local

; Used only in Context = Domain
PDC = MyServer
DN = &quot;DC=mydomain,DC=local&quot;

;target user group
GroupName = &quot;Операторы сервера&quot;
</code></pre></div><br /><br /><p>P.S. Решение &quot;вылежалось&quot; с пол года, так что публикую как есть. Будут коментарии -&gt; тема в обсуждениях: <a href="http://forum.script-coding.com/viewtopic.php?id=9001">Серый форум&nbsp; ? Общение&nbsp; ? Прочие скриптовые технологии и близкие к ним&nbsp; ? VB.NET: Авторизация OpenVPN через учётку Windows</a></p>]]></description>
			<author><![CDATA[null@example.com (BeS Yara)]]></author>
			<pubDate>Mon, 26 May 2014 06:13:16 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=83318#p83318</guid>
		</item>
	</channel>
</rss>
