Пример #1
0
        public List<PageItem> Process(int Flags, byte[] RecordData)
        {
            MemoryStream _ms = null;
            BinaryReader _br = null;
            try
            {
                _ms = new MemoryStream(RecordData);
                _br = new BinaryReader(_ms);

                Byte[] PrivateData = _br.ReadBytes(RecordData.Length);
                //Ok we should have our private data which I am storing my tooltip value in...
                //now lets interpret it...            
                string PData = new System.Text.ASCIIEncoding().GetString(PrivateData);
                //If string starts with "ToolTip" then lets do something with it.. otherwise I don't care about it.
                if (PData.StartsWith("ToolTip"))
                {
                    PageRectangle pr = new PageRectangle();
                    StyleInfo si = new StyleInfo();
                    pr.SI = si;
                    //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn
                    string[] ttd = PData.Split('|');
                    pr.Tooltip = ttd[0].Split(':')[1];
                    pr.X = X + Single.Parse(ttd[1].Split(':')[1]) * SCALEFACTOR;
                    pr.Y = Y + Single.Parse(ttd[2].Split(':')[1]) * SCALEFACTOR;
                    pr.W = Single.Parse(ttd[3].Split(':')[1]) * SCALEFACTOR;
                    pr.H = Single.Parse(ttd[4].Split(':')[1]) * SCALEFACTOR;
                    items.Add(pr);
                }
                else if (PData.StartsWith("PolyToolTip"))
                {
                    PagePolygon pp = new PagePolygon();
                    StyleInfo si = new StyleInfo();
                    pp.SI = si;
                    //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn
                    string[] ttd = PData.Split('|');
                    PointF[] pts = new PointF[(ttd.Length - 1) / 2];
                    pp.Points = pts;
                    pp.Tooltip = ttd[0].Split(':')[1];
                    for (int i = 0; i < pts.Length; i++)
                    {
                        pts[i].X = X + Single.Parse(ttd[i*2 +1]) * SCALEFACTOR;
                        pts[i].Y = Y + Single.Parse(ttd[i*2 +2]) * SCALEFACTOR;
                    }
                    items.Add(pp);
                }
                return items;
            }

            finally
            {
                if (_br != null)
                    _br.Close();
                if (_ms != null)
                    _ms.Dispose();

            }
        }
Пример #2
0
        public ServiceI()
        {
            string
                                   configUsername = ConfigurationManager.AppSettings["username"],
                                   configPassword = ConfigurationManager.AppSettings["password"];

            if (!string.IsNullOrEmpty(configUsername))
            {
                string
                    requestUsername,
                    requestPassword;

                try
                {
                    string
                        userAndPassEncoded = this.Context.Request.Headers["Authorization"].Substring(6),
                        userAndPassDecoded = new System.Text.ASCIIEncoding().GetString(Convert.FromBase64String(userAndPassEncoded));

                    string[]
                    userAndPasswordArray = userAndPassDecoded.Split(':');

                    requestUsername = userAndPasswordArray[0];
                    requestPassword = userAndPasswordArray[1];
                }
                catch (Exception eException)
                {
                    throw new ApplicationException("Unable to get the Basic Authentication credentials from the request", eException);
                }

                if (configUsername != requestUsername || configPassword != requestPassword)
                {
                    throw new ApplicationException("You are not authorized to access this web service");
                }
            }
        }
Пример #3
0
        // First method OnAuthenticateRequest, that implements authentication logic step 1
        /*
        ####################################################################
        # OnAuthenticateRequest
        #
        #
        #
        ####################################################################
        */
        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;

            // then follow authentication logic
            // get Http header "Authorization"
            // check if not empty

            string authorization = app.Request.Headers["Authorization"];
            if ((authorization == null) || (authorization.Length == 0))
            {
                //AccessDenied(app);
                return;
            }

            // check if Http header has the syntax of basic
            authorization = authorization.Trim();
            if (!authorization.StartsWith("Basic"))
            {
                // *** Not validating
                return;
            }

            // cut the word "basic" and decode from base64
            // get "username:password"

            byte[] tempConverted = Convert.FromBase64String(authorization.Substring(6));
            string userInfo = new ASCIIEncoding().GetString(tempConverted);

            // get "username"
            // get "password"

            string[] usernamePassword = userInfo.Split(new char[] { ':' });
            string username = usernamePassword[0];
            string password = usernamePassword[1];

            // compare username, password against the values, stored in the database
            // if everything is fine, get user group list from the database
            // and create an instance of GenericPrincipal

            if (AuthenticateUser(username, password))
            {
                app.Context.User = new GenericPrincipal(new GenericIdentity(username,
                    "Custom Basic Authentication"), null);
            }

                // else, AccessDenied

            else
            {
                AccessDenied(app);
            }
        }
        public void OnAuthenticateRequest2(
			  object source
			, EventArgs eventArgs
			)
        {
            HttpApplication app = (HttpApplication)source;

            string authHeader = app.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    return;
                }

                authStr = authStr.Trim();

                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes =
                Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string username = userPass[0];
                string password = userPass[1];

                if ( ! Validate(username, password))
                {
                    DenyAccess(app);
                    return;
                }
            }
            else
            {
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }
Пример #5
0
        public static string GetIdentityName(RequestContext requestContext)
        {
            string sUserName   = requestContext.HttpContext.User.Identity.Name;
            bool   isBasicAuth = requestContext.HttpContext.Request.Headers["Authorization"] != null && requestContext.HttpContext.Request.Headers["Authorization"].StartsWith("Basic");

            if ((isBasicAuth))
            {
                string   encodedHeader = requestContext.HttpContext.Request.Headers["Authorization"].Substring(6);
                string   decodedHeader = new System.Text.ASCIIEncoding().GetString(Convert.FromBase64String(encodedHeader));
                string[] detail        = decodedHeader.Split(Convert.ToChar(":"));
                sUserName = detail[0];
            }
            else
            {
                sUserName = requestContext.HttpContext.User.Identity.Name;
            }
            return(sUserName);
        }
        public bool Authorize(HttpContextBase context)
        {
            if (!SecurityContext.IsAuthenticated)
            {
                try
                {
                    //Try basic
                    var authorization = context.Request.Headers["Authorization"];
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return false;
                    }
                    authorization = authorization.Trim();
                    if (authorization.IndexOf(',')!=-1)
                      authorization = authorization.Substring(0, authorization.IndexOf(',')).Trim();

                    if (authorization.IndexOf("Basic", 0) != 0)
                    {
                        return false;
                    }

                    // cut the word "basic" and decode from base64
                    // get "username:password"
                    var tempConverted = Convert.FromBase64String(authorization.Substring(6));
                    var user = new ASCIIEncoding().GetString(tempConverted);

                    // get "username"
                    // get "password"
                    var usernamePassword = user.Split(new[] { ':' });
                    var username = usernamePassword[0];
                    var password = usernamePassword[1];
                    _log.Debug("Basic Authorizing {0}", username);
                    Authentificate(username, password);
                }
                catch (Exception)
                {
                    
                }

            }
            return SecurityContext.IsAuthenticated;
        }
Пример #7
0
        public static bool ProcessBasicAuthorization(HttpContext context, out string authCookie)
        {
            authCookie = null;
            try
            {
                //Try basic
                var authorization = context.Request.Headers["Authorization"];
                if (string.IsNullOrEmpty(authorization))
                {
                    return false;
                }
                authorization = authorization.Trim();
                if (authorization.IndexOf("Basic", 0) != 0)
                {
                    return false;
                }

                // cut the word "basic" and decode from base64
                // get "username:password"
                var tempConverted = Convert.FromBase64String(authorization.Substring(6));
                var user = new ASCIIEncoding().GetString(tempConverted);

                // get "username"
                // get "password"
                var usernamePassword = user.Split(new[] { ':' });
                var username = usernamePassword[0];
                var password = usernamePassword[1];

                var userInfo = CoreContext.UserManager.GetUserByEmail(username);
                if (userInfo != null)
                {
                    authCookie = SecurityContext.AuthenticateMe(userInfo.ID.ToString(), password);
                }

            }
            catch (Exception) { }

            return SecurityContext.IsAuthenticated;
        }
Пример #8
0
            private void ProcessBasicAuthRequest()
            {
                string authStr = HttpContext.Current.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    DenyAccess();
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    // Don't understand this header...we'll pass it along and 
                    // assume someone else will handle it
                    DenyAccess();
                    return;
                }

                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string username = userPass[0];
                string password = userPass[1];

                UserInfo user = UserController.GetUserByUsernamePassword(
                                    username, password, System.Web.HttpContext.Current.Request.UserHostAddress);

                if (user == null)
                {
                    // Invalid credentials; deny access
                    DenyAccess();
                    return;

                    //throw new Exception("Wrong BASIC credentials have been supplied");
                }

                SecurityContext.SetThreadPrincipal(user);
            }
Пример #9
0
 private string[] GetMessage(NetworkStream stream)
 {
     byte[] numArray = new byte[4096];
       int count = stream.Read(numArray, 0, 4096);
       string str = new ASCIIEncoding().GetString(numArray, 0, count).Trim(new char[1]);
       Trace.Write(new LogInfo(LogType.Workflow, null, " --> " + str));
       return str.Split(new char[1]
       {
     '|'
       }, StringSplitOptions.None);
 }
    public static void Main()
    {
        Console.WriteLine("initializing server");

        UdpClient server = new UdpClient(8080);

        // an endpoint is not needed the data will be sent
        // to the port where the server is bound to
        IPEndPoint dummy = null;

        bool loop = true;

        while (loop)
        {
            Console.WriteLine("waiting for request...");

            byte[] datagram = server.Receive(ref dummy);

            // split request string into parts, part1=client IP address or
            // DNS name, part2=client port, part3=command
            string dg =
                new System.Text.ASCIIEncoding().GetString(datagram);
            string[] cmd = dg.Split(new Char[] { ':' });
            string   remoteClientHost = cmd[0];
            int      remoteClientPort = Int32.Parse(cmd[1]);
            string   command          = cmd[2];
            string   result           = null;

            Console.WriteLine("executing remote command:" + command);

            switch (command)
            {
            case "GET":
                result = "Hello World !";
                break;

            // finish communication
            case "EXIT":
                result = "BYE";
                loop   = false;
                break;

            // invalid command
            default:
                result = "ERROR";
                break;
            }

            if (result != null)
            {
                Console.WriteLine("sending result to (" + remoteClientHost + ":" + remoteClientPort + "): " + result);

                // convert data string to byte array
                Byte[] d = System.Text.Encoding.ASCII.GetBytes(result.ToCharArray());

                // send result to the client
                server.Send(d, d.Length, remoteClientHost, remoteClientPort);
            }
        }

        Console.WriteLine("clearing up server...");
        server.Close();

        Console.Write("press return to exit");
        Console.ReadLine();
    }
Пример #11
0
        // This the call back function which will be invoked when the socket
        // detects any client writing of data on the stream
        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);

                string incoming = szData.Substring(0, szData.Length - 1);

                if (incoming.StartsWith("/rsaC"))
                {
            #if _SHOWMSG
                    MessageBox.Show("RSA public key received");
            #endif

                    string rsaKey = incoming.Substring(5);
                    string[] fields = rsaKey.Split(' ');

                    clientInfo tempclient = new clientInfo();
                    tempclient.ip = fields[0];
                    tempclient.port = fields[1];
                    tempclient.publicKey = fields[2];

                    if(!clientsList.Contains(tempclient)) clientsList.Add(tempclient);

                }
                else if (incoming.StartsWith("/bck"))
                {
                    //client wants to back up
                    //decide which parties to connect
                    //pseudo connections list.
                    string[] backupreq = incoming.Substring(4).Split(' ');

                    //client req = new client();
                    int clientnum = -1;
                    for (int i = 0; i < clientsList.Count; i++)
                    {
                        if (clientsList[i].ip.Equals(backupreq[0]))
                        {
                            if (clientsList[i].port.Equals(backupreq[1]))
                            {
                                clientnum = i;
                            }
                        }
                    }
                    if (clientnum == -1) MessageBox.Show("Backup Request from unauthenticated user");
                    else
                    {
                        //req = clientsList[clientnum];

                        clientsList[clientnum].files[0].fileID = backupreq[2];
                        clientsList[clientnum].files[0].filesize = System.Convert.ToInt32(backupreq[3]);

                        //first part of every ticket is same
                        string ticketData = clientsList[clientnum].ip + " " + clientsList[clientnum].port + " " + clientsList[clientnum].publicKey;

                        // Create a UnicodeEncoder to convert between byte array and string.
                        ASCIIEncoding ByteConverter = new ASCIIEncoding();
                        byte[] originalData = ByteConverter.GetBytes(ticketData);
                        byte[] signedData;

                        signedData = rsa.SignData(originalData, new SHA1CryptoServiceProvider());

                        for (int i = 0; i < clientsList.Count; i++)
                        {
                            //Ticket i = E(PRas, IPa + PUa) || E(PRas, IPb + PUb)

                            if (i != clientnum)
                            {
                                //second part of the ticket
                                string ticketSecondData = clientsList[i].ip + " " + clientsList[i].port + " " + clientsList[i].publicKey;

                                // Create a UnicodeEncoder to convert between byte array and string.
                                byte[] originalSecondData = ByteConverter.GetBytes(ticketSecondData);
                                byte[] signedSecondData;

                                signedSecondData = rsa.SignData(originalSecondData, new SHA1CryptoServiceProvider());

                                clientsList[clientnum].files[0].filetickets.AddToList(originalData, signedData, originalSecondData, signedSecondData);

                            }
                        }

                        //sends them to the client
                        try
                        {
                            string functionID = "/tck";
                            string strTickets = clientsList[clientnum].files[0].filetickets.EncodeToString();

                            //TODO: somehow concatanate the message header; functionID
                            string TicketListMsg = functionID + strTickets; //tickets

                            byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(TicketListMsg);

                            if (m_workerSocket[clientnum] != null)
                            {
                                if (m_workerSocket[clientnum].Connected)
                                {
                                    m_workerSocket[clientnum].Send(byData2);
                                }
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }

                    }

                    //mytickets tickets = new mytickets();

                    //clients[] clientsList = new clients[5];
                    //for (int i = 0; i < 5; i++)
                    //{
                    //    clientsList[i].ip = i * 100;
                    //    clientsList[i].port = i * 1000;
                    //    clientsList[i].publicKey = (i * 10000).ToString();
                    //}

                }
                else if (incoming.StartsWith("/rcv"))
                {
                    //client wants to recover
                    //decide which parties to connect
                    //pseudo connections list.
                    string[] recoverreq = incoming.Substring(4).Split(' ');

                    //client req = new client();
                    int clientnum = -1;
                    int filenum = -1;
                    for (int i = 0; i < clientsList.Count; i++)
                    {
                        if (clientsList[i].ip.Equals(recoverreq[0]))
                        {
                            if (clientsList[i].port.Equals(recoverreq[1]))
                            {
                                for (int j = 0; j < MAX_FILE; j++)
                                {
                                    if (clientsList[i].files[j].fileID != null)
                                    {
                                        if (clientsList[i].files[j].fileID.Equals(recoverreq[2]))
                                        {
                                            clientnum = i;
                                            filenum = j;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (clientnum == -1) MessageBox.Show("User nor authenticated!");
                    else if (filenum == -1) MessageBox.Show("File not in database!");
                    else
                    {
                        //req = clientsList[clientnum];
                        mytickets RecoveryTickets = new mytickets();
                        bool enoughFound = false;
                        for (int i = 0; !enoughFound && i < clientsList[clientnum].files[filenum].filetickets.ticketlist.Count; i++)
                        {

                            string possibleStorage = new ASCIIEncoding().GetString(clientsList[clientnum].files[filenum].filetickets.ticketlist[i].origSecond);
                            string[] fields = possibleStorage.Split(' ');
                            string possibleStorageIP = fields[0];
                            string possibleStoragePort = fields[1];
                            for (int j = 0; j < m_clientCount; j++)
                            {
                                if (m_workerSocket[j] != null)
                                {
                                    if (m_workerSocket[j].Connected)
                                    {
                                        if (possibleStorageIP.Equals(clientsList[j].ip))
                                        {
                                            if (possibleStoragePort.Equals(clientsList[j].port))
                                            {
                                                RecoveryTickets.AddToList(clientsList[clientnum].files[filenum].filetickets.ticketlist[i]);
                                                if (RecoveryTickets.ticketlist.Count >= clientsList[clientnum].files[filenum].filetickets.ticketlist.Count - 1)
                                                    enoughFound = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //sends them to the client
                        try
                        {
                            string functionID = "/rectck";
                            string strTickets = RecoveryTickets.EncodeToString();

                            //TODO: somehow concatanate the message header; functionID
                            string TicketListMsg = functionID + strTickets; //tickets

                            byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(TicketListMsg);

                            if (m_workerSocket[clientnum] != null)
                            {
                                if (m_workerSocket[clientnum].Connected)
                                {
                                    m_workerSocket[clientnum].Send(byData2);
                                }
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }
                    }
                }
                else
                {
                    tb_encRecv.Enabled = true;
                    tb_encRecv.Text = BytesToHex(Convert.FromBase64String(szData.Substring(0, szData.Length - 1)));
                    string decryptedText = cryptor.DecryptMessage(szData.Substring(0, szData.Length - 1));
                    richTextBoxReceivedMsg.Text = decryptedText + "\n" + richTextBoxReceivedMsg.Text;

                }

                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
Пример #12
0
        public List <PageItem> Process(int Flags, byte[] RecordData)
        {
            MemoryStream _ms = null;
            BinaryReader _br = null;

            try
            {
                _ms = new MemoryStream(RecordData);
                _br = new BinaryReader(_ms);

                Byte[] PrivateData = _br.ReadBytes(RecordData.Length);
                //Ok we should have our private data which I am storing my tooltip value in...
                //now lets interpret it...
                string PData = new System.Text.ASCIIEncoding().GetString(PrivateData);
                //If string starts with "ToolTip" then lets do something with it.. otherwise I don't care about it.
                if (PData.StartsWith("ToolTip"))
                {
                    PageRectangle pr = new PageRectangle();
                    StyleInfo     si = new StyleInfo();
                    pr.SI = si;
                    //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn
                    string[] ttd = PData.Split('|');
                    pr.Tooltip = ttd[0].Split(':')[1];
                    pr.X       = X + Single.Parse(ttd[1].Split(':')[1]) * SCALEFACTOR;
                    pr.Y       = Y + Single.Parse(ttd[2].Split(':')[1]) * SCALEFACTOR;
                    pr.W       = Single.Parse(ttd[3].Split(':')[1]) * SCALEFACTOR;
                    pr.H       = Single.Parse(ttd[4].Split(':')[1]) * SCALEFACTOR;
                    items.Add(pr);
                }
                else if (PData.StartsWith("PolyToolTip"))
                {
                    PagePolygon pp = new PagePolygon();
                    StyleInfo   si = new StyleInfo();
                    pp.SI = si;
                    //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn
                    string[] ttd = PData.Split('|');
                    PointF[] pts = new PointF[(ttd.Length - 1) / 2];
                    pp.Points  = pts;
                    pp.Tooltip = ttd[0].Split(':')[1];
                    for (int i = 0; i < pts.Length; i++)
                    {
                        pts[i].X = X + Single.Parse(ttd[i * 2 + 1]) * SCALEFACTOR;
                        pts[i].Y = Y + Single.Parse(ttd[i * 2 + 2]) * SCALEFACTOR;
                    }
                    items.Add(pp);
                }
                return(items);
            }

            finally
            {
                if (_br != null)
                {
                    _br.Close();
                }
                if (_ms != null)
                {
                    _ms.Dispose();
                }
            }
        }
 private static string[] GetDecodedAndSplitAuthorizatonHeader(
   string AuthHeader)
 {
     string[] RetVal = new string[2] { string.Empty, string.Empty };
     if (AuthHeader != null && AuthHeader.StartsWith("Basic "))
     {
         try
         {
             string EncodedString = AuthHeader.Substring(6);
             byte[] DecodedBytes = Convert.FromBase64String(EncodedString);
             string DecodedString = new ASCIIEncoding().GetString(DecodedBytes);
             RetVal = DecodedString.Split(new char[] { ':' });
         }
         catch
         {
         }
     }
     return RetVal;
 }
Пример #14
0
        public void OnPeerDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);

                string incoming = szData.Substring(0, szData.Length - 1);

                if (incoming.StartsWith("/file"))
                {
                    MessageBox.Show("receiving file");
                    //recieved file
                    //file infile = new file();

                    string infilemsg = incoming.Substring(5);
                    cryptor.rijn.Key = senderClient.sessionkey;
                    string infilepart = cryptor.DecryptMessage(infilemsg);
                    string[] infilefields = infilepart.Split(' ');
                    //infile.fileid = infilefields[0];
                    //infile.filesize = infilefields[1];
                    string concat = infilefields[2]+" "+infilefields[3]+" "+infilefields[4];
                    byte[] bytefile = System.Text.Encoding.ASCII.GetBytes(concat);
                    //infile.filedata = bytefile;

                    string filename = infilefields[0];
                    //infile.filename = filename;

                    //filelist.Add(infile);
                    FileStream fStream = new FileStream(filename, FileMode.CreateNew);

                    BinaryWriter bw = new BinaryWriter(fStream);

                    bw.Write(bytefile);

                    bw.Close();

                    fStream.Close();

                }
                else if (incoming.StartsWith("/req"))
                {
                    //MessageBox.Show("Give me a halelujah");
                    //recieved share request

                    //receive tickets and import them to a arraylist.
                    mytickets tickets = new mytickets();

                    //List<client> clientlist = new List<client>();

                    tickets.DecodeFromString(incoming.Substring(4));

                    if ((!rsaserver.VerifyData(tickets.ticketlist[0].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signFirst))
                            || (!rsaserver.VerifyData(tickets.ticketlist[0].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signSecond)))
                    {
                        MessageBox.Show("AS is not authentic!");

                    }
                    else
                    {
                        ASCIIEncoding ByteConverter = new ASCIIEncoding();
                        string originalData = ByteConverter.GetString(tickets.ticketlist[0].origSecond);
                        string[] origfields = originalData.Split(' ');

                        if (!rsa.ToXmlString(false).Equals(origfields[2]))
                        {
                            MessageBox.Show("This ticket is not mine!");
                        }
                        else
                        {
                            string destData = ByteConverter.GetString(tickets.ticketlist[0].origFirst);
                            string[] destfields = destData.Split(' ');
                            senderClient = new client();
                            senderClient.ip = destfields[0];
                            senderClient.port = destfields[1];
                            senderClient.publicKey = destfields[2];
                            senderClient.ticket = incoming.Substring(4);
                            //WaitForPeerData(); // gerek var mý ?

                        }

                    }

                }
                else if (incoming.StartsWith("/key"))
                {
                    //recieved shared key

                    string[] KeyFields = incoming.Substring(4).Split(' ');
                    rsapeer.FromXmlString(senderClient.publicKey);

                    if (!rsapeer.VerifyData(ToByteArray(KeyFields[0]), new SHA1CryptoServiceProvider(), ToByteArray(KeyFields[1])))
                    {
                        MessageBox.Show("Key is not authenticated by valid sender!");

                    }
                    else
                    {
                        byte[] SessionKey = rsa.Decrypt(ToByteArray(KeyFields[0]), true);
                        senderClient.sessionkey = SessionKey;

                    }

                }
                else if (incoming.StartsWith("/sndreq"))
                {
                    //file'i oku
                    string[] fields = incoming.Substring(7).Split(' ');

                    //receive tickets and import them to a arraylist.
                    mytickets tickets = new mytickets();

                    //List<client> clientlist = new List<client>();

                    tickets.DecodeFromString(fields[0]);

                    if ((!rsaserver.VerifyData(tickets.ticketlist[0].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signFirst))
                            || (!rsaserver.VerifyData(tickets.ticketlist[0].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signSecond)))
                    {
                        MessageBox.Show("AS is not authentic!");

                    }
                    else
                    {

                        try
                        {

                            string fname = fields[1];
                            FileInfo fInfo = new FileInfo(fname);

                            long numBytes = fInfo.Length;

                            FileStream fStream = new FileStream(fname, FileMode.Open, FileAccess.Read);

                            BinaryReader br = new BinaryReader(fStream);

                            data = br.ReadBytes((int)numBytes);
                            br.Close();
                            fStream.Close();

                            MessageBox.Show("sending file piece back");
                            string functionID = "/pback";

                            string request = functionID + BytesToHex(data).Replace(" ", "");

                            //Object objData = request;

                            byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);

                            //who to send?
                            Socket tempSoc;
                            //try
                            //{
                            string target = new ASCIIEncoding().GetString(tickets.ticketlist[0].origFirst);
                            string[] targetFields = target.Split(' ');
                            string ipStr = targetFields[0];
                            string portStr = targetFields[1];

                            UpdateControls(false);
                            // Create the socket instance
                            tempSoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                            // Cet the remote IP address
                            IPAddress ip = IPAddress.Parse(ipStr);
                            int iPortNo = System.Convert.ToInt16(portStr);
                            // Create the end point
                            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
                            // Connect to the remote host

                            tempSoc.Connect(ipEnd);
                            if (tempSoc.Connected)
                            {

                                UpdateControls(true);
                                //Wait for data asynchronously

                            }
                            //}
                            //catch (SocketException se)
                            //{
                            //  string str;
                            //str = "\nConnection failed, is the server running?\n" + se.Message;
                            //MessageBox.Show(str);
                            //UpdateControls(false);

                            //}

                            if (tempSoc != null)
                            {
                                tempSoc.Send(byData);
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }
                    }
                }
                else if (incoming.StartsWith("/pback"))
                {
                    string filePartMsg = incoming.Substring(6);
                    byte[] filePartb = ToByteArray(filePartMsg);

                    string bconcat = System.Text.Encoding.ASCII.GetString(filePartb);

                    string[] infilefields = bconcat.Split(' ');

                    byte[] tempPart = ToByteArray(infilefields[0]);

                    SharedData partOftheSecretThatWeAreTryingToAcquire = new SharedData();
                    partOftheSecretThatWeAreTryingToAcquire.xi = System.Convert.ToInt64(infilefields[1]);
                    partOftheSecretThatWeAreTryingToAcquire.yi = System.Convert.ToInt64(infilefields[2]);

                    secretsFromOthers.Add(partOftheSecretThatWeAreTryingToAcquire);
                    partsFromOthers.Add(tempPart);

                    if (partsFromOthers.Count >= enoughParts)
                    {
                        Reconstruct();
                    }
                }

                // Continue the waiting for data on the Socket
                WaitForPeerData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
Пример #15
0
        private void msgLoop()
        {
            while (true)
            {
                lock (clientLock)
                {
                    byte[] bytes = new byte[1024];
                    int len = stream.Read(bytes, 0, 1024);

                    if (len == 0)
                    {
                        break;
                    }

                    string str = new ASCIIEncoding().GetString(bytes, 0, len);

                    foreach (string split in str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        OnMsgGet(split);
                    }
                }
            }
        }
        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;

            //the Authorization header is checked if present
            string authHeader = app.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    // header is not correct...we'll pass it along and
                    // assume someone else will handle it
                    return;
                }

                authStr = authStr.Trim();

                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes =
                Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string username = userPass[0];
                string password = userPass[1];

                Microsoft.Xrm.Client.CrmConnection connection = GetCrmConnection(username, password);
                using (OrganizationService service = new OrganizationService(connection))
                {
                    WhoAmIRequest req = new WhoAmIRequest();
                    WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
                    if (resp.Results.Count > 0)
                    {
                        app.Context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), new string []{"none"});
                    }
                    else
                    {
                        DenyAccess(app);
                        return;
                    }
                }

                if (Membership.ValidateUser(username, password))
                {
                    string[] roles = Roles.GetRolesForUser(username);
                }
                else
                {
                }
            }
            else
            {
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }