Actualización de grupos de seguridad - AWS SDK for .NET

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Actualización de grupos de seguridad

En este ejemplo, se muestra cómo utilizar la AWS SDK for .NET para añadir una regla a un grupo de seguridad. En concreto, el ejemplo agrega una regla para permitir el tráfico entrante en un determinado puerto TCP, que se puede usar, por ejemplo, en las conexiones remotas a una instancia de EC2. La aplicación toma el ID de un grupo de seguridad existente, una dirección IP (o un intervalo de direcciones) en formato CIDR y, opcionalmente, un número de puerto TCP. A continuación, agrega una regla de entrada al grupo de seguridad en cuestión.

nota

Para usar este ejemplo, necesita una dirección IP (o un intervalo de direcciones) en formato CIDR. Consulte la sección Consideraciones adicionales al final de este tema para conocer los métodos con los que obtener la dirección IP del equipo local.

En las siguientes secciones se proporcionan fragmentos de código de este ejemplo. Tras ello, se muestra el código completo del ejemplo, que se puede compilar y ejecutar tal cual.

Adición de una regla de entrada

El siguiente fragmento de código agrega una regla de entrada a un grupo de seguridad para una dirección IP (o intervalo de direcciones) y un puerto TCP determinados.

El ejemplo que aparece al final de este tema muestra este fragmento de código en uso.

// // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); }

Código completo

En esta sección se muestran las referencias relevantes y el código completo de este ejemplo.

NuGet paquetes:

Elementos de programación:

using System; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2AddRuleForRDP { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to add a rule that allows inbound traffic on TCP a port class Program { private const int DefaultPort = 3389; static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if(parsedArgs.Count == 0) { PrintHelp(); return; } // Get the application arguments from the parsed list var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id"); var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address"); var portStr = CommandLine.GetArgument(parsedArgs, DefaultPort.ToString(), "-p", "--port"); if(string.IsNullOrEmpty(ipAddress)) CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format."); if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-")) CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect."); if(int.Parse(portStr) == 0) CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed."); // Add a rule to the given security group that allows // inbound traffic on a TCP port await AddIngressRule( new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr)); } // // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" + "\n -g, --group-id: The ID of the security group to which you want to add the inbound rule." + "\n -i, --ip-address: An IP address or address range in CIDR format." + "\n -p, --port: The TCP port number. Defaults to 3389."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class that represents a command line on the console or terminal. // (This is the same for all examples. When you have seen it once, you can ignore it.) static class CommandLine { // // Method to parse a command line of the form: "--key value" or "-k value". // // Parameters: // - args: The command-line arguments passed into the application by the system. // // Returns: // A Dictionary with string Keys and Values. // // If a key is found without a matching value, Dictionary.Value is set to the key // (including the dashes). // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN", // where "N" represents sequential numbers. public static Dictionary<string,string> Parse(string[] args) { var parsedArgs = new Dictionary<string,string>(); int i = 0, n = 0; while(i < args.Length) { // If the first argument in this iteration starts with a dash it's an option. if(args[i].StartsWith("-")) { var key = args[i++]; var value = key; // Check to see if there's a value that goes with this option? if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++]; parsedArgs.Add(key, value); } // If the first argument in this iteration doesn't start with a dash, it's a value else { parsedArgs.Add("--NoKey" + n.ToString(), args[i++]); n++; } } return parsedArgs; } // // Method to get an argument from the parsed command-line arguments // // Parameters: // - parsedArgs: The Dictionary object returned from the Parse() method (shown above). // - defaultValue: The default string to return if the specified key isn't in parsedArgs. // - keys: An array of keys to look for in parsedArgs. public static string GetArgument( Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? defaultReturn; } // // Method to exit the application with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

Consideraciones adicionales

  • Si no se indica un número de puerto, la aplicación lo establece de forma predeterminada en 3389, que es el puerto de Windows RDP, con el que puede conectarse a una instancia de EC2 donde se ejecute Windows. En cambio, si lanza una instancia de EC2 que ejecuta Linux, utilice el puerto TCP 22 (SSH).

  • Observe que, en el ejemplo, IpProtocol está establecido en “tcp”. Los valores de IpProtocol se encuentran en la descripción de la IpProtocol propiedad de la IpPermissionclase.

  • Es conveniente que tenga la dirección IP de su equipo local cuando utilice este ejemplo. Estas son algunas formas de obtener la dirección.

    • Si el equipo local (desde el que se conectará a la instancia de EC2) tiene una dirección IP pública estática, puede utilizar un servicio para obtener esa dirección. Uno de estos servicios es http://checkip.amazonaws.com/. Para obtener más información sobre la autorización del tráfico entrante, consulte Añadir reglas a un grupo de seguridad y Reglas de grupos de seguridad para diferentes casos de uso en la Guía del usuario de Amazon EC2.

    • Otra forma de obtener la dirección IP del equipo local consiste en utilizar la consola de Amazon EC2.

      Seleccione uno de sus grupos de seguridad, seleccione la pestaña Reglas de entrada y, luego, seleccione Editar reglas de entrada. En una regla de entrada, abra el menú desplegable de la columna Origen y seleccione Mi IP para ver la dirección IP de su equipo local en formato CIDR. Asegúrese de cancelar la operación.

  • Para comprobar los resultados de este ejemplo, puede examinar la lista de grupos de seguridad en la consola de Amazon EC2.