/// <summary> /// Updates the storage properties of the policy that this object operates on /// </summary> private void UpdateEventTypes(AuditingPolicy wrappedPolicy, DatabaseSecurityPolicyProperties properties) { string[] userEnteredEventType = wrappedPolicy.EventType; if (userEnteredEventType == null || userEnteredEventType.Length == 0) { return; } HashSet <String> eventTypes = new HashSet <String>(userEnteredEventType); if (!ValidateShortcutUsage(eventTypes, Constants.All)) { throw new Exception(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidEventTypeSet, Constants.All)); } if (!ValidateShortcutUsage(eventTypes, Constants.None)) { throw new Exception(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidEventTypeSet, Constants.None)); } properties.IsEventTypeDataAccessEnabled = ValueOfProperty(eventTypes, Constants.Access); properties.IsEventTypeSchemaChangeEnabled = ValueOfProperty(eventTypes, Constants.Schema); properties.IsEventTypeDataChangesEnabled = ValueOfProperty(eventTypes, Constants.Data); properties.IsEventTypeSecurityExceptionsEnabled = ValueOfProperty(eventTypes, Constants.Security); properties.IsEventTypeGrantRevokePermissionsEnabled = ValueOfProperty(eventTypes, Constants.RevokePermissions); // we need to re-add the event types to the AuditingPolicy object to replace the All / None with the real values if (userEnteredEventType.Contains(Constants.All) || userEnteredEventType.Contains(Constants.None)) { AddEventTypesToWrapperFromPolicy(wrappedPolicy, properties); } }
private void AddConnectionStringsToWrapperFromPolicy(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { wrapper.ConnectionStrings.AdoNetConnectionString = ConstructAdoNetConnectionString(wrapper, properties); wrapper.ConnectionStrings.OdbcConnectionString = ConstructOdbcConnectionString(wrapper, properties); wrapper.ConnectionStrings.JdbcConnectionString = ConstructJdbcConnectionString(wrapper, properties); wrapper.ConnectionStrings.PhpConnectionString = ConstructPhpConnectionString(wrapper, properties); }
private void AddEventTypesToWrapperFromPolicy(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { HashSet <string> events = new HashSet <string>(); if (properties.IsEventTypeDataAccessEnabled) { events.Add(Constants.Access); } if (properties.IsEventTypeDataChangesEnabled) { events.Add(Constants.Data); } if (properties.IsEventTypeSchemaChangeEnabled) { events.Add(Constants.Schema); } if (properties.IsEventTypeGrantRevokePermissionsEnabled) { events.Add(Constants.RevokePermissions); } if (properties.IsEventTypeSecurityExceptionsEnabled) { events.Add(Constants.Security); } wrapper.EventType = events.ToArray(); }
private string ConstructPhpConnectionString(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { string enterUser = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterUserId; string enterPassword = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterPassword; string pdoTitle = Microsoft.Azure.Commands.Sql.Properties.Resources.PdoTitle; string sqlServerSampleTitle = Microsoft.Azure.Commands.Sql.Properties.Resources.sqlSampleTitle; string connectionError = Microsoft.Azure.Commands.Sql.Properties.Resources.PhpConnectionError; StringBuilder sb = new StringBuilder(); sb.Append(string.Format("Server: {0}, {1}", properties.ProxyDnsName, properties.ProxyPort)).Append(Environment.NewLine); sb.Append(string.Format("SQL Database: {0}", wrapper.DatabaseName)).Append(Environment.NewLine); sb.Append(string.Format("User Name: {0}", enterUser)).Append(Environment.NewLine).Append(Environment.NewLine); sb.Append(pdoTitle).Append(Environment.NewLine); sb.Append("try{").Append(Environment.NewLine); sb.Append(string.Format("$conn = new PDO ( \"sqlsrv:server = tcp:{0},{1}; Database = \"{2}\", \"{3}\", \"{4}\");", properties.ProxyDnsName, properties.ProxyPort, wrapper.DatabaseName, enterUser, enterPassword)).Append(Environment.NewLine); sb.Append("$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );").Append(Environment.NewLine); sb.Append("}").Append(Environment.NewLine); sb.Append("catch ( PDOException $e ) {").Append(Environment.NewLine); sb.Append(string.Format("print( \"{0}\" );", connectionError)).Append(Environment.NewLine); sb.Append("die(print_r($e));").Append(Environment.NewLine); sb.Append("}").Append(Environment.NewLine); sb.Append(sqlServerSampleTitle).Append(Environment.NewLine).Append(Environment.NewLine); sb.Append(string.Format("connectionInfo = array(\"UID\" => \"{0}@{1}\", \"pwd\" => \"{2}\", \"Database\" => \"{3}\", \"LoginTimeout\" => 30, \"Encrypt\" => 1);", enterUser, wrapper.ServerName, enterPassword, wrapper.DatabaseName)).Append(Environment.NewLine); sb.Append(string.Format("$serverName = \"tcp:{0},{1}\";", properties.ProxyDnsName, properties.ProxyPort)).Append(Environment.NewLine); sb.Append("$conn = sqlsrv_connect($serverName, $connectionInfo);"); return(sb.ToString()); }
/// <summary> /// Updates the storage properties of the policy that this object operates on /// </summary> private void UpdateStorage(string storageAccountName, DatabaseSecurityPolicyProperties properties) { if (storageAccountName != null) { properties.StorageAccountName = storageAccountName; } if (string.IsNullOrEmpty(properties.StorageAccountName) && (!IgnoreStorage)) // can happen if the user didn't provide account name for a policy that lacked it { throw new Exception(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.NoStorageAccountWhenConfiguringAuditingPolicy)); } // no need to do time consuming http inteaction to fetch these properties if the storage account was not changed if (properties.StorageAccountName == this.FetchedProperties.StorageAccountName) { properties.StorageAccountResourceGroupName = this.FetchedProperties.StorageAccountResourceGroupName; properties.StorageAccountSubscriptionId = this.FetchedProperties.StorageAccountSubscriptionId; properties.StorageTableEndpoint = this.FetchedProperties.StorageTableEndpoint; } else { properties.StorageAccountSubscriptionId = Subscription.Id.ToString(); properties.StorageAccountResourceGroupName = Communicator.GetStorageResourceGroup(properties.StorageAccountName); properties.StorageTableEndpoint = Communicator.GetStorageTableEndpoint(properties.StorageAccountName); } if (!IgnoreStorage) { // storage primary key is not sent when fetching the policy, so if it is needed, it should be fetched properties.StorageAccountKey = Communicator.GetPrimaryStorageKeys(properties.StorageAccountName); } }
private string ConstructAdoNetConnectionString(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { string enterUser = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterUserId; string enterPassword = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterPassword; return(string.Format("Server=tcp:{0},{1};Database={2};User ID={3}@{4};Password={5};Trusted_Connection=False;Encrypt=True;Connection Timeout=30", properties.ProxyDnsName, properties.ProxyPort, wrapper.DatabaseName, enterUser, wrapper.ServerName, enterPassword)); }
private string ConstructJdbcConnectionString(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { string enterUser = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterUserId; string enterPassword = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterPassword; return(string.Format("jdbc:sqlserver://{0}:{1};database={2};user={3}@{4};password={5};encrypt=true;hostNameInCertificate=*.database.secure.windows.net;loginTimeout=30;", properties.ProxyDnsName, properties.ProxyPort, wrapper.DatabaseName, enterUser, wrapper.ServerName, enterPassword)); }
private void addStorageInfoToWrapperFromPolicy(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { wrapper.StorageAccountName = properties.StorageAccountName; if (properties.StorageAccountKey != null) { wrapper.StorageKeyType = Constants.StorageKeyTypes.Primary; // TODO - until we have in prodcution the secondary field - handle as alway primary } if (properties.SecondaryStorageAccountKey != null) { wrapper.StorageKeyType = Constants.StorageKeyTypes.Secondary; } }
private AuditingPolicy WrapPolicy(DatabaseSecurityPolicy policy) { AuditingPolicy wrapper = new AuditingPolicy(); DatabaseSecurityPolicyProperties properties = policy.Properties; wrapper.UseServerDefault = properties.UseServerDefault; wrapper.IsEnabled = properties.IsAuditingEnabled; wrapper.StorageAccountName = properties.StorageAccountName; AddEventTypesToWrapperFromPolicy(wrapper, properties); this.FetchedProperties = properties; return(wrapper); }
private AuditingPolicy WrapPolicy(DatabaseSecurityPolicy policy) { AuditingPolicy wrapper = new AuditingPolicy(); DatabaseSecurityPolicyProperties properties = policy.Properties; wrapper.UseServerDefault = properties.UseServerDefault; wrapper.IsEnabled = properties.IsAuditingEnabled; wrapper.DirectAccessEnabled = !properties.IsBlockDirectAccessEnabled; addStorageInfoToWrapperFromPolicy(wrapper, properties); AddEventTypesToWrapperFromPolicy(wrapper, properties); this.FetchedProperties = properties; return(wrapper); }
private DatabaseSecurityPolicyUpdateParameters UnwrapPolicy(AuditingPolicy policy) { DatabaseSecurityPolicyUpdateParameters updateParameters = new DatabaseSecurityPolicyUpdateParameters(); DatabaseSecurityPolicyProperties properties = new DatabaseSecurityPolicyProperties(); updateParameters.Properties = properties; properties.RetentionDays = 90; properties.IsAuditingEnabled = policy.IsEnabled; properties.UseServerDefault = policy.UseServerDefault; UpdateEventTypes(policy, properties); UpdateStorage(policy.StorageAccountName, properties); return(updateParameters); }
private string ConstructOdbcConnectionString(AuditingPolicy wrapper, DatabaseSecurityPolicyProperties properties) { string enterUser = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterUserId; string enterPassword = Microsoft.Azure.Commands.Sql.Properties.Resources.EnterPassword; StringBuilder sb = new StringBuilder(); sb.Append("Driver={SQL Server Native Client 11.0};"); sb.Append(string.Format("Server=tcp:{0},{1};", properties.ProxyDnsName, properties.ProxyPort)); sb.Append(string.Format("Database={0};", wrapper.DatabaseName)); sb.Append(string.Format("Uid={0}@{1};", enterUser, wrapper.ServerName)); sb.Append(string.Format("Pwd={0};", enterPassword)); sb.Append("Encrypt=yes;Connection Timeout=30;"); return(sb.ToString()); }
/// <summary> /// Gets Azure SQL Database security policy object according to a given /// Azure SQL Database Server and Database. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// Azure SQL Database hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// policy is being retreived. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get Azure SQL Database security policy /// request /// </returns> public async Task <DatabaseSecurityPolicyGetResponse> GetAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databaseSecurityPolicies/"; url = url + Uri.EscapeDataString(databaseName); List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DatabaseSecurityPolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DatabaseSecurityPolicyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DatabaseSecurityPolicy databaseSecurityPolicyInstance = new DatabaseSecurityPolicy(); result.DatabaseSecurityPolicy = databaseSecurityPolicyInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); databaseSecurityPolicyInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DatabaseSecurityPolicyProperties propertiesInstance = new DatabaseSecurityPolicyProperties(); databaseSecurityPolicyInstance.Properties = propertiesInstance; JToken isAuditingEnabledValue = propertiesValue["isAuditingEnabled"]; if (isAuditingEnabledValue != null && isAuditingEnabledValue.Type != JTokenType.Null) { bool isAuditingEnabledInstance = ((bool)isAuditingEnabledValue); propertiesInstance.IsAuditingEnabled = isAuditingEnabledInstance; } JToken retentionDaysValue = propertiesValue["retentionDays"]; if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null) { int retentionDaysInstance = ((int)retentionDaysValue); propertiesInstance.RetentionDays = retentionDaysInstance; } JToken isEventTypeDataAccessEnabledValue = propertiesValue["isEventTypeDataAccessEnabled"]; if (isEventTypeDataAccessEnabledValue != null && isEventTypeDataAccessEnabledValue.Type != JTokenType.Null) { bool isEventTypeDataAccessEnabledInstance = ((bool)isEventTypeDataAccessEnabledValue); propertiesInstance.IsEventTypeDataAccessEnabled = isEventTypeDataAccessEnabledInstance; } JToken isEventTypeSchemaChangeEnabledValue = propertiesValue["isEventTypeSchemaChangeEnabled"]; if (isEventTypeSchemaChangeEnabledValue != null && isEventTypeSchemaChangeEnabledValue.Type != JTokenType.Null) { bool isEventTypeSchemaChangeEnabledInstance = ((bool)isEventTypeSchemaChangeEnabledValue); propertiesInstance.IsEventTypeSchemaChangeEnabled = isEventTypeSchemaChangeEnabledInstance; } JToken isEventTypeDataChangesEnabledValue = propertiesValue["isEventTypeDataChangesEnabled"]; if (isEventTypeDataChangesEnabledValue != null && isEventTypeDataChangesEnabledValue.Type != JTokenType.Null) { bool isEventTypeDataChangesEnabledInstance = ((bool)isEventTypeDataChangesEnabledValue); propertiesInstance.IsEventTypeDataChangesEnabled = isEventTypeDataChangesEnabledInstance; } JToken isEventTypeSecurityExceptionsEnabledValue = propertiesValue["isEventTypeSecurityExceptionsEnabled"]; if (isEventTypeSecurityExceptionsEnabledValue != null && isEventTypeSecurityExceptionsEnabledValue.Type != JTokenType.Null) { bool isEventTypeSecurityExceptionsEnabledInstance = ((bool)isEventTypeSecurityExceptionsEnabledValue); propertiesInstance.IsEventTypeSecurityExceptionsEnabled = isEventTypeSecurityExceptionsEnabledInstance; } JToken isEventTypeGrantRevokePermissionsEnabledValue = propertiesValue["isEventTypeGrantRevokePermissionsEnabled"]; if (isEventTypeGrantRevokePermissionsEnabledValue != null && isEventTypeGrantRevokePermissionsEnabledValue.Type != JTokenType.Null) { bool isEventTypeGrantRevokePermissionsEnabledInstance = ((bool)isEventTypeGrantRevokePermissionsEnabledValue); propertiesInstance.IsEventTypeGrantRevokePermissionsEnabled = isEventTypeGrantRevokePermissionsEnabledInstance; } JToken storageAccountNameValue = propertiesValue["storageAccountName"]; if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null) { string storageAccountNameInstance = ((string)storageAccountNameValue); propertiesInstance.StorageAccountName = storageAccountNameInstance; } JToken storageAccountKeyValue = propertiesValue["storageAccountKey"]; if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null) { string storageAccountKeyInstance = ((string)storageAccountKeyValue); propertiesInstance.StorageAccountKey = storageAccountKeyInstance; } JToken secondaryStorageAccountKeyValue = propertiesValue["secondaryStorageAccountKey"]; if (secondaryStorageAccountKeyValue != null && secondaryStorageAccountKeyValue.Type != JTokenType.Null) { string secondaryStorageAccountKeyInstance = ((string)secondaryStorageAccountKeyValue); propertiesInstance.SecondaryStorageAccountKey = secondaryStorageAccountKeyInstance; } JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"]; if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null) { string storageTableEndpointInstance = ((string)storageTableEndpointValue); propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance; } JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"]; if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null) { string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue); propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance; } JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"]; if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null) { string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue); propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance; } JToken proxyDnsNameValue = propertiesValue["proxyDnsName"]; if (proxyDnsNameValue != null && proxyDnsNameValue.Type != JTokenType.Null) { string proxyDnsNameInstance = ((string)proxyDnsNameValue); propertiesInstance.ProxyDnsName = proxyDnsNameInstance; } JToken proxyPortValue = propertiesValue["proxyPort"]; if (proxyPortValue != null && proxyPortValue.Type != JTokenType.Null) { string proxyPortInstance = ((string)proxyPortValue); propertiesInstance.ProxyPort = proxyPortInstance; } JToken useServerDefaultValue = propertiesValue["useServerDefault"]; if (useServerDefaultValue != null && useServerDefaultValue.Type != JTokenType.Null) { bool useServerDefaultInstance = ((bool)useServerDefaultValue); propertiesInstance.UseServerDefault = useServerDefaultInstance; } JToken isBlockDirectAccessEnabledValue = propertiesValue["isBlockDirectAccessEnabled"]; if (isBlockDirectAccessEnabledValue != null && isBlockDirectAccessEnabledValue.Type != JTokenType.Null) { bool isBlockDirectAccessEnabledInstance = ((bool)isBlockDirectAccessEnabledValue); propertiesInstance.IsBlockDirectAccessEnabled = isBlockDirectAccessEnabledInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); databaseSecurityPolicyInstance.Id = idInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); databaseSecurityPolicyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); databaseSecurityPolicyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); databaseSecurityPolicyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }