elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Fallo al iniciar sesion
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Fallo al iniciar sesion  (Leído 5,365 veces)
Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
Fallo al iniciar sesion
« en: 29 Marzo 2015, 23:39 pm »

No consigo iniciar sesion en esta web:

Código:
<form action="http://www.web.com/index.php/users/dologin" method="post" accept-charset="utf-8">    <p align="center"><label>Usuario</label>    <input type="text" name="usuario" value="" id="keyboard"  /></p>

    <p align="center"><label>Contraseña</label>    <input type="password" name="contrasena" value="" id="keyboard_pwd"  /></p>

    <p align="center"><input type="submit" name="submit" value="Login"  /></p>
    </form>

Estoy usando C#uso esto:

Código
  1. public void signUp(string usuario, string contraseña)
  2.        {
  3.            string postData = "usuario=" + usuario + "&contrasena=" + contraseña + "&submit=Login";
  4.            byte[] byteData = ASCIIEncoding.ASCII.GetBytes(postData);
  5.            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.web.com/index.php/users/dologin");
  6.            req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//utf-8;
  7.            req.ContentType = "application/x-www-form-urlencoded";
  8.            req.ContentLength = byteData.Length;
  9.            req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0";
  10.            req.Host = "www.web.com";
  11.            req.Method = "POST";
  12.            req.Proxy = null;
  13.            using (Stream reqStream = req.GetRequestStream())
  14.                reqStream.Write(byteData, 0, byteData.Length);
  15.            GetResponse(req);
  16.        }
  17.  
  18.        private static void GetResponse(HttpWebRequest req)
  19.        {
  20.            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
  21.            using (Stream responseStream = response.GetResponseStream())
  22.            {
  23.                using (StreamReader sr = new StreamReader(responseStream))
  24.                {
  25.                    string responseData = sr.ReadToEnd();
  26.                    Console.WriteLine(responseData);
  27.                    if (responseData.Contains("Salir de"))
  28.                        Console.WriteLine("Login successful!");
  29.                    else
  30.                        Console.WriteLine("Login failed!");
  31.                }
  32.            }
  33.        }

¿Que puedo estar pasando por alto?, saludos y gracias.

Edito: Aporto mas informacion, el servidor me devuelve la pagina del index, si no pongo la variable usuario y la escribo mal (PE usaodi) me dice que el campo de usuario no esta rellenado, igual ocurre con la contraseña luego es algo que si que envio, pero apesar de que el nombre y usuario son correctos y consigo iniciar sesion en navegador, con el programa aun no lo he conseguido.

Saludos.


« Última modificación: 29 Marzo 2015, 23:51 pm por Kaxperday » En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: Fallo al iniciar sesion
« Respuesta #1 en: 30 Marzo 2015, 11:13 am »

¿Que puedo estar pasando por alto?, saludos y gracias.

1. ¿Te has asegurado de codificar los valores de los parámetros en caso de que contengan caracteres especiales como espacios en blanco, puntos, etc?:
Código
  1. HttpUtility.UrlEncode(usuario);
  2. HttpUtility.UrlEncode(contraseña);

2. ¿Has comprobado que le estás pasando las cabeceras correctas?.

3. De todas formas podrías necesitar más que eso, prueba a obtener la Cookie de visitante en la página principal, y luego a loguearte usando dicha cookie,
escribí este snippet al que se le puede dar un uso más o menos genérico que podría servir para tu situación, le hice unas pequeñas modificaciones para adaptarlo a tus necesidades, solo modifica los valores de la propiedades 'UrlMain', 'UrlLogin', 'UrlLoginQueryFormat', comprueba las cabeceras que asigno en 'RequestHeadersPostLogin' sean correctas y no falten más, y por último llama al método 'CheckLogin' para evaluar el login.

