Beispiel #1
0
        public List <TokenSigningCertificate> getTokenSigningCertificates()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "TokenSigningCertificatesHelper.getTokenSigningCertificates invoked");
            List <TokenSigningCertificate> certsToReturn = new List <TokenSigningCertificate>();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                    try
                    {
                        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
                        UPSBrowserLogger.LogDebug(loggingCategory, "LocalMachine cert store open");

                        SPContext spContext = Microsoft.SharePoint.SPContext.Current;
                        string siteHostName = (new Uri(spContext.Site.Url)).Host.ToLower();

                        UPSBrowserLogger.LogDebug(loggingCategory, $"Current SP site URL host part: {siteHostName}");

                        foreach (X509Certificate2 cert in store.Certificates)
                        {
                            UPSBrowserLogger.LogDebug(loggingCategory, $"cert.FriendlyName: {cert.FriendlyName}, cert.HasPrivateKey: {cert.HasPrivateKey}, cert.NotAfter: {cert.NotAfter}");
                            if (cert.HasPrivateKey && (cert.NotAfter > DateTime.Now))
                            {
                                TokenSigningCertificate certToAdd = new TokenSigningCertificate
                                {
                                    friendlyName = cert.FriendlyName,
                                    subject      = cert.Subject,
                                    thumbprint   = cert.Thumbprint,
                                    rank         = cert.Subject.ToLower().Equals($"cn={siteHostName}") ? 1 : 0,
                                    cert         = cert
                                };
                                certsToReturn.Add(certToAdd);
                                UPSBrowserLogger.LogDebug(loggingCategory, $"Cert added - friendly name: {certToAdd.friendlyName}; subject: {certToAdd.subject}, rank: {certToAdd.rank}");
                            }
                            ;
                        }
                    }
                    catch (Exception e)
                    {
                        UPSBrowserLogger.LogError(loggingCategory, e.Message);
                    };
                });
            }
            catch (System.Exception e)
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Error while trying to elevate privileges: {e.Message}");
            };

            return(certsToReturn.OrderByDescending(cert => cert.rank).ToList());
        }
Beispiel #2
0
        private void ImportUsersStartImportButton_Click(object sender, EventArgs evt)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "ImportUsersStartImportButton_Click invoked");

            string        resolvedUsersEmails = upsbrowser_import_users_resolved_hiddeninput.Text;
            List <string> emails = new List <string>(resolvedUsersEmails.Split(';'));

            emails = emails.Where(email => !string.IsNullOrEmpty(email)).ToList <string>(); //filter out empty emails

            string wsBaseUrl             = UPSBrowserSettings.getStringProperty(this.settings, "wsExternalUsersSourceUrl");
            string certThumbprint        = UPSBrowserSettings.getStringProperty(this.settings, "tokenSigningCertificateThumbprint");
            string identityProviderName  = UPSBrowserSettings.getStringProperty(this.settings, "identityProviderName");
            TokenSigningCertificate cert = certs.FirstOrDefault(c => c.thumbprint == certThumbprint);

            List <User> users = null;

            try
            {
                externalUsersSource.Init(wsBaseUrl, cert);
                users = externalUsersSource.getUsersByEmails(emails);
            }
            catch (Exception e)
            {
                DisplayCriticalError($"Error getting users from external source: {e.Message}", true);
                return;
            };


            if ((users != null) && (users.Count > 0))
            {
                foreach (User user in users)
                {
                    User createdUser = upsUsersDAL.createUser(user, identityProviderName);
                    if (createdUser != null)
                    {
                        string hiddenInputValue = upsbrowser_import_users_resolved_hiddeninput.Text.ToLower();
                        hiddenInputValue = hiddenInputValue.Replace(createdUser.WorkEmail.ToLower() + ";", "");
                        upsbrowser_import_users_resolved_hiddeninput.Text = hiddenInputValue;
                    }
                }
                ;
            }
            ;
        }
