예제 #1
0
 public static void WriteReservation(Reservation r)
 {
     try
     {
         string fullPath = Path.GetFullPath(path + "reservations.txt");
         File.AppendAllText(fullPath, r.Write());
         try
         {
             Audit.WriteInFileSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "reservations.txt");
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
         }
     }
     catch (Exception e)
     {
         try
         {
             Audit.WriteInFileFailed(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "reservations.txt", e.Message);
         }
         catch (Exception eror)
         {
             Console.WriteLine(eror.Message);
         }
         Console.WriteLine($"Error while trying to write reservation with id {r.Id}, error: : {e.Message}");
     }
 }
예제 #2
0
 public static void WriteDiscount()
 {
     try
     {
         string fullPath = Path.GetFullPath(path + "discount.txt");
         File.WriteAllText(fullPath, String.Empty);
         File.AppendAllText(fullPath, Discount.ToString());
         try
         {
             Audit.WriteInFileSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "discount.txt");
         }
         catch (Exception e)
         {
             try
             {
                 Audit.WriteInFileFailed(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "discount.txt", e.Message);
             }
             catch (Exception eror)
             {
                 Console.WriteLine(eror.Message);
             }
             Console.WriteLine(e.Message);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"Error while trying to write discount : {e.Message}");
     }
 }
예제 #3
0
 public static void WriteUser(User u)
 {
     try
     {
         string fullPath = Path.GetFullPath(path + "users.txt");
         File.AppendAllText(fullPath, u.Write());
         try
         {
             Audit.WriteInFileSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "users.txt");
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
         }
     }
     catch (Exception e)
     {
         try
         {
             Audit.WriteInFileFailed(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "users.txt", e.Message);
         }
         catch (Exception eror)
         {
             Console.WriteLine(eror.Message);
         }
         Console.WriteLine($"Error while trying to write user with username {u.Username}, error: : {e.Message}");
     }
 }
예제 #4
0
        /// <summary>
        /// Implementation of a custom certificate validation on the service side.
        /// Service should consider certificate valid if its issuer is the same as the issuer of the service.
        /// If validation fails, throw an exception with an adequate message.
        /// </summary>
        /// <param name="certificate"> certificate to be validate </param>
        public override void Validate(X509Certificate2 certificate)
        {
            /// This will take service's certificate from storage
            X509Certificate2 srvCert = CertManager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine,
                                                                             Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "Service");

            if (!certificate.Issuer.Equals(srvCert.Issuer))
            {
                throw new Exception("Certificate is not from the valid issuer.");
            }
        }
예제 #5
0
        public static List <Reservation> ReadReservations()
        {
            List <Reservation> temp = new List <Reservation>();

            try
            {
                string fullPath = Path.GetFullPath(path + "reservations.txt");

                FileStream   stream = new FileStream(fullPath, FileMode.Open);
                StreamReader reader = new StreamReader(stream);

                string line = "";
                while ((line = reader.ReadLine()) != null)
                {
                    string[] tokens = line.Split(';');

                    string[] dateTokens = tokens[2].Split('/');
                    DateTime date       = new DateTime(int.Parse(dateTokens[2]), int.Parse(dateTokens[1]), int.Parse(dateTokens[0]));

                    Reservation r = new Reservation(int.Parse(tokens[0]), int.Parse(tokens[1]), date, int.Parse(tokens[3]));
                    r.State = (ReservationState)Enum.Parse(typeof(ReservationState), tokens[4]);
                    temp.Add(r);
                }

                reader.Close();
                stream.Close();
                try
                {
                    Audit.ReadFromFileSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "reservations.txt");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (Exception e)
            {
                try
                {
                    Audit.ReadFromFileFailed(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "reservations.txt", e.Message);
                }
                catch (Exception eror)
                {
                    Console.WriteLine(eror.Message);
                }
                Console.WriteLine($"Error while trying to read performances : {e.Message}");
            }
            return(temp);
        }
예제 #6
0
        public string GetClientUserName()
        {
            string retValue = "";

            try
            {
                string   nameClient = Formatter.ParseName(ServiceSecurityContext.Current.PrimaryIdentity.Name);
                string[] clientName = nameClient.Split(';');
                string[] tokens     = clientName[0].Split(',');
                retValue = tokens[0].Split('=')[1];
            }
            catch (Exception e)
            {
                Console.WriteLine($"\nError while trying to get the client name: {e.Message}.");
            }
            return(retValue);
        }
        // decrypt request
        // write data to the database
        public bool Write(byte[] encryptedKey, byte[] encryptedValue)
        {
            Console.WriteLine("----------------------------------------------------------------------------------");
            Console.WriteLine("Received encrypted WRITE request...");

            IIdentity       identity        = Thread.CurrentPrincipal.Identity;
            WindowsIdentity windowsIdentity = identity as WindowsIdentity;

            string user = Formatter.ParseName(windowsIdentity.Name);

            Console.WriteLine("User requesting the service: ");
            Console.WriteLine(user);

            byte[] sessionKey = GetSessionKey(user);
            string key;
            string value;

            try
            {
                key   = Encoding.ASCII.GetString(_3DESAlgorithm.Decrypt(encryptedKey, sessionKey)).Trim('\0');
                value = Encoding.ASCII.GetString(_3DESAlgorithm.Decrypt(encryptedValue, sessionKey)).Trim('\0');
            }
            catch (Exception e)
            {
                Console.WriteLine("Data Error: {0}", e.Message);
                throw new FaultException <DataException>(new DataException("Data Error: Key/Value cannot be  null, empty, or whitespace"));
            }
            try
            {
                Database.Write(key, value);
                return(true);
            }
            catch (FaultException <DataException> e)
            {
                Console.WriteLine("Data Error: {0}", e.Detail.Message);
                throw new FaultException <DataException>(new DataException(e.Detail.Message));
            }

            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
                throw new FaultException <DataException>(new DataException(e.Message));
            }
        }
