/// <summary> /// Determines if the specified client certificate is valid based on its serial number and a list of valid serial /// numbers. /// </summary> /// <param name="certificate"> /// The certificate whose validity to check. /// </param> /// <param name="validSerialNumbers"> /// The list of serial numbers for valid certificates. /// </param> /// <returns> /// * True if the specified certificate is valid. /// * Else returns false. /// </returns> /// <exception cref="ArgumentNullException"> /// * Parameter certificate cannot be null. /// -OR- /// * Parameter validSerialNumbers cannot be null. /// </exception> public static bool IsPresentedCertValid(HttpClientCertificate certificate, Collection <string> validSerialNumbers) { if (certificate == null) { throw new ArgumentNullException("certificate", "Parameter certificate cannot be null."); } if (validSerialNumbers == null) { throw new ArgumentNullException("validSerialNumbers", "Parameter validSerialNumbers cannot be null."); } bool result = false; // Certificate is valid if its serial number matches one of the listed valid serial numbers, regardless of case, or // if it is null, empty, or whitespace and one of the valid serial numbers is also null, empty, or whitespace. foreach (string serialNumber in validSerialNumbers) { if (String.Equals(certificate.SerialNumber, serialNumber, StringComparison.OrdinalIgnoreCase) == true || (String.IsNullOrWhiteSpace(certificate.SerialNumber) == true && String.IsNullOrWhiteSpace(serialNumber) == true)) { result = true; break; } } return(result); }
public void DefaultValues() { HttpClientCertificate hcc = GetHttpClientCertificate(); Assert.AreEqual(0, hcc.BinaryIssuer.Length, "BinaryIssuer"); Assert.AreEqual(0, hcc.CertEncoding, "CertEncoding"); Assert.AreEqual(0, hcc.Certificate.Length, "Certificate"); Assert.AreEqual(String.Empty, hcc.Cookie, "Cookie"); Assert.AreEqual(0, hcc.Flags, "Flags"); Assert.IsFalse(hcc.IsPresent, "IsPresent"); Assert.AreEqual(String.Empty, hcc.Issuer, "Issuer"); Assert.IsTrue(hcc.IsValid, "IsValid"); Assert.AreEqual(0, hcc.KeySize, "KeySize"); Assert.AreEqual(0, hcc.PublicKey.Length, "PublicKey"); Assert.AreEqual(0, hcc.SecretKeySize, "SecretKeySize"); Assert.AreEqual(String.Empty, hcc.SerialNumber, "SerialNumber"); Assert.AreEqual(String.Empty, hcc.ServerIssuer, "ServerIssuer"); Assert.AreEqual(String.Empty, hcc.ServerSubject, "ServerSubject"); Assert.AreEqual(String.Empty, hcc.Subject, "Subject"); DateTime start = DateTime.Now.AddMinutes(1); DateTime end = start.AddMinutes(-2); // creation time - doesn't update (at least after first call) Assert.IsTrue(hcc.ValidFrom < start, "ValidFrom <"); Assert.IsTrue(hcc.ValidFrom > end, "ValidFrom >"); Assert.IsTrue(hcc.ValidUntil < start, "ValidUntil <"); Assert.IsTrue(hcc.ValidUntil > end, "ValidUntil >"); // NameValueCollection stuff Assert.AreEqual(0, hcc.Count, "Count"); }
private void DoTestSSL(HttpContext context) { HttpClientCertificate certificate = context.Request.ClientCertificate; context.Response.Output.WriteLine("issuer: " + certificate.Issuer); context.Response.Output.WriteLine("server-issuer: " + certificate.ServerIssuer); context.Response.Output.WriteLine("server-subject" + certificate.ServerSubject); context.Response.Output.WriteLine("valid-from: " + certificate.ValidFrom); context.Response.Output.WriteLine("valid-until: " + certificate.ValidUntil); foreach (String key in certificate.AllKeys) { context.Response.Output.Write(key + ": "); if (certificate.GetValues(key) != null) { foreach (String value in certificate.GetValues(key)) { context.Response.Output.Write(value + ", "); } } context.Response.Output.WriteLine(); } context.Response.Output.WriteLine("is-valid: " + certificate.IsValid); context.Response.Output.WriteLine("is-present: " + certificate.IsPresent); context.Response.Output.WriteLine("cert-cookie: " + certificate.Cookie); context.Response.Output.WriteLine("binary-cert: " + certificate.Certificate.Length); context.Response.Output.WriteLine("cert-encoding: " + certificate.CertEncoding); Introspect(context); }
private static HttpRequestBase CreateStubWebRequest(HttpClientCertificate clientCertificate) { Mock <HttpRequestBase> mock = new Mock <HttpRequestBase>(MockBehavior.Strict); mock.Setup(r => r.ClientCertificate).Returns(clientCertificate); return(mock.Object); }
protected void Page_Load(object sender, EventArgs e) { try { HttpContext context = HttpContext.Current; byte[] RawData = context.Request.ClientCertificate.Certificate; X509Certificate2 xc = new X509Certificate2(); HttpClientCertificate cert = Request.ClientCertificate; if (cert.IsPresent) { X509Certificate2 certificado = new X509Certificate2(RawData); Certificado objCertificado = new CertificadoBO().PegarCertificado(RawData); txtCpfCnpj.Text = objCertificado.eCpfCnpj; txtNome.Text = objCertificado.Nome; txtTipo.Text = objCertificado.TipoCertificado.ToString(); } else { txtTipo.Text = ""; txtNome.Text = ""; txtCpfCnpj.Text = ""; } } catch (Exception) { txtTipo.Text = ""; txtNome.Text = ""; txtCpfCnpj.Text = ""; } }
public void ClientCertificateGet_ReturnsRequestBaseClientCertificate() { // Arrange byte[] expectedCertificateBytes = Convert.FromBase64String(Base64Certificate); HttpContextBase webContext = CreateDummyWebContext(); HttpClientCertificate clientCertificate = CreateHttpClientCertificate( expectedCertificateBytes ); HttpRequestBase webRequest = CreateStubWebRequest(clientCertificate); using (HttpRequestMessage request = CreateRequest()) { HttpRequestContext context = CreateProductUnderTest( webContext, webRequest, request ); // Act X509Certificate2 certificate = context.ClientCertificate; // Assert Assert.NotNull(certificate); Assert.Equal(expectedCertificateBytes, certificate.RawData); } }
public static bool CertAuth(this HttpRequestBase request, string issuer) { HttpClientCertificate cert = request.ClientCertificate; if (cert == null || !cert.IsValid) { return(false); } X509Certificate2 x509 = new X509Certificate2(cert.Certificate); X509Chain chain = new X509Chain(true); chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; chain.Build(x509); if (!chain.ChainElements.Cast <X509ChainElement>().Any(e => e.Certificate.Thumbprint.Equals(issuer, StringComparison.OrdinalIgnoreCase))) { return(false); } string userName = x509.GetNameInfo(X509NameType.SimpleName, false); FormsAuthentication.SetAuthCookie(userName, false, request.ApplicationPath); return(true); }
public void Add() { HttpClientCertificate hcc = GetHttpClientCertificate(); Assert.AreEqual(0, hcc.Count, "0"); hcc.Add("a", "b"); Assert.AreEqual(1, hcc.Count, "1"); // it's not read-only (at least not in this case) }
public void Get() { HttpClientCertificate hcc = GetHttpClientCertificate(); Assert.AreEqual(String.Empty, hcc.Get(null), "null"); hcc.Add("a", "b"); Assert.AreEqual(String.Empty, hcc.Get("a"), "Get(string)"); Assert.AreEqual("b", hcc.Get(0), "Get(int)"); }
public bool IsAuthenticated(HttpClientCertificate httpClientCertificate, ref string username) { // Explicitly cast certificate to usable type, X509Certificate2 var certificate = new X509Certificate2(httpClientCertificate.Certificate); string cName = ""; // Verify the certificate, then if it is create the username and bind it to the reference if (Verify(certificate, ref cName)) { string[] name = cName.Trim().Split(' '); if (name.Length == 1) { username = name[0]; } else if (name.Length > 0) { // max specifies the maximum length of the username generated int max = 10; for (int i = 0; i < name.Length; i++) { int remaining = max - username.Length; if (remaining < 0) { break; } else { for (int j = 0; j < remaining; j++) { if (j < name[i].Length) { username += name[i][j]; } else { break; } } } } Global.LogInfo("\tUsername: \"" + username + "\" found. Logging in..."); } else { Global.LogInfo("\tCertificate does not have a Common Name (CN), unable to create username"); return(false); } return(true); } else { Global.LogInfo("\tUnable to verify certificate"); return(false); } }
X509Certificate2 HttpChannelListener.IHttpAuthenticationContext.GetClientCertificate(out bool isValidCertificate) { HttpClientCertificate clientCertificate = this.Application.Request.ClientCertificate; isValidCertificate = clientCertificate.IsValid; if (clientCertificate.IsPresent) { return(new X509Certificate2(clientCertificate.Certificate)); } return(null); }
protected void Page_Load(object sender, EventArgs e) { if (this.Session["times"] == null) { this.Session["times"] = (object)0; } string ip = this.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ip == null) { ip = this.Request.ServerVariables["REMOTE_ADDR"]; } this.Session["ip"] = (object)ip; try { LOGIN_ATTEMPT loginAttempt = Queryable.Single <LOGIN_ATTEMPT>(this.classobj.Login_attempts, (System.Linq.Expressions.Expression <Func <LOGIN_ATTEMPT, bool> >)(p => p.IP == ip)); if (loginAttempt.DateTime.AddMinutes((double)loginAttempt.Time_rest) > DateTime.Now) { this.Response.Redirect("WorningPageInterop.aspx"); } } catch { } HttpClientCertificate clientCertificate = this.Request.ClientCertificate; X509Certificate2 x509Certificate2 = new X509Certificate2(this.Context.Request.ClientCertificate.Certificate); string contents; if (clientCertificate.IsPresent) { contents = clientCertificate.Subject.Split(',')[2].Trim(); this.Session["CertificateName"] = (object)contents; } else { contents = "No certificate was found."; this.Session["CertificateName"] = (object)null; } try { File.WriteAllText("C:\\test.txt", contents); } catch { } if (!new WebApplicationInterop.InteropDAL().GetSetting().CanCopyPrintScreen.Value) { this.ClientScript.RegisterClientScriptBlock(this.GetType(), "setClipBoardData", "" + "function setClipBoardData(){" + "setInterval(\"window.clipboardData.setData('text','')\",20);" + "}" + "function blockError(){" + "window.location.reload(true);" + "return true;}", true); } else { this.ClientScript.RegisterClientScriptBlock(this.GetType(), "setClipBoardData", "" + "function setClipBoardData(){" + "}", true); } }
public async Task <JsonResult> CreateClient(HttpClientCertificate client) { if (ModelState.IsValid) { Client _client = AutoMapperConfiguration.Mapper.Map <Client>(client); bool result = await _clientService.CreateClient(_client); return(Json(result, JsonRequestBehavior.AllowGet)); } return(Json(true, JsonRequestBehavior.AllowGet)); }
public void MirrorValues_Alternate() { hwr.MirrorVariableName = true; hwr.AlternateChoice = true; HttpClientCertificate hcc = GetHttpClientCertificate(); // if CERT_KEYSIZE is missing then HTTPS_KEYSIZE isn't checked Assert.AreEqual(0, hcc.KeySize, "Alternate-KeySize"); // if CERT_SECRETKEYSIZE is missing then HTTPS_SECRETKEYSIZE isn't looked Assert.AreEqual(0, hcc.SecretKeySize, "Alternate-SecretKeySize"); }
public static Dictionary <string, string> Convert(HttpClientCertificate coll) { var keyValues = new Dictionary <string, string>(); var keys = coll.Keys; foreach (var key in keys) { var strKey = key.ToString(); var value = coll.Get(strKey).ToString(); keyValues.Add(strKey, value); } return(keyValues); }
private IEnumerable <Claim> GetClaimsFromCertificate(HttpClientCertificate cert) { //Validate cert var x509Issuer = GetIssuer(new X509Certificate2(cert.Certificate)); if (ValidateIssuer(x509Issuer)) { return(ExtractUserClaims(cert.Subject)); } else { throw new CryptographicException("Issuer is not trusted"); } }
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) { var httpRequest = authService.RequestContext.Get <IHttpRequest>(); HttpClientCertificate certificate = ((HttpRequest)httpRequest.OriginalRequest).ClientCertificate; if (certificate == null) { throw HttpError.Unauthorized("Certificate not supplied."); } string subject = certificate.Subject; string issuer = certificate.Issuer; return(Authenticate(authService, session, subject, issuer, request.Continue)); }
public void HttpWorkerRequest() { // required to "activate" later call as IsPresent will return true hwr.MirrorVariableName = true; hwr.Override = true; HttpClientCertificate hcc = GetHttpClientCertificate(); // not affected by server variables (but by HttpWorkerRequest) Assert.AreEqual(2, hcc.BinaryIssuer.Length, "BinaryIssuer"); Assert.AreEqual(Int32.MinValue, hcc.CertEncoding, "CertEncoding"); Assert.AreEqual(1, hcc.Certificate.Length, "Certificate"); Assert.AreEqual(3, hcc.PublicKey.Length, "PublicKey"); Assert.AreEqual(DateTime.MaxValue, hcc.ValidFrom, "ValidFrom"); Assert.AreEqual(DateTime.MinValue, hcc.ValidUntil, "ValidUntil"); }
protected void Page_Load(object sender, EventArgs e) { string userName; userName = User.Identity.Name; greetingLabel.Text = "Welcome " + userName; HttpClientCertificate cert = Request.ClientCertificate; if (cert.IsPresent) { certLabel.Text = cert.Get("SUBJECT O"); } else { certLabel.Text = "No certificate was found."; } }
private void Page_Load(object sender, System.EventArgs e) { System.Web.UI.HtmlControls.HtmlForm frm = (HtmlForm)FindControl("Form1"); GHTTestBegin(frm); // =================================== // testing if the clientCertficate object is set // =================================== GHTSubTestBegin("ClinetCertficate1"); try { if (Request.ClientCertificate == null) { GHTSubTestAddResult("Failed"); } else { GHTSubTestAddResult("Success"); } } catch (Exception ex) { GHTSubTestAddResult("unxpected " + ex.GetType().Name + " exception was caught-" + ex.Message); } GHTSubTestEnd(); // =================================== // testing if the objects return is from the // correct type // =================================== GHTSubTestBegin("ClinetCertficate2"); try { HttpClientCertificate CC = this.Request.ClientCertificate; GHTSubTestAddResult("success"); } catch (Exception ex) { GHTSubTestAddResult("Unxpected " + ex.GetType().Name + " exception was caught-" + ex.Message); } GHTSubTestEnd(); GHTTestEnd(); }
public void ClientCertificateGet_ReturnsNull_WhenRequestBaseClientCertificateCertificateIsNull() { // Arrange HttpContextBase webContext = CreateDummyWebContext(); HttpClientCertificate clientCertificate = CreateHttpClientCertificate(null); HttpRequestBase webRequest = CreateStubWebRequest(clientCertificate); using (HttpRequestMessage request = CreateRequest()) { HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request); // Act X509Certificate2 certificate = context.ClientCertificate; // Assert Assert.Null(certificate); } }
public void Valid() { HttpClientCertificate hcc = GetHttpClientCertificate(); // just to see if it always returns DateTime.Now or if it cache the value long from1 = hcc.ValidFrom.Ticks; Thread.Sleep(100); // don't go too fast long until1 = hcc.ValidUntil.Ticks; Thread.Sleep(100); // don't go too fast long from2 = hcc.ValidFrom.Ticks; Thread.Sleep(100); // don't go too fast long until2 = hcc.ValidUntil.Ticks; Assert.AreEqual(from1, from2, "from-from"); Assert.AreEqual(until1, until2, "until-until"); Assert.AreEqual(from1, until2, "from-until"); }
/// <summary> /// this code in the PageLoad of the page which you want to make it secure /// http://msdn.microsoft.com/en-us/library/aa302412.aspx /// </summary> /// <param name="WebRequest">Request.ClientCertificate</param> /// <returns></returns> public static bool ClientCertificate(HttpRequest WebRequest) { if (WebRequest != null) { HttpClientCertificate cert = WebRequest.ClientCertificate; if (cert.IsPresent) { return(true); } else { return(false); } } else { return(false); } }
public void MirrorValues() { hwr.MirrorVariableName = true; HttpClientCertificate hcc = GetHttpClientCertificate(); // not default (because we now have some data) Assert.IsFalse(hcc.IsValid, "IsValid"); Assert.IsTrue(hcc.IsPresent, "IsPresent"); Assert.AreEqual("CERT_COOKIE", hcc.Cookie, "Cookie"); Assert.AreEqual(11, hcc.Flags, "Flags"); Assert.AreEqual("CERT_ISSUER", hcc.Issuer, "Issuer"); Assert.AreEqual(12, hcc.KeySize, "KeySize"); Assert.AreEqual(13, hcc.SecretKeySize, "SecretKeySize"); Assert.AreEqual("CERT_SERIALNUMBER", hcc.SerialNumber, "SerialNumber"); Assert.AreEqual("CERT_SERVER_ISSUER", hcc.ServerIssuer, "ServerIssuer"); Assert.AreEqual("CERT_SERVER_SUBJECT", hcc.ServerSubject, "ServerSubject"); Assert.AreEqual("CERT_SUBJECT", hcc.Subject, "Subject"); }
private static string ParseUserName(HttpClientCertificate cert, string issuer) { if (issuer.IsNullOrEmpty()) { throw new ApplicationException("Issuer has not been set."); } if (Debugger.IsAttached) { return("Debug"); } if (cert != null && cert.IsValid && !cert.Subject.IsNullOrEmpty() && cert.BinaryIssuer.ToHexString().Equals(issuer, StringComparison.OrdinalIgnoreCase)) { return(cert.Subject.Substring("CN=".Length)); } return(null); }
private void CheckCertificate(HttpClientCertificate Cert) { if (!Cert.IsPresent) { throw new CSAAWeb.BusinessRuleException("Certificate must be provided."); } if (!Cert.IsValid) { throw new CSAAWeb.BusinessRuleException("Certificate is not valid."); } if (Cert.ValidUntil.CompareTo(DateTime.Now) < 0) { throw new CSAAWeb.BusinessRuleException("Certificate has expired."); } //if (Certificates.Contains(Cert.SerialNumber)) throw new CSAAWeb.BusinessRuleException("Certificate is not installed."); //Changed by cognizant on Feb 10 2005 as onsite suggestion if (!Certificates.Contains(Cert.SerialNumber)) { throw new CSAAWeb.BusinessRuleException("Certificate is not installed."); } }
private static ADUser ResolveCertificateFromCacheOrAD(HttpClientCertificate certificate, string orgName) { Logger.EnterFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificateFromCacheOrAD"); X509Identifier x509Identifier = CertificateAuthenticationModule.CreateCertificateIdentity(certificate); ADUser aduser = CertificateAuthenticationModule.GetUserFromCache(x509Identifier); if (aduser == null) { aduser = CertificateAuthenticationModule.ResolveCertificate(x509Identifier, orgName); if (aduser != null) { CertificateAuthenticationModule.AddUserToCache(x509Identifier, aduser); } } else { HttpLogger.SafeAppendGenericInfo("ResolveCertificateFromCacheOrAD", "Cache"); } if (aduser == null) { Logger.LogEvent(CertificateAuthenticationModule.eventLogger, TaskEventLogConstants.Tuple_CertAuth_UserNotFound, certificate.Subject, new object[] { certificate.Subject }); Logger.LogVerbose("Found no user by certificate {0}", new object[] { certificate.Subject }); } else { Logger.LogVerbose("Found user {0} by certificate {1}", new object[] { aduser.Name, certificate.Subject }); } Logger.ExitFunction(ExTraceGlobals.CertAuthTracer, "ResolveCertificateFromCacheOrAD"); return(aduser); }
//********************************************************************* /// /// <summary> /// /// </summary> /// <param name="clientCert"></param> /// <returns></returns> /// //********************************************************************* private static bool AuthenticateUser(HttpClientCertificate clientCert) { var validated = false; try { var name = clientCert.Subject; validated = IsAuthorized(clientCert); if (validated) { var identity = new System.Security.Principal.GenericIdentity(name); SetPrincipal(new System.Security.Principal.GenericPrincipal(identity, null)); } } catch (FormatException) { // Credentials were not formatted correctly. validated = false; } return(validated); }
/// <summary> /// Validator entrypoint /// </summary> /// <param name="cert">Certificate to validate</param> /// <returns>True if the certificate was validated; false otherwise</returns> public static bool Validate(HttpClientCertificate cert) { //****** DISABLED UNTIL OSI WORKS //if (frontDoorCert == null) //{ // string frontDoorCertSubject = ConfigurationManager.AppSettings["FrontDoorClientCert"]; // frontDoorCert = GetCertificateBySubjectName(frontDoorCertSubject); //} //if (cert != null && cert.IsPresent) //{ // try // { // return new X509Certificate2(cert.Certificate).Thumbprint == frontDoorCert.Thumbprint; // } // catch (Exception) // { // // Do your exception logging here // } //} return(true); }
protected void Page_Load(object sender, EventArgs e) { string UsuarioAutenticado; string UsuarioASP; // Usuario que realiza la solicitud de la página UsuarioAutenticado = User.Identity.Name; UsuarioASP = WindowsIdentity.GetCurrent().Name; etUsuarioAut.Text = "Usted es el usuario: " + UsuarioAutenticado; // Contexto de seguridad bajo el que se ejecuta la página etUsuarioASP.Text = "La página se ejecuta bajo el " + "contexto de seguridad: " + UsuarioASP; HttpClientCertificate certificado = Request.ClientCertificate; if (certificado.IsPresent) { // Obtener el campo "organización" (O) del certificado etCertificado.Text = certificado.Get("Subject O"); } else { etCertificado.Text = " El certificado de cliente se ha omitido."; } }
private static HttpRequestBase CreateStubWebRequest(HttpClientCertificate clientCertificate) { Mock<HttpRequestBase> mock = new Mock<HttpRequestBase>(MockBehavior.Strict); mock.Setup(r => r.ClientCertificate).Returns(clientCertificate); return mock.Object; }