VB.Net:
Código
  1.  
  2.    ''' <summary>
  3.    ''' Gets the main url.
  4.    ''' </summary>
  5.    ''' <value>The main url.</value>
  6.    Public ReadOnly Property UrlMain As String
  7.        Get
  8.            Return "http://www.cgwallpapers.com/"
  9.        End Get
  10.    End Property
  11.  
  12.    ''' <summary>
  13.    ''' Gets the login url.
  14.    ''' </summary>
  15.    ''' <value>The login url.</value>
  16.    Public ReadOnly Property UrlLogin As String
  17.        Get
  18.            Return "http://www.cgwallpapers.com/login.php"
  19.        End Get
  20.    End Property
  21.  
  22.    ''' <summary>
  23.    ''' Gets the login query string format.
  24.    ''' </summary>
  25.    ''' <value>The login query string format.</value>
  26.    Public ReadOnly Property UrlLoginQueryFormat As String
  27.        Get
  28.            Return "usuario={0}&contrasena={1}"
  29.        End Get
  30.    End Property
  31.  
  32.    ''' <summary>
  33.    ''' Gets the headers for a Login POST request.
  34.    ''' </summary>
  35.    ''' <value>The headers for a Login POST request.</value>
  36.    Public ReadOnly Property RequestHeadersPostLogin As WebHeaderCollection
  37.        Get
  38.  
  39.            Dim headers As New WebHeaderCollection
  40.            With headers
  41.                .Add("Accept-Language", "en-us,en;q=0.5")
  42.                .Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
  43.                .Add("Keep-Alive", "99999")
  44.            End With
  45.            Return headers
  46.  
  47.        End Get
  48.    End Property
  49.  
  50.    ''' <summary>
  51.    ''' Determines whether the user is logged in the site.
  52.    ''' </summary>
  53.    Private isLogged As Boolean
  54.  
  55.    ''' <summary>
  56.    ''' Gets the cookie container.
  57.    ''' </summary>
  58.    ''' <value>The cookie container.</value>
  59.    Public ReadOnly Property CookieCollection As CookieCollection
  60.        Get
  61.            Return Me.cookieCollection1
  62.        End Get
  63.    End Property
  64.    ''' <summary>
  65.    ''' The cookie container.
  66.    ''' </summary>
  67.    Private cookieCollection1 As CookieCollection
  68.  
  69.    ''' <summary>
  70.    ''' Defines the query data for a LoginPost request.
  71.    ''' </summary>
  72.    Private NotInheritable Class LoginQueryData
  73.  
  74.        ''' <summary>
  75.        ''' Gets the Usuario field.
  76.        ''' </summary>
  77.        ''' <value>The Usuario field.</value>
  78.        Public Property Usuario As String
  79.  
  80.        ''' <summary>
  81.        ''' Gets or sets the Conteasena field.
  82.        ''' </summary>
  83.        ''' <value>The Conteasena field.</value>
  84.        Public Property Contrasena As String
  85.  
  86.    End Class
  87.  
  88.    ''' <summary>
  89.    ''' Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.
  90.    ''' </summary>
  91.    ''' <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param>
  92.    ''' <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns>
  93.    Private Function GetLoginQueryString(ByVal loginQueryData As LoginQueryData) As String
  94.  
  95.        Return String.Format(Me.UrlLoginQueryFormat,
  96.                             loginQueryData.Usuario,
  97.                             loginQueryData.Contrasena)
  98.  
  99.    End Function
  100.  
  101.    ''' <summary>
  102.    ''' Sets the cookie container.
  103.    ''' </summary>
  104.    ''' <param name="url">The url.</param>
  105.    ''' <param name="cookieCollection">The cookie collection.</param>
  106.    ''' <returns>CookieContainer.</returns>
  107.    Private Function SetCookieContainer(ByVal url As String,
  108.                                        ByVal cookieCollection As CookieCollection) As CookieContainer
  109.  
  110.        Dim cookieContainer As New CookieContainer
  111.        Dim refDate As Date
  112.  
  113.        For Each oldCookie As Cookie In cookieCollection
  114.  
  115.            If Not DateTime.TryParse(oldCookie.Value, refDate) Then
  116.  
  117.                Dim newCookie As New Cookie
  118.                With newCookie
  119.                    .Name = oldCookie.Name
  120.                    .Value = oldCookie.Value
  121.                    .Domain = New Uri(url).Host
  122.                    .Secure = False
  123.                End With
  124.  
  125.                cookieContainer.Add(newCookie)
  126.  
  127.            End If
  128.  
  129.        Next oldCookie
  130.  
  131.        Return cookieContainer
  132.  
  133.    End Function
  134.  
  135.    ''' <summary>
  136.    ''' Converts cookie string to global cookie collection object.
  137.    ''' </summary>
  138.    ''' <param name="cookie">The cookie string.</param>
  139.    ''' <param name="cookieCollection">The cookie collection.</param>
  140.    Private Sub SaveCookies(ByVal cookie As String,
  141.                            ByRef cookieCollection As CookieCollection)
  142.  
  143.        Dim cookieStrings() As String = cookie.Trim.
  144.                                               Replace("path=/,", String.Empty).
  145.                                               Replace("path=/", String.Empty).
  146.                                               Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
  147.  
  148.        cookieCollection = New CookieCollection
  149.  
  150.        For Each cookieString As String In cookieStrings
  151.  
  152.            If Not String.IsNullOrEmpty(cookieString.Trim) Then
  153.  
  154.                cookieCollection.Add(New Cookie(name:=cookieString.Trim.Split("="c)(0),
  155.                                                value:=cookieString.Trim.Split("="c)(1)))
  156.  
  157.            End If
  158.  
  159.        Next cookieString
  160.  
  161.    End Sub
  162.  
  163.    ''' <summary>
  164.    ''' Convert cookie container object to global cookie collection object.
  165.    ''' </summary>
  166.    ''' <param name="cookieContainer">The cookie container.</param>
  167.    ''' <param name="cookieCollection">The cookie collection.</param>
  168.    ''' <param name="url">The url.</param>
  169.    Private Sub SaveCookies(ByVal cookieContainer As CookieContainer,
  170.                            ByRef cookieCollection As CookieCollection,
  171.                            ByVal url As String)
  172.  
  173.        cookieCollection = New CookieCollection
  174.  
  175.        For Each cookie As Cookie In cookieContainer.GetCookies(New Uri(url))
  176.  
  177.            cookieCollection.Add(cookie)
  178.  
  179.        Next cookie
  180.  
  181.    End Sub
  182.  
  183.    ''' <param name="url">The url.</param>
  184.    ''' <param name="cookieCollection">The cookie collection.</param>
  185.    ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  186.    Private Function GetMethod(ByVal url As String,
  187.                               ByRef cookieCollection As CookieCollection) As Boolean
  188.  
  189.        Debug.WriteLine("[+] GetMethod function started.")
  190.  
  191.        Dim request As HttpWebRequest = Nothing
  192.        Dim response As HttpWebResponse = Nothing
  193.        Dim sr As StreamReader = Nothing
  194.        Dim result As Boolean = False
  195.  
  196.        Try
  197.            Debug.WriteLine("[+] Attempting to perform a request with:")
  198.            Debug.WriteLine(String.Format("Method: {0}", "GET"))
  199.            Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin)))
  200.  
  201.            request = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
  202.            With request
  203.                .Method = "GET"
  204.                .Headers = Me.RequestHeadersPostLogin
  205.                .Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
  206.                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
  207.                .AllowAutoRedirect = False
  208.                .KeepAlive = True
  209.            End With
  210.            Debug.WriteLine("[-] Request done.")
  211.  
  212.            ' Get the server response.
  213.            Debug.WriteLine("[+] Getting server response...")
  214.            response = DirectCast(request.GetResponse, HttpWebResponse)
  215.            Debug.WriteLine("[-] Getting server response done.")
  216.  
  217.            If request.HaveResponse Then
  218.  
  219.                ' Save the cookie info.
  220.                Debug.WriteLine("[+] Saving cookies...")
  221.                Me.SaveCookies(response.Headers("Set-Cookie"), cookieCollection)
  222.                Debug.WriteLine("[-] Saving cookies done.")
  223.  
  224.                ' Get the server response.
  225.                Debug.WriteLine("[+] Getting server response...")
  226.                response = DirectCast(request.GetResponse, HttpWebResponse)
  227.                Debug.WriteLine("[-] Getting server response done.")
  228.  
  229.                Debug.WriteLine("[+] Reading server response...")
  230.                sr = New StreamReader(response.GetResponseStream)
  231.                Using sr
  232.                    ' Read the response from the server, but we do not save it.
  233.                    sr.ReadToEnd()
  234.                End Using
  235.                result = True
  236.                Debug.WriteLine("[-] Reading server response done.")
  237.  
  238.            Else ' No response received from server.
  239.                Throw New Exception(String.Format("No response received from server with url: {0}", url))
  240.                result = False
  241.  
  242.            End If
  243.  
  244.        Catch ex As Exception
  245.            Throw
  246.            result = False
  247.  
  248.        Finally
  249.            If sr IsNot Nothing Then
  250.                sr.Dispose()
  251.            End If
  252.            If response IsNot Nothing Then
  253.                response.Close()
  254.            End If
  255.  
  256.        End Try
  257.  
  258.        Debug.WriteLine("[-] GetMethod function finished.")
  259.        Debug.WriteLine("[i] Returning result value...")
  260.        Return result
  261.  
  262.    End Function
  263.  
  264.    ''' <param name="loginData">The login post data.</param>
  265.    ''' <param name="cookieCollection">The cookie collection.</param>
  266.    ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  267.    Private Function PostLoginMethod(ByVal loginData As LoginQueryData,
  268.                                     ByRef cookieCollection As CookieCollection) As Boolean
  269.  
  270.        Debug.WriteLine("[+] PostLoginMethod function started.")
  271.  
  272.        Dim request As HttpWebRequest = Nothing
  273.        Dim response As HttpWebResponse = Nothing
  274.        Dim sw As StreamWriter = Nothing
  275.        Dim initialCookieCount As Integer = 0
  276.        Dim postData As String
  277.        Dim result As Boolean = False
  278.  
  279.        Try
  280.            Debug.WriteLine("[+] Attempting to perform a login request with:")
  281.            Debug.WriteLine(String.Format("Method: {0}", "POST"))
  282.            Debug.WriteLine(String.Format("Referer: {0}", Me.UrlMain))
  283.            Debug.WriteLine(String.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"))
  284.            Debug.WriteLine(String.Format("ContentType: {0}", "application/x-www-form-urlencoded"))
  285.            Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin)))
  286.  
  287.            request = DirectCast(HttpWebRequest.Create(Me.UrlLogin), HttpWebRequest)
  288.            With request
  289.                .Method = "POST"
  290.                .Headers = Me.RequestHeadersPostLogin
  291.                .Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  292.                .ContentType = "application/x-www-form-urlencoded"
  293.                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
  294.                .Referer = Me.UrlMain
  295.            End With
  296.            Debug.WriteLine("[-] Request done.")
  297.  
  298.            Debug.WriteLine("[+] Passing request cookie info...")
  299.            If cookieCollection IsNot Nothing Then ' Pass cookie info from the login page.
  300.                request.CookieContainer = Me.SetCookieContainer(Me.UrlLogin, cookieCollection)
  301.            End If
  302.            Debug.WriteLine("[-] Passing request cookie info done.")
  303.  
  304.            ' Set the post data.
  305.            Debug.WriteLine("[+] Setting post data with:")
  306.            Debug.WriteLine(String.Format("Usuario: {0}", loginData.Usuario))
  307.            Debug.WriteLine(String.Format("Contrasena: {0}", loginData.Contrasena))
  308.            postData = Me.GetLoginQueryString(loginData)
  309.  
  310.            sw = New StreamWriter(request.GetRequestStream)
  311.            Using sw
  312.                sw.Write(postData) ' Post the data to the server.
  313.            End Using
  314.            Debug.WriteLine("[-] Setting post data done.")
  315.  
  316.            ' Get the server response.
  317.            Debug.WriteLine("[+] Getting server response...")
  318.            initialCookieCount = request.CookieContainer.Count
  319.            response = DirectCast(request.GetResponse, HttpWebResponse)
  320.            Debug.WriteLine("[-] Getting server response done.")
  321.  
  322.            If request.CookieContainer.Count > initialCookieCount Then ' Login successful.
  323.                result = True
  324.  
  325.            Else ' Login unsuccessful.
  326.                result = False
  327.  
  328.            End If
  329.  
  330.            Debug.WriteLine(String.Format("[i] Login response result is: {0}",
  331.                                          If(result, "Successful (True)",
  332.                                                     "Unsuccessful (False)")))
  333.  
  334.            If result Then ' Save new login cookies.
  335.                Debug.WriteLine("[+] Saving new login cookies...")
  336.                Me.SaveCookies(request.CookieContainer, cookieCollection, Me.UrlMain)
  337.                Debug.WriteLine("[-] Saving new login cookies done.")
  338.            End If
  339.  
  340.        Catch ex As Exception
  341.            Throw
  342.  
  343.        Finally
  344.            If sw IsNot Nothing Then
  345.                sw.Dispose()
  346.            End If
  347.            If response IsNot Nothing Then
  348.                response.Close()
  349.            End If
  350.  
  351.        End Try
  352.  
  353.        Debug.WriteLine("[-] PostLoginMethod function finished.")
  354.        Debug.WriteLine("[i] Returning result value...")
  355.        Me.isLogged = result
  356.        Return result
  357.  
  358.    End Function
  359.  
  360.    ''' <summary>
  361.    ''' Determines whether the account can log in CGWallpapers site.
  362.    ''' </summary>
  363.    ''' <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns>
  364.    Public Function CheckLogin(ByVal username As String,
  365.                               ByVal password As String) As Boolean
  366.  
  367.        If Me.GetMethod(Me.UrlMain, Me.cookieCollection1) Then
  368.  
  369.            Dim loginQueryData As New LoginQueryData With
  370.                  {
  371.                      .Usuario = HttpUtility.UrlEncode(username),
  372.                      .Contrasena = HttpUtility.UrlEncode(password)
  373.                  }
  374.            Return Me.PostLoginMethod(loginQueryData, Me.cookieCollection1)
  375.  
  376.        Else
  377.            Return False
  378.  
  379.        End If ' Me.GetMethod
  380.  
  381.    End Function
  382.  

Traducción online a C# (sin testear):
Código
  1. /// <summary>
  2. /// Gets the main url.
  3. /// </summary>
  4. /// <value>The main url.</value>
  5. public string UrlMain {
  6. get { return "http://www.cgwallpapers.com/"; }
  7. }
  8.  
  9. /// <summary>
  10. /// Gets the login url.
  11. /// </summary>
  12. /// <value>The login url.</value>
  13. public string UrlLogin {
  14. get { return "http://www.cgwallpapers.com/login.php"; }
  15. }
  16.  
  17. /// <summary>
  18. /// Gets the login query string format.
  19. /// </summary>
  20. /// <value>The login query string format.</value>
  21. public string UrlLoginQueryFormat {
  22. get { return "usuario={0}&contrasena={1}"; }
  23. }
  24.  
  25. /// <summary>
  26. /// Gets the headers for a Login POST request.
  27. /// </summary>
  28. /// <value>The headers for a Login POST request.</value>
  29. public WebHeaderCollection RequestHeadersPostLogin {
  30.  
  31. get {
  32. WebHeaderCollection headers = new WebHeaderCollection();
  33. var _with1 = headers;
  34. _with1.Add("Accept-Language", "en-us,en;q=0.5");
  35. _with1.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  36. _with1.Add("Keep-Alive", "99999");
  37. return headers;
  38.  
  39. }
  40. }
  41.  
  42. /// <summary>
  43. /// Determines whether the user is logged in the site.
  44. /// </summary>
  45.  
  46. private bool isLogged;
  47. /// <summary>
  48. /// Gets the cookie container.
  49. /// </summary>
  50. /// <value>The cookie container.</value>
  51. public CookieCollection CookieCollection {
  52. get { return this.cookieCollection1; }
  53. }
  54. /// <summary>
  55. /// The cookie container.
  56. /// </summary>
  57.  
  58. private CookieCollection cookieCollection1;
  59. /// <summary>
  60. /// Defines the query data for a LoginPost request.
  61. /// </summary>
  62. private sealed class LoginQueryData
  63. {
  64.  
  65. /// <summary>
  66. /// Gets the Usuario field.
  67. /// </summary>
  68. /// <value>The Usuario field.</value>
  69. public string Usuario { get; set; }
  70.  
  71. /// <summary>
  72. /// Gets or sets the Conteasena field.
  73. /// </summary>
  74. /// <value>The Conteasena field.</value>
  75. public string Contrasena { get; set; }
  76.  
  77. }
  78.  
  79. /// <summary>
  80. /// Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.
  81. /// </summary>
  82. /// <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param>
  83. /// <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns>
  84. private string GetLoginQueryString(LoginQueryData loginQueryData)
  85. {
  86.  
  87. return string.Format(this.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena);
  88.  
  89. }
  90.  
  91. /// <summary>
  92. /// Sets the cookie container.
  93. /// </summary>
  94. /// <param name="url">The url.</param>
  95. /// <param name="cookieCollection">The cookie collection.</param>
  96. /// <returns>CookieContainer.</returns>
  97. private CookieContainer SetCookieContainer(string url, CookieCollection cookieCollection)
  98. {
  99.  
  100. CookieContainer cookieContainer = new CookieContainer();
  101. System.DateTime refDate = default(System.DateTime);
  102.  
  103.  
  104. foreach (Cookie oldCookie in cookieCollection) {
  105.  
  106. if (!DateTime.TryParse(oldCookie.Value, refDate)) {
  107. Cookie newCookie = new Cookie();
  108. var _with2 = newCookie;
  109. _with2.Name = oldCookie.Name;
  110. _with2.Value = oldCookie.Value;
  111. _with2.Domain = new Uri(url).Host;
  112. _with2.Secure = false;
  113.  
  114. cookieContainer.Add(newCookie);
  115.  
  116. }
  117.  
  118. }
  119.  
  120. return cookieContainer;
  121.  
  122. }
  123.  
  124. /// <summary>
  125. /// Converts cookie string to global cookie collection object.
  126. /// </summary>
  127. /// <param name="cookie">The cookie string.</param>
  128. /// <param name="cookieCollection">The cookie collection.</param>
  129.  
  130. private void SaveCookies(string cookie, ref CookieCollection cookieCollection)
  131. {
  132. string[] cookieStrings = cookie.Trim.Replace("path=/,", string.Empty).Replace("path=/", string.Empty).Split({ ';' }, StringSplitOptions.RemoveEmptyEntries);
  133.  
  134. cookieCollection = new CookieCollection();
  135.  
  136.  
  137. foreach (string cookieString in cookieStrings) {
  138.  
  139. if (!string.IsNullOrEmpty(cookieString.Trim)) {
  140. cookieCollection.Add(new Cookie(name: cookieString.Trim.Split('=')(0), value: cookieString.Trim.Split('=')(1)));
  141.  
  142. }
  143.  
  144. }
  145.  
  146. }
  147.  
  148. /// <summary>
  149. /// Convert cookie container object to global cookie collection object.
  150. /// </summary>
  151. /// <param name="cookieContainer">The cookie container.</param>
  152. /// <param name="cookieCollection">The cookie collection.</param>
  153. /// <param name="url">The url.</param>
  154.  
  155. private void SaveCookies(CookieContainer cookieContainer, ref CookieCollection cookieCollection, string url)
  156. {
  157. cookieCollection = new CookieCollection();
  158.  
  159.  
  160. foreach (Cookie cookie in cookieContainer.GetCookies(new Uri(url))) {
  161. cookieCollection.Add(cookie);
  162.  
  163. }
  164.  
  165. }
  166.  
  167. /// <param name="url">The url.</param>
  168. /// <param name="cookieCollection">The cookie collection.</param>
  169. /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  170. private bool GetMethod(string url, ref CookieCollection cookieCollection)
  171. {
  172.  
  173. Debug.WriteLine("[+] GetMethod function started.");
  174.  
  175. HttpWebRequest request = null;
  176. HttpWebResponse response = null;
  177. StreamReader sr = null;
  178. bool result = false;
  179.  
  180. try {
  181. Debug.WriteLine("[+] Attempting to perform a request with:");
  182. Debug.WriteLine(string.Format("Method: {0}", "GET"));
  183. Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin)));
  184.  
  185. request = (HttpWebRequest)HttpWebRequest.Create(url);
  186. var _with3 = request;
  187. _with3.Method = "GET";
  188. _with3.Headers = this.RequestHeadersPostLogin;
  189. _with3.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  190. _with3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
  191. _with3.AllowAutoRedirect = false;
  192. _with3.KeepAlive = true;
  193. Debug.WriteLine("[-] Request done.");
  194.  
  195. // Get the server response.
  196. Debug.WriteLine("[+] Getting server response...");
  197. response = (HttpWebResponse)request.GetResponse;
  198. Debug.WriteLine("[-] Getting server response done.");
  199.  
  200.  
  201. if (request.HaveResponse) {
  202. // Save the cookie info.
  203. Debug.WriteLine("[+] Saving cookies...");
  204. this.SaveCookies(response.Headers("Set-Cookie"), ref cookieCollection);
  205. Debug.WriteLine("[-] Saving cookies done.");
  206.  
  207. // Get the server response.
  208. Debug.WriteLine("[+] Getting server response...");
  209. response = (HttpWebResponse)request.GetResponse;
  210. Debug.WriteLine("[-] Getting server response done.");
  211.  
  212. Debug.WriteLine("[+] Reading server response...");
  213. sr = new StreamReader(response.GetResponseStream);
  214. using (sr) {
  215. // Read the response from the server, but we do not save it.
  216. sr.ReadToEnd();
  217. }
  218. result = true;
  219. Debug.WriteLine("[-] Reading server response done.");
  220.  
  221. // No response received from server.
  222. } else {
  223. throw new Exception(string.Format("No response received from server with url: {0}", url));
  224. result = false;
  225.  
  226. }
  227.  
  228. } catch (Exception ex) {
  229. throw;
  230. result = false;
  231.  
  232. } finally {
  233. if (sr != null) {
  234. sr.Dispose();
  235. }
  236. if (response != null) {
  237. response.Close();
  238. }
  239.  
  240. }
  241.  
  242. Debug.WriteLine("[-] GetMethod function finished.");
  243. Debug.WriteLine("[i] Returning result value...");
  244. return result;
  245.  
  246. }
  247.  
  248. /// <param name="loginData">The login post data.</param>
  249. /// <param name="cookieCollection">The cookie collection.</param>
  250. /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  251. private bool PostLoginMethod(LoginQueryData loginData, ref CookieCollection cookieCollection)
  252. {
  253.  
  254. Debug.WriteLine("[+] PostLoginMethod function started.");
  255.  
  256. HttpWebRequest request = null;
  257. HttpWebResponse response = null;
  258. StreamWriter sw = null;
  259. int initialCookieCount = 0;
  260. string postData = null;
  261. bool result = false;
  262.  
  263. try {
  264. Debug.WriteLine("[+] Attempting to perform a login request with:");
  265. Debug.WriteLine(string.Format("Method: {0}", "POST"));
  266. Debug.WriteLine(string.Format("Referer: {0}", this.UrlMain));
  267. Debug.WriteLine(string.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
  268. Debug.WriteLine(string.Format("ContentType: {0}", "application/x-www-form-urlencoded"));
  269. Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin)));
  270.  
  271. request = (HttpWebRequest)HttpWebRequest.Create(this.UrlLogin);
  272. var _with4 = request;
  273. _with4.Method = "POST";
  274. _with4.Headers = this.RequestHeadersPostLogin;
  275. _with4.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  276. _with4.ContentType = "application/x-www-form-urlencoded";
  277. _with4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
  278. _with4.Referer = this.UrlMain;
  279. Debug.WriteLine("[-] Request done.");
  280.  
  281. Debug.WriteLine("[+] Passing request cookie info...");
  282. // Pass cookie info from the login page.
  283. if (cookieCollection != null) {
  284. request.CookieContainer = this.SetCookieContainer(this.UrlLogin, cookieCollection);
  285. }
  286. Debug.WriteLine("[-] Passing request cookie info done.");
  287.  
  288. // Set the post data.
  289. Debug.WriteLine("[+] Setting post data with:");
  290. Debug.WriteLine(string.Format("Usuario: {0}", loginData.Usuario));
  291. Debug.WriteLine(string.Format("Contrasena: {0}", loginData.Contrasena));
  292. postData = this.GetLoginQueryString(loginData);
  293.  
  294. sw = new StreamWriter(request.GetRequestStream);
  295. using (sw) {
  296. sw.Write(postData);
  297. // Post the data to the server.
  298. }
  299. Debug.WriteLine("[-] Setting post data done.");
  300.  
  301. // Get the server response.
  302. Debug.WriteLine("[+] Getting server response...");
  303. initialCookieCount = request.CookieContainer.Count;
  304. response = (HttpWebResponse)request.GetResponse;
  305. Debug.WriteLine("[-] Getting server response done.");
  306.  
  307. // Login successful.
  308. if (request.CookieContainer.Count > initialCookieCount) {
  309. result = true;
  310.  
  311. // Login unsuccessful.
  312. } else {
  313. result = false;
  314.  
  315. }
  316.  
  317. Debug.WriteLine(string.Format("[i] Login response result is: {0}", result ? "Successful (True)" : "Unsuccessful (False)"));
  318.  
  319. // Save new login cookies.
  320. if (result) {
  321. Debug.WriteLine("[+] Saving new login cookies...");
  322. this.SaveCookies(request.CookieContainer, ref cookieCollection, this.UrlMain);
  323. Debug.WriteLine("[-] Saving new login cookies done.");
  324. }
  325.  
  326. } catch (Exception ex) {
  327. throw;
  328.  
  329. } finally {
  330. if (sw != null) {
  331. sw.Dispose();
  332. }
  333. if (response != null) {
  334. response.Close();
  335. }
  336.  
  337. }
  338.  
  339. Debug.WriteLine("[-] PostLoginMethod function finished.");
  340. Debug.WriteLine("[i] Returning result value...");
  341. this.isLogged = result;
  342. return result;
  343.  
  344. }
  345.  
  346.  
  347. /// <summary>
  348. /// Determines whether the account can log in CGWallpapers site.
  349. /// </summary>
  350. /// <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns>
  351. public bool CheckLogin(string username, string password)
  352. {
  353.  
  354.  
  355. if (this.GetMethod(this.UrlMain, this.cookieCollection1)) {
  356. LoginQueryData loginQueryData = new LoginQueryData {
  357. Usuario = HttpUtility.UrlEncode(username),
  358. Contrasena = HttpUtility.UrlEncode(password)
  359. };
  360. return this.PostLoginMethod(loginQueryData, this.cookieCollection1);
  361.  
  362. } else {
  363. return false;
  364.  
  365. }
  366. // Me.GetMethod
  367.  
  368. }
  369.  
  370. //=======================================================
  371. //Service provided by Telerik (www.telerik.com)
  372. //=======================================================


En línea

Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
Re: Fallo al iniciar sesion
« Respuesta #2 en: 31 Marzo 2015, 20:22 pm »

Hola elektro gracias por la respuesta, las variables si que estan codificadas:

Código
  1. string postData = "usuario=" + usuario + "&contrasena=" + contraseña + "&submit=Login";
  2.            byte[] byteData = ASCIIEncoding.ASCII.GetBytes(postData);

He mirado con wireshark lo que mando y parece estar todo correcto el tamaño de cadena, todo.

Funciona bien pero sigo sin saber porque no logea, porque no me devuelve esa página una vez iniciada la sesión.

Saludos.
En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: Fallo al iniciar sesion
« Respuesta #3 en: 31 Marzo 2015, 21:08 pm »

las variables si que estan codificadas:

Código
  1. string postData = "usuario=" + usuario + "&contrasena=" + contraseña + "&submit=Login";
  2.            byte[] byteData = ASCIIEncoding.ASCII.GetBytes(postData);

Por codificar me refiero a la codificación html, no a codificar el string en una secuencia de bytes cómo estás haciendo.

Si el usuario/contraseña contiene por ejemplo un espacio entonces vas a codificar 1 byte " " en lugar de codificar los caracteres "%20", ¿me entiendes?.

Porfavor, aclara si el usuario/contraseña contienen espacios u otros caracteres ilegales para descartar que ese sea el problema,
si tienes dudas vuelve a leer la pregunta nº1 que hice en el comentario anterior donde mostré un ejemplo de cómo codificar el string (primero codificas el usuario/contraseña a html, y luego generas los bytes cómo estabas haciendo, pero con el usuario/contraseña codificados a html).

Saludos!
« Última modificación: 31 Marzo 2015, 21:11 pm por Eleкtro » En línea

Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
Re: Fallo al iniciar sesion
« Respuesta #4 en: 31 Marzo 2015, 22:53 pm »

Hola socio no creo que sea problema, la cadena que mando en el POST detectada por el wireshark es la siguiente:

usuario=ASJDIAJI&contrasena=AKJDFIAJIFJ&submit=Login

Son solo mayúsculas ni espacios ni carácteres extraños, no creo que radique ahí el problema, pero se puede investigar más.

Gracias y un saludo.
En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
kub0x
Enlightenment Seeker
Moderador
***
Desconectado Desconectado

Mensajes: 1.486


S3C M4NI4C


Ver Perfil
Re: Fallo al iniciar sesion
« Respuesta #5 en: 1 Abril 2015, 03:19 am »

Muy buenas he visto que estabas en apuros y esto ya lo discutimos hace un tiempo. Ese code en C# me suena ;) jejej

Edito: Aporto mas informacion, el servidor me devuelve la pagina del index.

¿Quieres decir que cuando introduces el user/passwd correcto te lleva al index? Yo lo que suelo hacer para construir peticiones HTTP es analizarlas primero con un FireBug en Firefox para determinar las cabeceras de la solicitud y POST (en este caso, pero lo mismo con GET). Dale una oportunidad y nos cuentas. Cuanta mas info nos des mejor.

Fíjate que el header "Host" no lo tienes seteado a la web que lanzas el POST. Quizá lo quisiste poner así en este post, pero lo remarco por si acaso.

Código
  1. req.Host = "www.web.com"


Saludos.
En línea

Viejos siempre viejos,
Ellos tienen el poder,
Y la juventud,
¡En el ataúd! Criaturas Al poder.

Visita mi perfil en ResearchGate

Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
Re: Fallo al iniciar sesion
« Respuesta #6 en: 1 Abril 2015, 14:45 pm »

Claro! Es correcto en vez de web pone el nombre de dominio de la página. Precioso code por cierto :) en el FORM pone que es método POST, no sé el problema es ese que me vuelve al index como si no he hecho nada, cuando los datos son correctos y no se usar firebug a ese nivel xP, soy mas de live HTTP HEADERS y copiar la cabecera de inicio de sesión que en este caso no funciona para mi programa xp.

Haber como va :P gracias.
En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Iniciar Sesion
PHP
::: Devil ::: 1 1,712 Último mensaje 29 Mayo 2014, 22:19 pm
por Mokonauta
Iniciar sesion en web con C# « 1 2 »
.NET (C#, VB.NET, ASP)
Kaxperday 19 13,810 Último mensaje 5 Diciembre 2014, 20:01 pm
por Kaxperday
RESUELTO <- Fallo al validar la sesión
Sugerencias y dudas sobre el Foro
MadBad 2 7,004 Último mensaje 14 Junio 2017, 16:59 pm
por MadBad
Fallo al iniciar mon0
Hacking Wireless
e 5 4,343 Último mensaje 10 Abril 2018, 01:28 am
por El_Andaluz
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines