Cifrado y descifrado simétrico con Rijndael (AES) utilizando C#/Mono

Cifrado y descifrado simétrico con Rijndael (AES) utilizando C#/Mono – Jorge Iván Meza Martínez

Introducción.

Advanced Encryption Standard (AES), también conocido como Rijndael (pronunciado “Rain Doll” en inglés), es un esquema de cifrado por bloques adoptado como un estándar de cifrado por el gobierno de los Estados Unidos. El AES fue anunciado por el Instituto Nacional de Estándares y Tecnología (NIST) como FIPS PUB 197 de los Estados Unidos (FIPS 197) el 26 de noviembre de 2001 después de un proceso de estandarización que duró 5 años.  Se transformó en un estándar efectivo el 26 de mayo de 2002. Desde 2006, el AES es uno de los algoritmos más populares usados en criptografía simétrica.

El cifrador fue desarrollado por dos criptólogos belgas, Joan Daemen y Vincent Rijmen, ambos estudiantes de la Katholieke Universiteit Leuven, y enviado al proceso de selección AES bajo el nombre “Rijndael”.

Tomado del artículo Advanced Encryption Standard de Wikipedia.

Implementación con strings.

La aplicación de demostración de esta técnica requiere del uso de por lo menos los siguientes namespaces.

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

Establecer la clave y el vector de inicio.

Estos valores pueden ser especificados manualmente o de manera automática por el framework.  La implementación para permitir que se definan automáticamente estos valores es la siguiente.

Rijndael rijndael = Rijndael.Create();
byte[] key = rijndael.Key;
byte[] iv  = rijndael.IV;

Es posible forzar la generación de nuevas claves y nuevos vectores de inicio para el algoritmo utilizando los métodos rijndael.GenerateKey() y rijndael.GenerateIV() respectivamente.

Si por el contrario se desea especificar estos valores manualmente su implementación es la siguiente siendo strKey y strIv, la clave y el vector de inicialización como cadenas de texto.

byte[] key = UTF8Encoding.UTF8.GetBytes(strKey);
byte[] iv  = UTF8Encoding.UTF8.GetBytes(strIv);

Especificando estos valores manualmente es necesario garantizar que sus longitudes sean válidas para el algoritmo.  En este caso se utilizará una longitud de clave de 32 bits y una longitud de vector de inicio de 16 bits.

int keySize = 32;
int ivSize = 16;

Array.Resize(ref key, keySize);
Array.Resize(ref iv, ivSize);

Cifrado de cadenas de texto.

Para cifrar la información se requiere de los siguientes parámetros.

  1. Cadena de texto con los datos a cifrar.
  2. Clave.
  3. Vector de inicio.

El proceso retornará finalmente una cadena de texto con los datos cifrados.

/**
 * Cifra una cadena texto con el algoritmo de Rijndael
 *
 * @param	plainMessage	mensaje plano (sin cifrar)
 * @param	Key		        clave del cifrado para Rijndael
 * @param	IV		        vector de inicio para Rijndael
 * @return	string		        texto cifrado
 */

public static string encryptString(String plainMessage, byte[] Key, byte[] IV)
{
    // Crear una instancia del algoritmo de Rijndael

    Rijndael RijndaelAlg = Rijndael.Create();

    // Establecer un flujo en memoria para el cifrado

    MemoryStream memoryStream = new MemoryStream();

    // Crear un flujo de cifrado basado en el flujo de los datos

    CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                 RijndaelAlg.CreateEncryptor(Key, IV),
                                                 CryptoStreamMode.Write);

    // Obtener la representación en bytes de la información a cifrar

    byte[] plainMessageBytes = UTF8Encoding.UTF8.GetBytes(plainMessage);

    // Cifrar los datos enviándolos al flujo de cifrado

    cryptoStream.Write(plainMessageBytes, 0, plainMessageBytes.Length);

    cryptoStream.FlushFinalBlock();

    // Obtener los datos datos cifrados como un arreglo de bytes

    byte[] cipherMessageBytes = memoryStream.ToArray();

    // Cerrar los flujos utilizados

    memoryStream.Close();
    cryptoStream.Close();

    // Retornar la representación de texto de los datos cifrados

    return Convert.ToBase64String(cipherMessageBytes);
}

Descifrado de cadenas de texto.

El proceso inverso, el de descifrado, se realiza de manera antagónica.  Para hacerlo es necesario contar con los siguientes parámetros.

  1. Cadena de texto con los datos cifrados.
  2. Clave.
  3. Vector de inicio.

El proceso retornará finalmente una cadena de texto con los datos descifrados.

/**
 * Descifra una cadena texto con el algoritmo de Rijndael
 *
 * @param	encryptedMessage	mensaje cifrado
 * @param	Key			clave del cifrado para Rijndael
 * @param	IV			vector de inicio para Rijndael
 * @return	string			texto descifrado (plano)
 */

public static string decryptString(String encryptedMessage, byte[] Key, byte[] IV)
{
    // Obtener la representación en bytes del texto cifrado

    byte[] cipherTextBytes = Convert.FromBase64String(encryptedMessage);

    // Crear un arreglo de bytes para almacenar los datos descifrados

    byte[] plainTextBytes = new byte[cipherTextBytes.Length];

    // Crear una instancia del algoritmo de Rijndael

    Rijndael RijndaelAlg = Rijndael.Create();

    // Crear un flujo en memoria con la representación de bytes de la información cifrada

    MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

    // Crear un flujo de descifrado basado en el flujo de los datos

    CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                 RijndaelAlg.CreateDecryptor(Key, IV),
                                                 CryptoStreamMode.Read);

    // Obtener los datos descifrados obteniéndolos del flujo de descifrado

    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

    // Cerrar los flujos utilizados

    memoryStream.Close();
    cryptoStream.Close();

    // Retornar la representación de texto de los datos descifrados

    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}

Implementación con archivos.

El cifrado y descifrado de mensajes en archivos se realiza de manera similar al expuesto anteriormente con cadenas, sin embargo varían los flujos (streams) utilizados para obtener y dirigir el flujo de la información.

Cifrado a archivos.

/**
 * Cifra una cadena texto con el algoritmo de Rijndael y lo almacena en un archivo
 *
 * @param	plainMessage	mensaje plano (sin cifrar)
 * @param	filename	        nombre del archivo donde se almacenará el mensaje cifrado
 * @param	Key		        clave del cifrado para Rijndael
 * @param	IV		        vector de inicio para Rijndael
 * @return	void
 */

public static void encryptToFile(String plainMessage, String filename, byte[] Key, byte[] IV)
{
    // Crear un flujo para el archivo a generarse

    FileStream fileStream = File.Open(filename, FileMode.OpenOrCreate);

    // Crear una instancia del algoritmo Rijndael

    Rijndael RijndaelAlg = Rijndael.Create();

    // Crear un flujo de cifrado basado en el flujo de los datos

    CryptoStream cryptoStream = new CryptoStream(fileStream,
                                                 RijndaelAlg.CreateEncryptor(Key, IV),
                                                 CryptoStreamMode.Write);

    // Crear un flujo de escritura basado en el flujo de cifrado

    StreamWriter streamWriter = new StreamWriter(cryptoStream);

    // Cifrar el mensaje a través del flujo de escritura

    streamWriter.WriteLine(plainMessage);

    // Cerrar los flujos utilizados

    streamWriter.Close();
    cryptoStream.Close();
    fileStream.Close();
}

Descifrado de archivos.

/**
 * Descifra el contenido de un archivo con el algoritmo de Rijndael y lo retorna
 * como una cadena de texto plano
 *
 * @param	filename		nombre del archivo donde se encuentra el mensaje cifrado
 * @param	Key			clave del cifrado para Rijndael
 * @param	IV			vector de inicio para Rijndael
 * @return	string			mensaje descifrado (plano)
 */

public static string decryptFromFile(String filename, byte[] Key, byte[] IV)
{
    // Crear un flujo para el archivo a generarse

    FileStream fileStream = File.Open(filename, FileMode.OpenOrCreate);

    // Crear una instancia del algoritmo Rijndael

    Rijndael RijndaelAlg = Rijndael.Create();

    // Crear un flujo de cifrado basado en el flujo de los datos

    CryptoStream cryptoStream = new CryptoStream(fileStream,
                                                 RijndaelAlg.CreateDecryptor(Key, IV),
                                                 CryptoStreamMode.Read);

    // Crear un flujo de lectura basado en el flujo de cifrado

    StreamReader streamReader = new StreamReader(cryptoStream);

    // Descifrar el mensaje a través del flujo de lectura

    string plainMessage = streamReader.ReadLine();

    // Cerrar los flujos utilizados

    streamReader.Close();
    cryptoStream.Close();
    fileStream.Close();

    return plainMessage;
}

   Cifrado y descifrado simétrico con Rijndael (AES) utilizando C#/Mono – Jorge Iván Meza Martínez 

Aplicación de demostración.

La aplicación de demostración incluye los conceptos y el código expuestos en este artículo.  Con ella es posible cifrar y descifrar un mensaje que consiste en una cadena de texto arbitraria en memoria y en un archivo.

Aplicación de demostración del uso del algoritmo Rijndael
Aplicación de demostración del uso del algoritmo Rijndael

Construír la aplicación.

La aplicación de demostración puede construírse utilizando la solución incluída en la distribución con MonoDevelop o Visual Studio.  También es posible construírla desde línea de comando (Mono) mediante la siguiente instrucción.

$ gmcs “/out:RijndaelSample.exe” “/r:/usr/lib/mono/2.0/System.dll” /t:exe “RijndaelSample/Main.cs”

Enlaces.

Cifrado y descifrado simétrico con Rijndael (AES) utilizando C#/Mono

Syncing Filezilla sitemanager.xml across multiple computers

So, I am using several computers and want to sync my filezilla sitemanager.xml across all platforms using a cloud service (example Dropbox).

1. Find your site manager file

Filezilla keeps all of your sites and access credentials in an XML file called “sitemanager.xml”
Windows 7/8 & Vista – C:\Users\YourUserName\AppData\Roaming\FileZilla\sitemanager.xml
Mac OSX – /users/YourUserName/.config/filezilla/sitemanager.xml
Linux – /home/YourUserName/.filezilla/sitemanager.xml

2. Make a backup copy of the sitemanager.xml in case you mess it up

3. Find a nice location for your shared sitemanager.xml file in your preferred cloud service, and copy it over
example: \Dropbox\Settings\sitemanager.xml

4. Make a “softlink” to your shared sitemanager.xml
You will need to use COMMAND PROMPT (Windows), or TERMINAL (Linux and OSX) for this.

Windows:
mklink “C:\Users\YourUserName\AppData\Roaming\FileZilla\sitemanager.xml” “C:\Users\YourUserName\Dropbox\Settings\sitemanager.xml”

OS X:
ln -s /users/YourUserName/Dropbox/Settings/sitemanager.xml /users/YourUserName/.config/filezilla/sitemanager.xml

Linux:
ln -s /home/YourUserName/Dropbox/Settings/sitemanager.xml /home/YourUserName/.filezilla/sitemanager.xml

The du Command

The du (i.e., disk usage) command reports the sizes of directory trees inclusive of all of their contents and the sizes of individual files. This makes it useful for tracking down space hogs, i.e., directories and files that consume large or excessive amounts of space on a hard disk drive (HDD) or other storage media.

A directory tree is a hierarchy of directories that consists of a single directory, called the parent directory or top level directory, and all levels of its subdirectories (i.e., directories within a directory). Any directory can be regarded as being the start of its own directory tree, at least if it contains subdirectories. Thus, a typical computer contains a large number of directory trees.

du is commonly employed by system administrators as a supplement to automated monitoring and notification programs that help prevent key directories and partitions (i.e., logically independent sections of a HDD) from becoming full. Full, or even nearly full, directories and partitions can cause a system to slow down, prevent users from logging in and even result in a system crash. Although visually identifying heavy consumers of disk space can be practical if there are relatively few users on a system, it is clearly not efficient for large systems with hundreds or thousands of users.

A minor limitation of du is the fact that the sizes of directories and files it reports are approximations, not exact numbers, and there is frequently a small discrepancy between these sizes and the sizes reported by other commands. However, this rarely detracts from its usefulness.

Also, du can only be used to estimate space consumption for directories and files for which the user has reading permission. Thus, an ordinary user would generally not be able to use du to determine space consumption for files or directories belonging to other users, including those belonging to the root account (i.e., the system administrator). However, as du is used mainly by system administrators, this is usually not a problem.

Syntax

The basic syntax for du is:

du [options] [directories and/or files]

The items in the square brackets are optional. When used with no options or arguments (i.e., names of directories or files), du lists the names and space consumption of each of the directories (including all levels of subdirectories) in the directory tree that begins with the current directory (i.e., the directory in which the user is currently working). The space consumption of any directory consists of the space occupied by all of the files in it and all of its subdirectories at all levels inclusive of all of the files in them. A final line at the end of the report gives the total space consumption for the directory tree.

du can provide information about any directory trees or files on the system whose names are given as arguments. For example, the following will report the names and sizes for each directory in the directory tree that begins with a directory named directory2 that resides in a directory named directory1, which, in turn, is located in the current directory:

du directory1/directory2

Likewise, the following will report the sizes of the two files named file1 and file2 that are located in the /sbin directory (which contains executable programs):

du /sbin/file1 /sbin/file2

du can accept any number of arguments, and they can be any combination of files and directories. When there are multiple arguments, no grand total is provided by default, although a total is still provided for each argument.

Options

As is the case with most commands on Linux and other Unix-like operating systems, du has a number of options, a few of which are commonly used. The options can vary somewhat according to the particular operating system and the version of du.

One of the most useful options is -h (i.e., human readable), which can make the output easier to read by displaying it in kilobytes (K), megabytes (M) and gigabytes (G) rather than just in the default kilobytes. Thus, the following command can be used to show the sizes of all the subdirectories in the current directory as well as the total size of the current directory, all formatted with the appropriate K, M or G:

du -h

The -s (for suppress or summarize) option tells du to report only the total disk space occupied by a directory tree and to suppress individual reports for its subdirectories. Thus, for example, the following would provide the total disk space occupied by the current directory in an easy-to-read format:

du -sh

The output is the same as the last line of a report issued by du with only the -h option.

The -a (i.e., all) option tells du to report not just the total disk usage for each directory at every level in a directory tree but also to report the space consumption for each individual file anywhere within the tree. Thus, for example, the following would list the name and size of every directory and file in the /etc directory (which contains system configuration files) for which the user has reading permission:

du -a /etc

A somewhat similar report is provided by using the star ( * ) wildcard, which will match any character or characters. For example, the following command would list the sizes of all directories that are in the tree that begins with the current directory:

du *

However, the only files listed are those in the the parent directory, not those in its subdirectories. Also, no total for the directory tree as a whole is provided.

The use of the -s option and the star wildcard together would cause du to report the names and sizes of only the files and directories contained directly in the top level directory itself (and to not list the names of any of its subdirectories and the files in them). The size of each listed directory is, of course, inclusive of all of its files and subdirectories (including all of the files in them). For example, such a report about the directory tree beginning with the current directory would be provided by the following:

du -hs *

The wildcard can also be used to filter the output to list only those items whose names begin with, contain or end with certain characters or sequences of characters. For example, the following would report the names and sizes of all of the directories and files in the current directory whose names begin with the letter s as well as the names and sizes of all levels of subdirectories of those directories regardless of what their names begin with:

du -h s*

The -c option can be added to provide a grand total for all of the files and directories that are listed. In the case of the above example, this would be

du -hc s*

As another example of the use of the wildcard, the following command would report the name and size of each gif (one of the two most popular image formats) file in the current directory as well as a total for all of the gifs:

du -hc *.gif

Another useful option is --max-depth=, which instructs du to list its subdirectories and their sizes to any desired level of depth (i.e., to any level of subdirectories) in a directory tree. For example, the following would cause du to list only the first tier (i.e., layer) of directories in the current directory and their sizes (inclusive of all of their contents, including those of their subdirectories):

du --max-depth=1

The total space consumption for the current directory tree will also be reported, and it will, of course, be the same regardless of the depth of the files listed.

Setting --max-depth= to zero tells du to not list any of the subdirectories within the selected directory, i.e., to list only report the size of the selected directory itself. The result is the same as using the -s option.

Using du With Filters

As is the case with other commands on Unix-like operating systems, du can be linked with pipes to filters to create powerful pipelines of commands. A filter is a (usually) small and specialized program that transforms data in some meaningful way.

For example, to arrange the output items according to size, du can be piped to the sort command, whose -n option tells it to list the output in numeric order with the smallest files first, as follows:

du | sort -n

As du will often generate more output than can fit on the monitor screen at one time, the output will fly by at high speed and be virtually unreadable. Fortunately, it is easy to display the output one screenful at a time by piping it to the less filter, for example,

du -h | less

The output of less can be advanced one screenful at a time by pressing the space bar, and it can be moved backward one screenful at a time by pressing the b key.

The output of du can likewise be piped to less after it has been passed through one or more other filters, for example,

du -h | sort -n | less

The grep filter can be used to search through du's output for any desired string (i.e., sequence of characters). Thus, for example, the following will provide a list of the names and sizes of directories and files in the current directory that contain the word linux:

du -ah | grep linux

One way in which du can be used to produce a list of (mostly) directories and files in a directory tree that are consuming large amounts of disk space is to use grep to search for all the lines that contain the upper case letter M (i.e., for megabytes) or G (for gigabytes), such as

du -ah | grep M

The only problem with this approach is that it will also select directories and files that contain an upper case M or G in their names even if the file size is not measured in megabytes or gigabytes. (However, this problem could be overcome through the use of regular expressions, an advanced pattern matching technique).

Alternatives to du

There are several other ways of monitoring disk space consumption and reporting file sizes. Although very useful tools, they are generally not good substitutes for du.

Among them is the df command, which is likewise used by system administrators to monitor disk usage. However, unlike du, it can only show the space consumption on entire partitions, and it lacks du's fine-grained ability to track the space usage of individual directories and files.

du is not designed to show the space consumption of partitions. The closest that it can come is to show the sizes of the first tier of directories in the root directory (i.e., the directory which contains all other directories and which is represented by a forward slash), several of which may be on their own partitions (depending on how the system has been set up). This is accomplished by becoming the root user and issuing the following command:

du -h --max-depth=1 /

The ls (i.e., list) command can provide the sizes of individual files by using its -s option, and its -h option (which is similar to du's -h option) can be added to make the output easier to read. For example, the following would list the names and sizes of the files in the current directory:

ls -sh

Although the names of the first tier of directories within the current directory are also listed, the size data accompanying them does not represent their actual disk space consumption (i.e., inclusive of their contents). Nor does ls report the contents of any lower tiers of directories, unless such directories are specifically listed as arguments.

A convenient alternative for finding the sizes of files and directory trees when using a GUI (graphical user interface) is to click with the right mouse button on the icon (i.e., a small picture or symbol) for that item and then select Properties from the menu that appears. Although this is frequently sufficient, it does not provide the detailed control and reporting that du provides.

DU (ABREVIATURA DE DISK USAGE, USO DE DISCO) ES UN COMANDO ESTÁNDAR DE LOS SISTEMAS OPERATIVOS DE LA FAMILIA UNIX. SE USA PARA ESTIMAR EL USO DE ESPACIO EN DISCO DURO DE UN ARCHIVO, UN DIRECTORIO EN PARTICULAR O DE ARCHIVOS EN UN SISTEMA DE ARCHIVOS. LA UTILIDAD DU APARECIÓ POR PRIMERA VEZ EN LA VERSIÓN 1 DEL UNIX DE AT&T

Examples:

$ du -sm *

Return

$ du -sm *
1172    Descargas
68855   Documentos
4084    Escritorio
22270   Imágenes
174192  Linux
50887   Música
3088    Proyectos
1379    Trabajo
219515  Videos

$ du -bsh Videos/

Return:

du -bsh Videos/
215G    Videos/

Si sólo quisiéramos ver cuáles son, por ejemplo, los 5 directorios más pesados en nuestro /home podríamos usa du con una serie de comandos extras, por ejemplo:

$ du -sm * | sort -nr | head -5

Lo cual devolvería:

$ du -sm * | sort -nr | head -5
219515  Videos
174192  Linux
68855   Documentos
50887   Música
22270   Imágenes

Pero los valores que nos devuelven no son “tan humanos” pues están representados en MB y son más engorrosos de entender. Es por ello que ejecutamos:

$ du -hs * | sort -nr | head -5

Replace webmin self-signed certificate to avoid sec_error_invalid_key error

Recent browser versions (e.g. Firefox 33) refuse to work with older Webmin installs.

They give a sec_error_invalid_key error, offer a 'Try again' button, but do not offer an option to add an exception.

Firefox 33 no longer supports certificates with private keys smaller than 1024 bits.

You can replace your webmin certificate with a new one by running this command:

file=/etc/webmin/miniserv.pem
openssl req -x509 -newkey rsa:2048 -keyout $file  -out $file 
 -days 3650 -nodes -subj 
 "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" 
openssl x509 -x509toreq -in $file -signkey $file >> $file
/etc/init.d/webmin restart

This command will create a 'pem' file with both the private key and self-signed certificate in the same file.  -nodes will let you create the file without a passphrase.  The -subj option saves you having to manually enter certificate details.

Or you can do it by setting ssl=0 in /etc/webmin/miniserv.conf; restarting webmin with "/etc/init.d/webmin restart" then using the web interface to make the certificate change at Webmin -> Webmin Configuration -> SSL Encryption -> Self Signed Certificate

Configurar Gmail en Outlook, en Apple Mail o en otros clientes de correo electrónico

Puedes descargarte mensajes de Gmail y verlos con otro programa (Microsoft Outlook, Apple Mail, Thunderbird, etc.) aunque no estés conectado a Internet. Este procedimiento se conoce como POP o IMAP, y es gratuito para todos los usuarios de Gmail.

Consejo: Te recomendamos que uses IMAP siempre que sea posible, pues te garantiza que puedas ver todo tu correo cuando quieras y en todos tus dispositivos. Si prefieres utilizar POP, lee las instrucciones para habilitar POP.

Paso 1: Habilita IMAP

Puedes recuperar tus mensajes de Gmail a través de un cliente o dispositivo que sea compatible con el acceso IMAP, como son Microsoft Outlook y Apple Mail.

Inicia sesión en Gmail.
Haz clic en el icono de la rueda dentada de la esquina superior derecha y selecciona Configuración.
Haz clic en Reenvío y correo POP/IMAP.
Selecciona Habilitar IMAP.
Haz clic en Guardar cambios.
Nota: Este ajuste no está disponible si tienes activada la vista básica en HTML de Gmail. Para habilitar IMAP, tienes que utilizar la vista estándar. Más información sobre la vista estándar y la vista básica en HTML

Paso 2: Configura tu cliente

Consulta la tabla siguiente para configurar tu cliente de correo.

Servidor de correo entrante (IMAP): imap.gmail.com

Requiere SSL: sí

Puerto: 993

Servidor de correo saliente (SMTP): smtp.gmail.com

Utilizar autenticación:

Puerto para SSL: 465 o 587

Utilizar la misma configuración que para el servidor de correo entrante

Nombre completo o Nombre para mostrar: [tu nombre]
Nombre de cuenta o Nombre de usuario: tu dirección de correo electrónico completa (incluido @gmail.com o @tudominio.com)
Dirección de correo electrónico: tu dirección de correo electrónico completa (incluido @gmail.com o @tudominio.com)
Contraseña: tu contraseña de Gmail

Inspeccionando la cola de correos sin entregar en Postfix

Por defecto se reintenta la entrega de los correos cada 5 minutos y se descartan (generando un correo de advertencia al remitente) si no ha podido hacerse transcurridos cinco días del envío. Podemos variar estos valores introduciendo los siguientes parámetros en el fichero de configuración principal (/etc/postfix/main.cf):

1
2
queue_run_delay = 600
maximal_queue_lifetime = 1d

Existen más parámetros relacionados con esta directiva en este enlace del manual de postfix.

Podemos inspeccionar la cola de postfix para ver que mensajes no ha podido entregar y la causa de ello en cualquier momento usando los comandos mailq o postqueue -p (ambos son equivalentes y proporcionan la misma salida aunque mailq es un comando mucho más flexible y potente con más opciones).


8A5E9E9225A 1708097 Mon Mar 7 22:40:01 a.hernandez@dominio.com.mx
(host dedrelay.securesvrfix.mx[208.109.80.210] refused to talk to me: 554 p3plsmtps2ded45.prod.phx3.securesvrfix.mx : HOSTING RELAY : d9OoamSM5zzCi : DED : You've rea
ched your daily relay quota - 209.109.80.210)
alatorre.c@dominio2.com
d.molina@grupomaas.com.mx8B012E9266E 67309 Mon Mar 7 17:55:15 a.hernandez@dominio.com.mx
(host dedrelay.securesvrfix.mx[208.109.80.54] refused to talk to me: 554 p3plsmtpout045.prod.phx3.securesvrfix.mx: HOSTING RELAY : d9JyaxC4eLF21 : DED : You've reach
ed your daily relay quota - 208.109.80.210)
sfernandez@dominio2.com.mx

el identificador del mensaje que nos permite ver mucha más información acerca del mismo, su estado y su contenido usando el comando postcat -vq seguido de dicho identificador. Por ejemplo, para inspeccionar el primer mensaje de la cola de aquí arriba:

1
postcat -vq A3C3486137

También podemos decirle en cualquier momento a postfix que reprocese esos mensajes mediante los comandos postqueue -f o postfix flush. O podemos pedirle que reintente sólo uno de los mensajes de la cola usando el identificador que ya conocemos así:

1
postqueue -i A3C3486137

Por último, para eliminar todos los mensajes en espera de entrega que están en la cola podemos usar el siguiente comando:

1
postsuper -d ALL deferred

Ten en cuenta que, en este caso, los mensajes serán eliminados sin que el remitente reciba ningún tipo de notificación de que no ha podido realizarse la entrega.

El siguiente comando elimina de la cola de correos el mensaje especificado.

postsuper -d D8D24E923E4

Actualizar distribución de Linux Ubuntu a la nueva versión

Actualizando Ubuntu

Antes de actualizar nuestra versión a la nueva, necesitamos que todos los paquetes de nuestro sistema estén al día. Para ello abriremos una ventana de Terminal y escribiremos el siguiente comando:

sudo apt-get update && sudo apt-get dist-upgrade

Este comando descargará e instalará los últimos paquetes disponibles que necesitemos. Continuaremos reiniciando nuestro sistema para que terminen de instalarse las actualizaciones pertinentes. Entonces usamos este comando:

sudo update-manager -d

Se nos mostrará la pantalla de Actualizaciones de Software que se encargará de buscar la nueva versión de Ubuntu disponible..

MIME Types for ClickOnce deployment

When you are hosting a ClickOnce deployment on a webserver, you need have certain MIME types defined so the server knows how to handle the files. You can host a ClickOnce deployment on any server regardless of the operating system. So you can host a ClickOnce deployment on an Apache server just as easily as a server running Microsoft Windows Server. You just need to set up the right MIME types.

When you install the .NET Framework, it registers the MIME types automatically. This is why you don’t have to set up MIME types if you install IIS on your desktop machine and test your deployments by deploying to localhost. Carrying that forward, if you have the .NET Framework installed on your server, the MIME types should already be registered.

This is generally one of the first things to check when you’re having problems downloading the deployment. A definite sign that your MIME types are not set up correctly is if your customers try to install the application and it shows the XML of the deployment manifest (the .application file) in Internet Explorer rather than installing the application.

Here are the basic MIME types you need for every ClickOnce deployment:

.application –> application/x-ms-application
.manifest –> application/x-ms-manifest
.deploy –> application/octet-stream

If you are targeting .NET 3.5 or .NET 4.0, you need these as well:

.msp –> application/octet-stream
.msu –> application/octet-stream

If you are deploying an Office application (VSTO add-in), you need this one:

.vsto –> application/x-ms-vsto

If you are deploying a WPF application, you need these:

.xaml –> application/xaml+xml
.xbap –> application/x-ms-xbap

Click one of these links to see how to set MIME types in IIS 6 or IIS 7.

If your application is hosted on an Apache webserver, you can set up your own MIME types by putting entries in the .htaccess file in the root folder of your deployment. The syntax for adding the MIME types is this:

AddType Mime-type file-extension

For example, for the first three MIME types above, you would add these lines to your .htaccess file:

AddType application/x-ms-application application
AddType application/x-ms-manifest manifest
AddType application/octet-stream deploy

You can create the .htaccess file simply by opening notepad or some other text editor and adding the lines above to it, and saving it with the file name of .htaccess. Then copy it to the root of your deployment folders, and those MIME types will work for that folder and all of its subfolders.

For more information than you ever wanted to know about .htaccess files, check out this article.

How to Install and Configure vsftpd on Ubuntu 14.04 LTS

FTP (File Transfer Protocol) is probably the most popular method of uploading files to a server; a wide array of FTP servers, such as vsftpd, and clients exist for every platform.

Pre-Flight Check

  • These instructions are intended specifically for installing the vsfptd on Ubuntu 14.04 LTS.
  • I’ll be working from a Liquid Web Core Managed Ubuntu 14.04 LTS server, and I’ll be logged in as root.

 

Step 1: Install vsftpd

Warning: FTP data is insecure; traffic is not encrypted, and all transmissions are clear text (including usernames, passwords, commands, and data). Consider securing your FTP connection with SSL/TLS.

First, you’ll follow a simple best practice: ensuring the list of available packages is up to date before installing anything new.

apt-get update

Then let’s install vsftpd and any required packages:

apt-get -y install vsftpd

Step 2: Configure vsftpd

For a refresher on editing files with vim see: New User Tutorial: Overview of the Vim Text Editor

Let’s edit the configuration file for vsftpd:

vim /etc/vsftpd.conf

Disallow anonymous, unidentified users to access files via FTP; change the anonymous_enable setting to NO:

anonymous_enable=NO

Allow local uses to login by changing the local_enable setting to YES:

local_enable=YES

If you want local user to be able to write to a directory, then change the write_enable setting to YES:

write_enable=YES

Local users will be ‘chroot jailed’ and they will be denied access to any other part of the server; change the chroot_local_user setting to YES:

chroot_local_user=YES

Exit and save the file with the command :wq.

Restart the vsftpd service:

service vsftpd restart

Step 3: Configure the User’s Home Directory

With certain version of vsftpd you may receive the following error: 500 OOPS: vsftpd: refusing to run with writable root inside chroot().

Not to worry! Create a new directory for the user receiving the error (user2 in this case) that is a subdirectory of their home directory (/home/user2). For example:

Fix permissions for user2‘s home directory:

chmod a-w /home/user2/

Make a new directory for uploading files:

mkdir /home/user2/files
chown user2:user2 /home/user2/files/

Activar SSL en Apache2 (Ubuntu 10.04)

# Instalamos Apache
sudo aptitude install apache2

# Habilitamos el módulo SSL
sudo a2enmod ssl

# Habilitamos la configuración SSL por default

sudo a2ensite default-ssl

# Reiniciamos el servidor
sudo /etc/init.d/apache2 restart

Ya con esto queda habilitado, puedes probarlo entrando al localhost con https://127.0.0.1
Para crear  nuestro certificado, debemos seguir los siguientes pasos

# Creamos las llaves

cd /etc/apache2

sudo openssl genrsa -des3 -out server.key 1024

# Creamos el certificado con la llave
sudo openssl req -new -key server.key -out server.csr

# Creamos nuestro certificado, contestando las preguntas que nos indique recordando la contraseña


sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

#Cambiamos de carpeta la llave y certificado

sudo cp server.crt /etc/ssl/certs/
sudo cp server.key /etc/ssl/private/

# Abrimos el archivo de configuracion default-ssl

cd /etc/apache2/sites-available
sudo vim default-ssl

# reemplazamos y habilitamos la siguiente configuracion
SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key

# habilitamos el archivo

sudo a2ensite default-ssl

# Reiniciamos apache y listo!!
sudo /etc/init.d/apache2 restart