LDAP Server not available error when using LDAPS authentication - c#

string username = "username";
var con = new LdapConnection(new LdapDirectoryIdentifier(ADUtilities.LDAPServer, Convert.ToInt32(ADUtilities.LDAPPort), false, false));
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.ProtocolVersion = 3;
var clientCertificateFile = new X509Certificate();
clientCertificateFile.Import(ADUtilities.LDAPSSLCertificatePath);
con.ClientCertificates.Add(clientCertificateFile);
con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(VerifyServerCertificate); }
con.Credential = new NetworkCredential(username, ADPassword);
con.AuthType = AuthType.Negotiate;
con.Timeout = new TimeSpan(0, 1, 0);
con.Bind();
private bool VerifyServerCertificate(LdapConnection ldapConnection, X509Certificate certificate) {
X509Certificate2 certificate2 = new X509Certificate2(certificate);
return certificate2.Verify();
}
Error is coming in the line con.bind() that LDAP server is not available. Same code is working fine with port 389 but not with 636 i.e. LDAPS

Related

How to access MongoDB using GSSAPI authentication mechanism?

I am trying to connect to the MongoDB server through a ssl certificate using c#. I am getting a System.TimeoutException (A timeout occurred after 30000ms selecting a server using the CompositeServerSelector).
I started with connection via MongoClientSetting object. Here is the code:
MongoClientSettings settings = new MongoClientSettings();
settings.MaxConnectionLifeTime = new TimeSpan(12, 0, 0);
settings.UseSsl = true;
settings.VerifySslCertificate = false;
var cert = new X509Certificate2("mongoDBCAFile.cer");
settings.SslSettings = new SslSettings{
ClientCertificates = new[] { cert }
};
settings.Servers = new[]{
new MongoServerAddress("xyz1.intranet.companyname.com", 12345),
new MongoServerAddress("xyz2.intranet.companyname.com", 12345)
};
settings.ReplicaSetName = "replicaName";
var cred = MongoCredential.CreateGssapiCredential("username#intranet.companyname.com").WithMechanismProperty("SERVICE_NAME", "servicename");
settings.Credential = cred;
var client = new MongoClient(settings);
var database = client.GetDatabase("DatabaseName");
var collection = database.GetCollection<BsonDocument>("CollectionName");
//This is the place of error
var count1 = collection.CountDocuments(new BsonDocument());
I tried playing around with ConnectTimeout, SocketTimeout, and wTimeOut but the error was same.
I also tried doing the same thing using the connection string as mentioned here but I wouldn't figure out how to create a connection string with these many parameters.
Found the solution.
The issue was with authentication of the user with external server. MongoDB server was waiting for the clearance from this external server, but Because the authentication was never successfully, MongoDB always lead to System.TimeoutException.
Here is the fix code.
settings.ReplicaSetName = "replicaName";
SecureString pwd = new NetworkCredential("intranet/userName", "myPassword").securePassword;
var cred = MongoCredential.CreateGssapiCredential("username/intranet.companyname.com", pwd).WithMechanismProperty("SERVICE_NAME", "serviceName").WithMechanismProperty("CANONICALIZE_HOST_NAME", "true");
settings.Credentials = cred;

Exchange Web services :The request failed. The underlying connection was closed: An unexpected error occurred on a receive