예제 #8
0
        public static void ReadDiscount()
        {
            try
            {
                string fullPath = Path.GetFullPath(path + "discount.txt");

                FileStream   stream = new FileStream(fullPath, FileMode.Open);
                StreamReader reader = new StreamReader(stream);

                string line = "";
                while ((line = reader.ReadLine()) != null)
                {
                    Discount = int.Parse(line);
                }

                reader.Close();
                stream.Close();
                try
                {
                    Audit.ReadFromFileSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "discount.txt");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (Exception e)
            {
                try
                {
                    Audit.ReadFromFileFailed(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "discount.txt", e.Message);
                }
                catch (Exception eror)
                {
                    Console.WriteLine(eror.Message);
                }
                Console.WriteLine($"Error while trying to read discount : {e.Message}");
            }
        }
예제 #9
0
파일: Program.cs 프로젝트: Dexter255/SBES
        static void Main(string[] args)
        {
            //Debugger.Launch();
            WCFDatabase db = WCFDatabase.InitializeDb();

            //uzmemo username od servera kako bismo uzeli certificate uz pomoc toga
            String serviceCertificateCN = Formatter.ParseName(WindowsIdentity.GetCurrent().Name);

            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            string address = "net.tcp://localhost:9999/WCFService";

            ServiceHost serviceHost = new ServiceHost(typeof(WCFService));

            serviceHost.AddServiceEndpoint(typeof(IWCFService), binding, address);

            //kazemo da ne gleda da li je povucen sertifikat i setujemo .cer fajl od servera
            serviceHost.Credentials.ClientCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
            serviceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
            serviceHost.Credentials.ServiceCertificate.Certificate = CertManager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine, serviceCertificateCN);

            serviceHost.Description.Behaviors.Remove(typeof(ServiceDebugBehavior));
            serviceHost.Description.Behaviors.Add(new ServiceDebugBehavior()
            {
                IncludeExceptionDetailInFaults = true
            });


            serviceHost.Authorization.ServiceAuthorizationManager = new AuthorizationManager();

            //polisa sadrzi uslove koje omogucavaju evaluaciju korisnika(da li ima pravo pristupa nekoj metodi)
            //na osnovu polise radimo proveru
            serviceHost.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();

            policies.Add(new CustomPolicy());
            serviceHost.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly();

            serviceHost.Description.Behaviors.Remove <ServiceSecurityAuditBehavior>();
            ///////////////////////// LOGGER /////////////////////////
            NetTcpBinding bindingLogger = new NetTcpBinding();

            bindingLogger.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
            string          addressLogger   = "net.tcp://localhost:10000/WCFLogger";
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(addressLogger));

            //////////////////////////////////////////////////////////


            WCFServiceLoggerConnection.InitializeService(bindingLogger, endpointAddress);

            serviceHost.Open();
            Console.WriteLine("WCFService is opened. Press <enter> to finish and save databases...");
            Console.ReadLine();

            serviceHost.Close();

            db.SerializeData();
        }
예제 #10
0
        public void PayReservation(int reservationsId)
        {
            CustomPrincipal principal = Thread.CurrentPrincipal as CustomPrincipal;

            if (principal.IsInRole("Korisnik") || principal.IsInRole("SuperKorisnik"))
            {
                string clientUsername = GetClientUserName();
                string clientRole     = GetClientRole();
                Console.WriteLine("\nPaying reservation...");
                foreach (User u in Database.users)
                {
                    if (u.Username.Equals(clientUsername))
                    {
                        foreach (Reservation r in u.Reservations)
                        {
                            foreach (Performance p in Database.performances)
                            {
                                if (p.Id.Equals(r.PerformanceId))
                                {
                                    if (r.Id.Equals(reservationsId))
                                    {
                                        if (clientRole.Equals("Korisnik"))
                                        {
                                            u.Balance -= r.TicketQuantity * p.TicketPrice;
                                            try
                                            {
                                                Audit.ChangeSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "balance.");
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine(e.Message);
                                            }
                                        }
                                        else
                                        {
                                            u.Balance -= r.TicketQuantity * p.TicketPrice - (r.TicketQuantity * p.TicketPrice) * (Database.Discount / 100);
                                            try
                                            {
                                                Audit.ChangeSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "balance.");
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine(e.Message);
                                            }
                                        }

                                        for (int i = 0; i < u.Reservations.Count(); i++)
                                        {
                                            if (u.Reservations[i].Id.Equals(reservationsId))
                                            {
                                                u.Reservations[i].State = ReservationState.PAID;

                                                try
                                                {
                                                    Audit.PayReservationSuccess(clientUsername, ReservationState.UNPAID.ToString(), ReservationState.PAID.ToString());
                                                }
                                                catch (Exception e)
                                                {
                                                    Console.WriteLine(e.Message);
                                                }

                                                Database.WriteReservations();
                                                Database.WriteUsers();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                try
                {
                    Audit.AuthorizationFailed(GetClientUserName(), "Pay Reservation",
                                              $"Pay Reservation can be used only by user in the Korisnik or SuperKorisnik group.");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

                ErrorMessage("Korisnik or SuperKorisnik", "Pay Reservation");
            }
        }
예제 #11
0
        static void Main(string[] args)
        {
            /// srvCertCN.SubjectName should be set to the service's username. .NET WindowsIdentity class provides information about Windows user running the given process
            string srvCertCN = Formatter.ParseName(WindowsIdentity.GetCurrent().Name);             //sbesserver

            NetTcpBinding binding = new NetTcpBinding();

            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;

            string      address = "net.tcp://localhost:9999/Receiver";
            ServiceHost host    = new ServiceHost(typeof(WCFService));

            host.AddServiceEndpoint(typeof(IWCFService), binding, address);

            ///Custom validation mode enables creation of a custom validator - CustomCertificateValidator
            host.Credentials.ClientCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
            host.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new ServiceCertValidator();

            ///If CA doesn't have a CRL associated, WCF blocks every client because it cannot be validated
            host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;

            ///Set appropriate service's certificate on the host. Use CertManager class to obtain the certificate based on the "srvCertCN"
            host.Credentials.ServiceCertificate.Certificate = CertManager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine, srvCertCN);

            ///Set custom policy
            host.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
            List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>();

            policies.Add(new CustomAuthorizationPolicy());
            host.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly();

            ///AuditBehaviour
            ServiceSecurityAuditBehavior newAudit = new ServiceSecurityAuditBehavior();

            newAudit.AuditLogLocation = AuditLogLocation.Application;
            newAudit.ServiceAuthorizationAuditLevel = AuditLevel.SuccessOrFailure;

            host.Description.Behaviors.Remove <ServiceSecurityAuditBehavior>();
            host.Description.Behaviors.Add(newAudit);

            Database.performances = Database.ReadPerformances();
            Database.reservations = Database.ReadReservations();
            Database.users        = Database.ReadUsers();
            Database.ReadDiscount();

            try
            {
                host.Open();
                Console.WriteLine("WCFService is started.\nPress <enter> to stop...");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("[ERROR] {0}", e.Message);
                Console.WriteLine("[StackTrace] {0}", e.StackTrace);
                Console.ReadLine();
            }
            finally
            {
                host.Close();
            }
        }
예제 #12
0
        public static List <User> ReadUsers()
        {
            List <User> temp = new List <User>();

            try
            {
                string fullPath = Path.GetFullPath(path + "users.txt");

                FileStream   stream = new FileStream(fullPath, FileMode.Open);
                StreamReader reader = new StreamReader(stream);

                string line = "";

                while ((line = reader.ReadLine()) != null)
                {
                    string[] tokens = line.Split(';');

                    List <Reservation> userReservations = new List <Reservation>();
                    User user  = null;
                    int  count = tokens[3].Count(x => x == ',');
                    if (count != 0)
                    {
                        string[] idRes = tokens[3].Split(',');
                        for (int i = 0; i < count; i++)
                        {
                            foreach (Reservation res in reservations)
                            {
                                if (int.Parse(idRes[i]) == res.Id)
                                {
                                    userReservations.Add(res);
                                }
                            }
                        }
                        user = new User(tokens[0], tokens[1], double.Parse(tokens[2]), userReservations);
                    }
                    else
                    {
                        user = new User(tokens[0], tokens[1]);
                    }
                    temp.Add(user);
                }

                reader.Close();
                stream.Close();
                try
                {
                    Audit.ReadFromFileSuccess(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "users.txt");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (Exception e)
            {
                try
                {
                    Audit.ReadFromFileFailed(Formatter.ParseName(WindowsIdentity.GetCurrent().Name), "users.txt", e.Message);
                }
                catch (Exception eror)
                {
                    Console.WriteLine(eror.Message);
                }
                Console.WriteLine($"Error while trying to read users : {e.Message}");
            }
            return(temp);
        }