Beispiel #3
0
        public string getTokenString(TokenSigningCertificate signingCertificate)
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "TokenHelper.getTokenString invoked");


            // In .NET 4.5 which is the target framework version, DateTimeOffset does not have the ToUnixTimeSeconds method which was only introduced in .NET 4.6
            var dateNowUtc   = DateTime.UtcNow;
            var epoch        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var unixDateTime = (dateNowUtc - epoch).TotalSeconds + (Constants.jwtTokenLifetimeInMinutes * 60);


            var payload = new Dictionary <string, object>()
            {
                { "sub", signingCertificate.subject },
                { "friendlyName", signingCertificate.friendlyName },
                { "iss", signingCertificate.subject },
                { "aud", Constants.jwtTokenAudience },
                //{ "exp", DateTimeOffset.UtcNow.AddMinutes(Constants.jwtTokenLifetimeInMinutes).ToUnixTimeSeconds() }
                { "exp", unixDateTime }
            };
            string token = null;


            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                UPSBrowserLogger.LogDebug(loggingCategory, "Running with elevated privileges");

                // If you get "Keyset does not exist" exception at this stage, make sure the the SP web app pool account has access to the private key of the selected cert
                UPSBrowserLogger.LogDebug(loggingCategory, "Trying to get the cert's private key...");
                var rsaCryptoServiceProvider = signingCertificate.cert.PrivateKey as RSACryptoServiceProvider;


                try
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "Trying to generate a JWT token string using the private key...");
                    token = Jose.JWT.Encode(payload, rsaCryptoServiceProvider, JwsAlgorithm.RS256);
                }
                catch (System.Security.Cryptography.CryptographicException cryptoException)
                {
                    UPSBrowserLogger.LogDebug(loggingCategory, "System.Security.Cryptography.CryptographicException catched");

                    // Look for "Invalid algorithm specified" exception -
                    UPSBrowserLogger.LogInfo(loggingCategory, $"cryptoException.Message: {cryptoException.Message}");

                    var privateKey = signingCertificate.cert.PrivateKey as RSACryptoServiceProvider;
                    bool privateKeyIsExportable = privateKey.CspKeyContainerInfo.Exportable;

                    if (privateKeyIsExportable)
                    {
                        UPSBrowserLogger.LogDebug(loggingCategory, $"Recreating RsaCryptoServiceProvider using the same cert with MS Enhanced CSP to enable SHA256");

                        // Re-create RsaCryptoServiceProvider using the same cert with MS Enhanced CSP to enable SHA256.
                        // This will only work if the private key of the cert is marked as exportable!
                        // The new RsaCryptoServiceProvider is created by exporting the original cert private key
                        // and re-importing it again, and the export operation will throw the exception if the original
                        // cert is not marked as exportable: "System.Security.Cryptography.CryptographicException: Key not valid for use in specified state."
                        RSACryptoServiceProvider rsaCryptoServiceProvider_MSEnchancedCSP = new RSACryptoServiceProvider();
                        rsaCryptoServiceProvider_MSEnchancedCSP.ImportParameters(privateKey.ExportParameters(true));

                        UPSBrowserLogger.LogDebug(loggingCategory, "Trying to generate a JWT token string again using the reimported private key...");
                        token = Jose.JWT.Encode(payload, rsaCryptoServiceProvider_MSEnchancedCSP, JwsAlgorithm.RS256);
                    }
                    else
                    {
                        UPSBrowserLogger.LogError(loggingCategory, $"Cannot recreate RsaCryptoServiceProvider with MS Enhanced CSP, the original cert private key is not exportable");
                        token = null;
                    }
                };
            });



            UPSBrowserLogger.LogDebug(loggingCategory, $"token: {token}");
            return(token);
        }
Beispiel #4
0
 public bool Init(string wsBaseUrl, TokenSigningCertificate tokenSigningCert)
 {
     this.wsBaseUrl        = wsBaseUrl;
     this.tokenSigningCert = tokenSigningCert;
     return(true);
 }
Beispiel #5
0
        public DataTable GetFilteredExternalUsers()
        {
            UPSBrowserLogger.LogDebug(loggingCategory, "GetFilteredExternalUsers invoked");

            string searchString   = upsbrowser_import_users_searchtextbox.Text;
            string wsBaseUrl      = UPSBrowserSettings.getStringProperty(this.settings, "wsExternalUsersSourceUrl");
            string certThumbprint = UPSBrowserSettings.getStringProperty(this.settings, "tokenSigningCertificateThumbprint");

            UPSBrowserLogger.LogDebug(loggingCategory, $"searchString: {searchString}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"wsBaseUrl: {wsBaseUrl}");
            UPSBrowserLogger.LogDebug(loggingCategory, $"certThumbprint: {certThumbprint}");

            UPSBrowserLogger.LogDebug(loggingCategory, $"certs == null: {certs == null}");
            TokenSigningCertificate cert = certs.FirstOrDefault(c => c.thumbprint == certThumbprint);

            UPSBrowserLogger.LogDebug(loggingCategory, $"cert == null: {cert == null}");

            if (
                string.IsNullOrEmpty(searchString)
                ||
                searchString.Length < Constants.searchStringMingLength
                ||
                string.IsNullOrEmpty(wsBaseUrl)
                ||
                cert == null
                )
            {
                UPSBrowserLogger.LogError(loggingCategory, $"Invalid searchString, wsBaseUrl or cert. Returning null.");
                return(null);
            }

            List <User> externalUsers = null;

            try
            {
                externalUsersSource.Init(wsBaseUrl, cert);
                externalUsers = externalUsersSource.getUsersBySearchString(searchString);
            }
            catch (Exception e)
            {
                DisplayCriticalError($"Error getting users from external source: {e.Message}", true);
                return(null);
            };

            if (externalUsers == null)
            {
                return(null);
            }
            ;

            DataTable dt = new DataTable();

            dt.Columns.Add("DisplayName");
            dt.Columns.Add("WorkEmail");
            dt.Columns.Add("JobTitle");
            dt.Columns.Add("Department");

            externalUsers.ForEach((externalUser) => {
                DataRow dr        = dt.NewRow();
                dr["DisplayName"] = externalUser.DisplayName;
                dr["WorkEmail"]   = externalUser.WorkEmail;
                dr["JobTitle"]    = externalUser.JobTitle;
                dr["Department"]  = externalUser.Department;
                dt.Rows.Add(dr);
            });

            return(dt);
        }
Beispiel #6
0
 public bool Init(string wsBaseUrl, TokenSigningCertificate tokenSigningCert)
 {
     return(true);
 }