I m getting this error : The request failed. The underlying connection was closed: An unexpected error occurred on a receive.
when im trying to read email from exchange server using EWS
this is my code :
try {
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ServicePointManager.MaxServicePoints =1000;
ServicePointManager.MaxServicePointIdleTime = 10000;
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 10000;
var exchange = new ExchangeService(ExchangeVersion.Exchange2013);
exchange.Credentials = new WebCredentials("user", "password", "domain");
exchange.TraceEnabled = true;
exchange.TraceFlags = TraceFlags.All;
exchange.AutodiscoverUrl("mail-id", RedirectionUrlValidationCallback);
exchange.Url = new System.Uri("https://URL/EWS/Exchange.asmx");
exchange.KeepAlive = false;
exchange.Timeout = 900000;
WriteToFile("Connected to Exchange Server : " + exchange.Url.Host);
TimeSpan ts = new TimeSpan(0, 0, -15, 0);
DateTime date = DateTime.Now.Add(ts);
SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
if (exchange != null)
{
FindItemsResults<Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(999));
foreach (Item item in findResults)
{
EmailMessage message2 = EmailMessage.Bind(exchange,
(EmailMessage.Bind(exchange, item.Id)).Id,
new PropertySet(BasePropertySet.FirstClassProperties,
new ExtendedPropertyDefinition(0x1013, MapiPropertyType.Binary)));
var mailbosy = message2.Body.Text;
}
I confirm what #Glen Scales says. The MSI download and NuGet downloads don't work. You must recompile from source.

Connect to MongoDB from .Net application with SSH

I connected shh tunnel and ForwardedPortLocal but mongo client does not connect .
Here is my expection "Additional information: Unable to connect to server localhost:27000: Invalid credential for database 'db_name'.."
var keyFile = new PrivateKeyFile(#"C:\Users\Desktop\mms_key.pem");
var username = "mms-user";
using (var client = new SshClient("dpmongo-0.sample.2121.mongodbdns.com",22, username, keyFile))
{
client.Connect();
var port = new ForwardedPortLocal("127.0.0.1", 27000, "localhost", 27000);
client.AddForwardedPort(port);
port.Start();
var credentials = MongoCredential.CreateMongoCRCredential("db_name", "user_name", "password");
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27000);
settings.Credentials = new[] { credentials };
var mongoEC2 = new MongoClient(settings);
var server = mongoEC2.GetServer();
var database = server.GetDatabase("db_name");
var collection = database.GetCollection<BsonDocument>("tag");
var query = Query.EQ("linkid", 2258021);
var userFound = collection.FindOne(query);
client.Disconnect();
}
string clientserver = "localhost";
string _port = "27000";
string mongo_username = "user_name";
string mongo_password = "password";
string databaseName = "db_name";
var connectionString = "mongodb://"
+ mongo_username + ":" + mongo_password + "#"
+ clientserver + ":" + _port + "/"
+ databaseName;
var server = new MongoClient(connectionString).GetServer();
//I tried this and it gave the same error on c#. This information was linked to my experiment on MongoCfee tools.

WCF Client Sign Soap Message with Smart Card

I have forms application with service reference by using CustomBinding for signing soap request (Only need soap body will be signed). If I try to sign request with private key included pfx wcf client succesfully sign Basic256Sha256Rsa15.
Succesfull case below:
private CustomBinding GetCustomHttpBinding()
{
CustomBinding binding = new CustomBinding();
// Open and Close = 20s
binding.OpenTimeout = new TimeSpan(0, 0, 20);
binding.CloseTimeout = new TimeSpan(0, 0, 20);
// Send and Receive = 300s
binding.SendTimeout = new TimeSpan(0, 5, 0);
binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
// ++ Setting security binding ++
var param = new X509SecurityTokenParameters();
param.X509ReferenceStyle = X509KeyIdentifierClauseType.IssuerSerial;
param.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
param.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
param.RequireDerivedKeys = false;
var userNameToken = new UserNameSecurityTokenParameters();
userNameToken.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
var securityElement = new AsymmetricSecurityBindingElement();
securityElement.EnableUnsecuredResponse = true;
securityElement.IncludeTimestamp = true;
securityElement.RecipientTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.Never);
securityElement.InitiatorTokenParameters = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient);
securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256Rsa15;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
securityElement.SetKeyDerivation(false);
securityElement.EndpointSupportingTokenParameters.Signed.Add(param);
//securityElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
binding.Elements.Add(securityElement);
// ++ Setting message encoding binding ++
var encodingElement = new TextMessageEncodingBindingElement();
encodingElement.MessageVersion = MessageVersion.Soap12;
encodingElement.WriteEncoding = Encoding.UTF8;
//encodingElement.MaxReadPoolSize = 50000000;
//encodingElement.MaxWritePoolSize = 50000000;
encodingElement.ReaderQuotas.MaxArrayLength = 50000000;
encodingElement.ReaderQuotas.MaxStringContentLength = 50000000;
binding.Elements.Add(encodingElement);
// ++ Setting https transport binding ++
var httpsElement = new HttpsTransportBindingElement();
// Messagge buffer size
httpsElement.MaxBufferSize = 50000000;
httpsElement.MaxReceivedMessageSize = 50000000;
httpsElement.MaxBufferPoolSize = 50000000;
httpsElement.RequireClientCertificate = true;
// Others
httpsElement.UseDefaultWebProxy = true;
binding.Elements.Add(httpsElement);
return binding;
}
And Service Sertificate set as
client.ClientCredentials.ClientCertificate.Certificate=cert;// From pfx file
client.ClientCredentials.ServiceCertificate.DefaultCertificate =serverCert;//from server certificate
I try to sign with my company smart card which is ACS38 smart card. If I use DefaultAlgotihmSuite Basic128 or Basic128Rsa15 then smartCard certificate succesfully sign body elements. I change algorihmsuite Basic256Sha256Rsa15 for requirement then I get KeySet does not exist. In this Smart Card have private key but WCF does not reach that private key.
Is there way to sign to Sign Soap Body with Sha256Rsa on SmartCard ?

Create a WCF REST Client Proxy Programatically (in C#)

I am trying to create a REST Client proxy programatically in C# using the code below but I keep getting a CommunicationException error. Am I missing something?
public static class WebProxyFactory
{
public static T Create<T>(string url) where T : class
{
ServicePointManager.Expect100Continue = false;
WebHttpBinding binding = new WebHttpBinding();
binding.MaxReceivedMessageSize = 1000000;
WebChannelFactory<T> factory =
new WebChannelFactory<T>(binding, new Uri(url));
T proxy = factory.CreateChannel();
return proxy;
}
public static T Create<T>(string url, string userName, string password)
where T : class
{
ServicePointManager.Expect100Continue = false;
WebHttpBinding binding = new WebHttpBinding();
binding.Security.Mode =
WebHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType =
HttpClientCredentialType.Basic;
binding.UseDefaultWebProxy = false;
binding.MaxReceivedMessageSize = 1000000;
WebChannelFactory<T> factory =
new WebChannelFactory<T>(binding, new Uri(url));
ClientCredentials credentials = factory.Credentials;
credentials.UserName.UserName = userName;
credentials.UserName.Password = password;
T proxy = factory.CreateChannel();
return proxy;
}
}
So that I can use it as follows:
IMyRestService proxy = WebProxyFactory.Create<IMyRestService>(url, usr, pwd);
var result = proxy.GetSomthing(); // Fails right here
For this to work with Forms Authentication, I had to physically override the Authentication headers as follows:
var proxy = WebProxyFactory.Create<ITitleWorldService>(url, userName, password);
using (new OperationContextScope((IContextChannel)proxy))
{
var authorizationToken = GetBasicAuthorizationToken(userName, password);
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = authorizationToken;
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
//var response = proxy.DoWork();
Console.WriteLine(proxy.SayHello());
}

Categories