Quantcast
Channel: AskApache
Viewing all 58 articles
Browse latest View live

K-Swiss MFCEO Internet Commercial


PirateBay and Anonymous SOPA Press Releases

$
0
0

AskApache.com

PirateBay SOPA Press Release

INTERNETS, 18th of January 2012.

PRESS RELEASE, FOR IMMEDIATE RELEASE

Over a century ago Thomas Edison got the patent for a device which would "do for the eye what the phonograph does for the ear". He called it the Kinetoscope. He was not only amongst the first to record video, he was also the first person to own the copyright to a motion picture.

Because of Edisons patents for the motion pictures it was close to financially impossible to create motion pictures in the North american east coast. The movie studios therefor relocated to California, and founded what we today call Hollywood. The reason was mostly because there was no patent. There was also no copyright to speak of, so the studios could copy old stories and make movies out of them - like Fantasia, one of Disneys biggest hits ever.

So, the whole basis of this industry, that today is screaming about losing control over immaterial rights, is that they circumvented immaterial rights. They copied (or put in their terminology: "stole") other peoples creative works, without paying for it. They did it in order to make a huge profit. Today, they're all successful and most of the studios are on the Fortune 500 list of the richest companies in the world. Congratulations - it's all based on being able to re-use other peoples creative works. And today they hold the rights to what other people create. If you want to get something released, you have to abide to their rules. The ones they created after circumventing other peoples rules.

The reason they are always complainting about "pirates" today is simple. We've done what they did. We circumvented the rules they created and created our own. We crushed their monopoly by giving people something more efficient. We allow people to have direct communication between eachother, circumventing the profitable middle man, that in some cases take over 107% of the profits (yes, you pay to work for them). It's all based on the fact that we're competition. We've proven that their existance in their current form is no longer needed. We're just better than they are.

And the funny part is that our rules are very similar to the founding ideas of the USA. We fight for freedom of speech. We see all people as equal. We believe that the public, not the elite, should rule the nation. We believe that laws should be created to serve the public, not the rich corporations.

The Pirate Bay is truly an international community. The team is spread all over the globe - but we've stayed out of the USA. We have Swedish roots and a swedish friend said this: The word SOPA means "trash" in Swedish. The word PIPA means "a pipe" in Swedish. This is of course not a coincidence. They want to make the internet inte a one way pipe, with them at the top, shoving trash through the pipe down to the rest of us obedient consumers. The public opinion on this matter is clear. Ask anyone on the street and you'll learn that noone wants to be fed with trash. Why the US government want the american people to be fed with trash is beyond our imagination but we hope that you will stop them, before we all drown.

SOPA can't do anything to stop TPB. Worst case we'll change top level domain from our current .org to one of the hundreds of other names that we already also use. In countries where TPB is blocked, China and Saudi Arabia springs to mind, they block hundreds of our domain names. And did it work? Not really. To fix the "problem of piracy" one should go to the source of the problem. The entertainment industry say they're creating "culture" but what they really do is stuff like selling overpriced plushy dolls and making 11 year old girls become anorexic. Either from working in the factories that creates the dolls for basically no salary or by watching movies and tv shows that make them think that they're fat.

In the great Sid Meiers computer game Civilization you can build Wonders of the world. One of the most powerful ones is Hollywood. With that you control all culture and media in the world. Rupert Murdoch was happy with MySpace and had no problems with their own piracy until it failed. Now he's complainting that Google is the biggest source of piracy in the world - because he's jealous. He wants to retain his mind control over people and clearly you'd get a more honest view of things on Wikipedia and Google than on Fox News.

Some facts (years, dates) are probably wrong in this press release. The reason is that we can't access this information when Wikipedia is blacked out. Because of pressure from our failing competitors. We're sorry for that.

THE PIRATE BAY, (K)2012

Anonymous Hackers SOPA Statement

Bright, and Clear: The Future of Free Speech

A rallying cry on the occassion of the Web's first mass blackout

As we watch the web go dark today in protest against the SOPA/PIPA censorship bills, let's take a moment and reflect on why this fight is so important. We may have learned that free speech is what makes America great, or instinctively resist attempts at silencing our voices. But these are abstract principles, divorced from the real world and our daily lives.

Free speech is the foundation of a free society. We can have the vote all we want. We can donate money wherever we want. But unless we're able to talk to each other and figure out collectively _what_ we want, those things don't matter.

We believe a healthy society doesn't allow its artists, musicians and other creators to starve. The copyright industry has been justly criticized for abusing the political process in a desperate attempt to maintain its role as a cultural gatekeeper, a business model made obsolete by a digital age of free copies. But the RIAA, MPAA & IFPI deserve our opprobrium for making enormous profits while often leaving the very artists it claims to represent *poorer* than they would be as independents.[1] While the public may have greater access to the few artists deemed sufficiently marketable to gain mass media promotion, fewer and fewer of us are making art and music in our own lives.

It's time we make a stand for a better world - not merely take rearguard actions to preserve a status quo that is _already_ failing us. Accordingly, we present the following list of demands:

  • We call on national legislatures to not only reject ACTA efforts to globalize the American intellectual property regime, but to abolish the WIPO.
  • We demand the elimination of the DMCA's registration requirement for qualification under the "safe harbor" provision. It's absurd that a website owner needs to mail in a form and pay a $100+ fee to the government to register a contact for copyright violations. A web page at a standard location (a la robots.txt) should suffice.
  • We expect courts to apply penalties just as severe to rightsholders who issue abusive takedown notices as those applied to copyright violators.
  • No more Jammie Thomases. Any penalties for copyright infringement must be sane and reasonable and not based unsubstantiated, outlandish claims of harm.
  • The Department of Justice must begin an anti-trust investigation into the copyright industry, with a specific focus on collusion between rightsholders and ISPs in monitoring Internet users, and payola and cross ownership with mass media.
  • We demand an end to sales of radio frequencies into private hands. We hold that spectrum is a form of speech - it rightly belongs to the people and is not the government's to auction off to begin with.
  • We demand that ISPs stop interfering with file sharing via BitTorrent or any other protocol.
  • We recognize a right of total ownership, not merely licensing, of products we have purchased and a right to tinker and modify them as we see fit. The Library of Congress should not be determining the acceptable boundaries of technology.
  • We reject the principle of contributory infringement entirely. While there may be bad uses, there is no bad code.
  • We expect legislators and judges to make efforts to educate themselves about the technologies they oversee, and to call on and respect the opinions of technical experts when necessary. The Internet makes nerds of us all.
  • All research receiving any public funding, directly or indirectly, must be placed in the public domain upon publication.
  • For the sake of innovation and competitiveness, the US Patent & Trade Office must immediately cease issuing software and business method patents, and declare all such existing patents null and void. We unequivocally reject any patents on mathematical formulas and genes or other naturally-occurring substances (human or otherwise).
  • Copyright and patent terms must be reduced to reasonable lengths (two and five years from the time of creation, respectively). Works should only be eligible for the length of protection in the effect when created - the continuing extension of terms to protect Disney's ownership of Mickey Mouse must cease.
  • We recognize a broad right of "fair use" as essential to a vibrant and creative culture. We will remix, sample, mash up, translate, perform, parody and otherwise create derivative works as we see fit.
  • Courts must accord bloggers the same rights as mainstream reporters. The right to a free press originally meant a literal, physical printing press - not membership in some government sanctioned elite. Blogs are the modern day digital equivalent.

We call upon all freedom loving Internauts to join us. We further call upon our legislators, bureaucrats and the media & telecommunications industries to immediately begin implementing our demands. The future of free speech is bright, and clear - either stand with us or get out of the way. [1]

KeepTheWebOpen - Fight Back!

The KeepTheWebOpen site shows how the world may fundamentally be changed for the better... soon.. maybe...

PirateBay and Anonymous SOPA Press Releases originally appeared on AskApache.com


Chmod, Umask, Stat, Fileperms, and File Permissions

$
0
0

AskApache.com

Unix file permissions are one of the more difficult subjects to grasp.. Well, ok maybe "grasp" isn't the word.. Master is the right word.. Unix file permissions is a hard topic to fully master, mainly I think because there aren't many instances when a computer user encounters them. Windows has been trying to figure it out for decades with little progress, so don't feel bad if you don't know much about it. Unless you're with the program and running Mac or any other BSD/Unix based OS you've never had the ability to secure your system in this most basic and fundamental way. Usually the first time someone encounters file permissions it's because their website was cracked..

.htaccess

$ chmod 604 .htaccess

604 -rw----r--  /home/askapache/cgi-bin/.htaccess

php.cgi

$ chmod 711 php.cgi

$ 711 -rwx--x--x  /home/askapache/cgi-bin/php.cgi

.php.ini

$ chmod 600 php.ini

$ 600 -rw-------  /home/askapache/cgi-bin/php.ini

I'm in the process of developing an updated version of the .htaccess security plugin, and one thing I have been working on is file permissions. Some people had problems trying to create files on their server and I realized it was bad programming on my part.. so I began researching permissions in detail. I went deep into the source code of Apache (which is why this site is called AskApache, BTW), PHP, Python, Ocaml, Perl, Ruby, and POSIX operating systems and got a pretty good handle on it now..

Tips before we dig in

Here's a few things I've learned that I didn't know before (using php).

Deleting Files and Directories

Deleting a file may require chmodding the file to 666 or even 777 before you are able to delete it. You also might have to chmod the parent directory of the file as well. Also, you may have to chdir to the directory the file is in. And lastly you may have to change the owner or group of the file. Further than that you can try renaming the file first then deleting it..

Deleting a directory means you need to remove every file in it first. It needs to be empty. And if your file system uses NFS or some other networked FS you might have even more problems deleting files. If the file you are trying to delete is being used by say, Apache or php then you might have to kill that process first.

Creating Files in Restrictive Environments

My research has been geared to try and make my code as robust as possible, I'm throwing everything but the kitchen sink into some of these functions because so many people are on such different types of servers. To create a file in a restrictive environment is a fun excercise to take.. You can write a file using many different functions, but there are some tricks if they all fail. One trick is instead of trying to "write" the data to the file, you can UPLOAD the data to the server and let PHP handle the file as if you used an upload form. I like to use fsockopen to do it, as some installations have been setup to prevent this type of fake upload.

Then there are the various other hacks like using an ftp connection (if you know the user/pass) to send the file from php, using ssh from php, whatever is available on the hosts php installation. In addition to those more involved workarounds you can often get around this problem by doing little hacks discussed at php.net in the comments for various functions. Such as changing the umask, changing directories with chdir first, creating a temporary file using a function like tempfile and then renaming or copying the tempfile to your desired file which sometimes gives you the permissions needed to write to the location.

If the php installation is newer than you can also look into creating your own stream context to pass write the data direct.

Stat Function

I've created a stat function in php that goes farther than the normal stat function... Just give the function a file to stat, and it returns an array of information.

function askapache_stat($filename) {
 clearstatcache();
 $ss=@stat($filename);
 if(!$ss) die("Couldnt stat {$filename}");
 $file_convert=array(0140000=>'ssocket',0120000=>'llink',0100000=>'-file',0060000=>'bblock',0040000=>'ddir',0020000=>'cchar',0010000=>'pfifo');
 $p=$ss['mode'];
 $t=decoct($ss['mode'] & 0170000);
 $str = (array_key_exists(octdec($t),$file_convert)) ? $file_convert[octdec($t)]{0} : 'u';
 $str.=(($p&0x0100)?'r':'-').(($p&0x0080)?'w':'-').(($p&0x0040)?(($p&0x0800)?'s':'x'):(($p&0x0800)?'S':'-'));
 $str.=(($p&0x0020)?'r':'-').(($p&0x0010)?'w':'-').(($p&0x0008)?(($p&0x0400)?'s':'x'):(($p&0x0400)?'S':'-'));
 $str.=(($p&0x0004)?'r':'-').(($p&0x0002)?'w':'-').(($p&0x0001)?(($p&0x0200)?'t':'x'):(($p&0x0200)?'T':'-'));
 
 $s=array(
 'perms'=>array(
  'umask'=>sprintf("%04o",umask()),
  'human'=>$str,
  'octal1'=>sprintf("%o", ($ss['mode'] & 000777)),
  'octal2'=>sprintf("0%o", 0777 & $p),
  'decimal'=>sprintf("%04o", $p),
  'fileperms'=>@fileperms($filename),
  'mode1'=>$p,
  'mode2'=>$ss['mode']),
 
 'filetype'=>array(
  'type'=>substr($file_convert[octdec($t)],1),
  'type_octal'=>sprintf("%07o", octdec($t)),
  'is_file'=>@is_file($filename),
  'is_dir'=>@is_dir($filename),
  'is_link'=>@is_link($filename),
  'is_readable'=> @is_readable($filename),
  'is_writable'=> @is_writable($filename)),
 
 'owner'=>array(
  'fileowner'=>$ss['uid'],
  'filegroup'=>$ss['gid'],
  'owner_name'=>(function_exists('posix_getpwuid')) ? @reset(@posix_getpwuid($ss['uid'])) : '',
  'group_name'=>(function_exists('posix_getgrgid')) ? @reset(@posix_getgrgid($ss['gid'])) : ''),
 
 'file'=>array(
  'filename'=>$filename,
  'realpath'=>(@realpath($filename) != $filename) ? @realpath($filename) : '',
  'dirname'=>@dirname($filename),
  'basename'=>@basename($filename)),
 
 'device'=>array(
  'device'=>$ss['dev'], //Device
  'device_number'=>$ss['rdev'], //Device number, if device.
  'inode'=>$ss['ino'], //File serial number
  'link_count'=>$ss['nlink'], //link count
  'link_to'=>($s['type']=='link') ? @readlink($filename) : ''),
 
 'size'=>array(
  'size'=>$ss['size'], //Size of file, in bytes.
  'blocks'=>$ss['blocks'], //Number 512-byte blocks allocated
  'block_size'=> $ss['blksize']), //Optimal block size for I/O.
 
 'time'=>array(
  'mtime'=>$ss['mtime'], //Time of last modification
  'atime'=>$ss['atime'], //Time of last access.
  'ctime'=>$ss['ctime'], //Time of last status change
  'accessed'=>@date('Y M D H:i:s',$ss['atime']),
  'modified'=>@date('Y M D H:i:s',$ss['mtime']),
  'created'=>@date('Y M D H:i:s',$ss['ctime'])),
 );
 
 clearstatcache();
 return $s;
}

PHP Stat Function Output

Example output, say from print_r(askapache_stat( __FILE__ ) );

Array(
[perms] => Array
  (
  [umask] => 0022
  [human] => -rw-r--r--
  [octal1] => 644
  [octal2] => 0644
  [decimal] => 100644
  [fileperms] => 33188
  [mode1] => 33188
  [mode2] => 33188
  )
 
[filetype] => Array
  (
  [type] => file
  [type_octal] => 0100000
  [is_file] => 1
  [is_dir] =>
  [is_link] =>
  [is_readable] => 1
  [is_writable] => 1
  )
 
[owner] => Array
  (
  [fileowner] => 035483
  [filegroup] => 23472
  [owner_name] => askapache
  [group_name] => grp22558
  )
 
[file] => Array
  (
  [filename] => /home/askapache/askapache-stat/public_html/ok/g.php
  [realpath] =>
  [dirname] => /home/askapache/askapache-stat/public_html/ok
  [basename] => g.php
  )
 
[device] => Array
  (
  [device] => 25
  [device_number] => 0
  [inode] => 92455020
  [link_count] => 1
  [link_to] =>
  )
 
[size] => Array
  (
  [size] => 2652
  [blocks] => 8
  [block_size] => 8192
  )
 
[time] => Array
  (
  [mtime] => 1227685253
  [atime] => 1227685138
  [ctime] => 1227685253
  [accessed] => 2008 Nov Tue 23:38:58
  [modified] => 2008 Nov Tue 23:40:53
  [created] => 2008 Nov Tue 23:40:53
  )
)

Every Permission 0000 to 0777

chmod, umask, file permissions testThis shows what each numeric permission does to a REGULAR file. I'll provide the code to do this below so you can do the same thing on your server.

chmod 0
----------
chmod 1
---------x
chmod 2
--------w-
chmod 3
--------wx
chmod 4
-------r--
chmod 5
-------r-x
chmod 6
-------rw-
chmod 7
-------rwx
chmod 10
------x---
chmod 11
------x--x
chmod 12
------x-w-
chmod 13
------x-wx
chmod 14
------xr--
chmod 15
------xr-x
chmod 16
------xrw-
chmod 17
------xrwx
chmod 20
-----w----
chmod 21
-----w---x
chmod 22
-----w--w-
chmod 23
-----w--wx
chmod 24
-----w-r--
chmod 25
-----w-r-x
chmod 26
-----w-rw-
chmod 27
-----w-rwx
chmod 30
-----wx---
chmod 31
-----wx--x
chmod 32
-----wx-w-
chmod 33
-----wx-wx
chmod 34
-----wxr--
chmod 35
-----wxr-x
chmod 36
-----wxrw-
chmod 37
-----wxrwx
chmod 40
----r-----
chmod 41
----r----x
chmod 42
----r---w-
chmod 43
----r---wx
chmod 44
----r--r--
chmod 45
----r--r-x
chmod 46
----r--rw-
chmod 47
----r--rwx
chmod 50
----r-x---
chmod 51
----r-x--x
chmod 52
----r-x-w-
chmod 53
----r-x-wx
chmod 54
----r-xr--
chmod 55
----r-xr-x
chmod 56
----r-xrw-
chmod 57
----r-xrwx
chmod 60
----rw----
chmod 61
----rw---x
chmod 62
----rw--w-
chmod 63
----rw--wx
chmod 64
----rw-r--
chmod 65
----rw-r-x
chmod 66
----rw-rw-
chmod 67
----rw-rwx
chmod 70
----rwx---
chmod 71
----rwx--x
chmod 72
----rwx-w-
chmod 73
----rwx-wx
chmod 74
----rwxr--
chmod 75
----rwxr-x
chmod 76
----rwxrw-
chmod 77
----rwxrwx
chmod 100
---x------
chmod 101
---x-----x
chmod 102
---x----w-
chmod 103
---x----wx
chmod 104
---x---r--
chmod 105
---x---r-x
chmod 106
---x---rw-
chmod 107
---x---rwx
chmod 110
---x--x---
chmod 111
---x--x--x
chmod 112
---x--x-w-
chmod 113
---x--x-wx
chmod 114
---x--xr--
chmod 115
---x--xr-x
chmod 116
---x--xrw-
chmod 117
---x--xrwx
chmod 120
---x-w----
chmod 121
---x-w---x
chmod 122
---x-w--w-
chmod 123
---x-w--wx
chmod 124
---x-w-r--
chmod 125
---x-w-r-x
chmod 126
---x-w-rw-
chmod 127
---x-w-rwx
chmod 130
---x-wx---
chmod 131
---x-wx--x
chmod 132
---x-wx-w-
chmod 133
---x-wx-wx
chmod 134
---x-wxr--
chmod 135
---x-wxr-x
chmod 136
---x-wxrw-
chmod 137
---x-wxrwx
chmod 140
---xr-----
chmod 141
---xr----x
chmod 142
---xr---w-
chmod 143
---xr---wx
chmod 144
---xr--r--
chmod 145
---xr--r-x
chmod 146
---xr--rw-
chmod 147
---xr--rwx
chmod 150
---xr-x---
chmod 151
---xr-x--x
chmod 152
---xr-x-w-
chmod 153
---xr-x-wx
chmod 154
---xr-xr--
chmod 155
---xr-xr-x
chmod 156
---xr-xrw-
chmod 157
---xr-xrwx
chmod 160
---xrw----
chmod 161
---xrw---x
chmod 162
---xrw--w-
chmod 163
---xrw--wx
chmod 164
---xrw-r--
chmod 165
---xrw-r-x
chmod 166
---xrw-rw-
chmod 167
---xrw-rwx
chmod 170
---xrwx---
chmod 171
---xrwx--x
chmod 172
---xrwx-w-
chmod 173
---xrwx-wx
chmod 174
---xrwxr--
chmod 175
---xrwxr-x
chmod 176
---xrwxrw-
chmod 177
---xrwxrwx
chmod 200
--w-------
chmod 201
--w------x
chmod 202
--w-----w-
chmod 203
--w-----wx
chmod 204
--w----r--
chmod 205
--w----r-x
chmod 206
--w----rw-
chmod 207
--w----rwx
chmod 210
--w---x---
chmod 211
--w---x--x
chmod 212
--w---x-w-
chmod 213
--w---x-wx
chmod 214
--w---xr--
chmod 215
--w---xr-x
chmod 216
--w---xrw-
chmod 217
--w---xrwx
chmod 220
--w--w----
chmod 221
--w--w---x
chmod 222
--w--w--w-
chmod 223
--w--w--wx
chmod 224
--w--w-r--
chmod 225
--w--w-r-x
chmod 226
--w--w-rw-
chmod 227
--w--w-rwx
chmod 230
--w--wx---
chmod 231
--w--wx--x
chmod 232
--w--wx-w-
chmod 233
--w--wx-wx
chmod 234
--w--wxr--
chmod 235
--w--wxr-x
chmod 236
--w--wxrw-
chmod 237
--w--wxrwx
chmod 240
--w-r-----
chmod 241
--w-r----x
chmod 242
--w-r---w-
chmod 243
--w-r---wx
chmod 244
--w-r--r--
chmod 245
--w-r--r-x
chmod 246
--w-r--rw-
chmod 247
--w-r--rwx
chmod 250
--w-r-x---
chmod 251
--w-r-x--x
chmod 252
--w-r-x-w-
chmod 253
--w-r-x-wx
chmod 254
--w-r-xr--
chmod 255
--w-r-xr-x
chmod 256
--w-r-xrw-
chmod 257
--w-r-xrwx
chmod 260
--w-rw----
chmod 261
--w-rw---x
chmod 262
--w-rw--w-
chmod 263
--w-rw--wx
chmod 264
--w-rw-r--
chmod 265
--w-rw-r-x
chmod 266
--w-rw-rw-
chmod 267
--w-rw-rwx
chmod 270
--w-rwx---
chmod 271
--w-rwx--x
chmod 272
--w-rwx-w-
chmod 273
--w-rwx-wx
chmod 274
--w-rwxr--
chmod 275
--w-rwxr-x
chmod 276
--w-rwxrw-
chmod 277
--w-rwxrwx
chmod 300
--wx------
chmod 301
--wx-----x
chmod 302
--wx----w-
chmod 303
--wx----wx
chmod 304
--wx---r--
chmod 305
--wx---r-x
chmod 306
--wx---rw-
chmod 307
--wx---rwx
chmod 310
--wx--x---
chmod 311
--wx--x--x
chmod 312
--wx--x-w-
chmod 313
--wx--x-wx
chmod 314
--wx--xr--
chmod 315
--wx--xr-x
chmod 316
--wx--xrw-
chmod 317
--wx--xrwx
chmod 320
--wx-w----
chmod 321
--wx-w---x
chmod 322
--wx-w--w-
chmod 323
--wx-w--wx
chmod 324
--wx-w-r--
chmod 325
--wx-w-r-x
chmod 326
--wx-w-rw-
chmod 327
--wx-w-rwx
chmod 330
--wx-wx---
chmod 331
--wx-wx--x
chmod 332
--wx-wx-w-
chmod 333
--wx-wx-wx
chmod 334
--wx-wxr--
chmod 335
--wx-wxr-x
chmod 336
--wx-wxrw-
chmod 337
--wx-wxrwx
chmod 340
--wxr-----
chmod 341
--wxr----x
chmod 342
--wxr---w-
chmod 343
--wxr---wx
chmod 344
--wxr--r--
chmod 345
--wxr--r-x
chmod 346
--wxr--rw-
chmod 347
--wxr--rwx
chmod 350
--wxr-x---
chmod 351
--wxr-x--x
chmod 352
--wxr-x-w-
chmod 353
--wxr-x-wx
chmod 354
--wxr-xr--
chmod 355
--wxr-xr-x
chmod 356
--wxr-xrw-
chmod 357
--wxr-xrwx
chmod 360
--wxrw----
chmod 361
--wxrw---x
chmod 362
--wxrw--w-
chmod 363
--wxrw--wx
chmod 364
--wxrw-r--
chmod 365
--wxrw-r-x
chmod 366
--wxrw-rw-
chmod 367
--wxrw-rwx
chmod 370
--wxrwx---
chmod 371
--wxrwx--x
chmod 372
--wxrwx-w-
chmod 373
--wxrwx-wx
chmod 374
--wxrwxr--
chmod 375
--wxrwxr-x
chmod 376
--wxrwxrw-
chmod 377
--wxrwxrwx
chmod 400
-r--------
chmod 401
-r-------x
chmod 402
-r------w-
chmod 403
-r------wx
chmod 404
-r-----r--
chmod 405
-r-----r-x
chmod 406
-r-----rw-
chmod 407
-r-----rwx
chmod 410
-r----x---
chmod 411
-r----x--x
chmod 412
-r----x-w-
chmod 413
-r----x-wx
chmod 414
-r----xr--
chmod 415
-r----xr-x
chmod 416
-r----xrw-
chmod 417
-r----xrwx
chmod 420
-r---w----
chmod 421
-r---w---x
chmod 422
-r---w--w-
chmod 423
-r---w--wx
chmod 424
-r---w-r--
chmod 425
-r---w-r-x
chmod 426
-r---w-rw-
chmod 427
-r---w-rwx
chmod 430
-r---wx---
chmod 431
-r---wx--x
chmod 432
-r---wx-w-
chmod 433
-r---wx-wx
chmod 434
-r---wxr--
chmod 435
-r---wxr-x
chmod 436
-r---wxrw-
chmod 437
-r---wxrwx
chmod 440
-r--r-----
chmod 441
-r--r----x
chmod 442
-r--r---w-
chmod 443
-r--r---wx
chmod 444
-r--r--r--
chmod 445
-r--r--r-x
chmod 446
-r--r--rw-
chmod 447
-r--r--rwx
chmod 450
-r--r-x---
chmod 451
-r--r-x--x
chmod 452
-r--r-x-w-
chmod 453
-r--r-x-wx
chmod 454
-r--r-xr--
chmod 455
-r--r-xr-x
chmod 456
-r--r-xrw-
chmod 457
-r--r-xrwx
chmod 460
-r--rw----
chmod 461
-r--rw---x
chmod 462
-r--rw--w-
chmod 463
-r--rw--wx
chmod 464
-r--rw-r--
chmod 465
-r--rw-r-x
chmod 466
-r--rw-rw-
chmod 467
-r--rw-rwx
chmod 470
-r--rwx---
chmod 471
-r--rwx--x
chmod 472
-r--rwx-w-
chmod 473
-r--rwx-wx
chmod 474
-r--rwxr--
chmod 475
-r--rwxr-x
chmod 476
-r--rwxrw-
chmod 477
-r--rwxrwx
chmod 500
-r-x------
chmod 501
-r-x-----x
chmod 502
-r-x----w-
chmod 503
-r-x----wx
chmod 504
-r-x---r--
chmod 505
-r-x---r-x
chmod 506
-r-x---rw-
chmod 507
-r-x---rwx
chmod 510
-r-x--x---
chmod 511
-r-x--x--x
chmod 512
-r-x--x-w-
chmod 513
-r-x--x-wx
chmod 514
-r-x--xr--
chmod 515
-r-x--xr-x
chmod 516
-r-x--xrw-
chmod 517
-r-x--xrwx
chmod 520
-r-x-w----
chmod 521
-r-x-w---x
chmod 522
-r-x-w--w-
chmod 523
-r-x-w--wx
chmod 524
-r-x-w-r--
chmod 525
-r-x-w-r-x
chmod 526
-r-x-w-rw-
chmod 527
-r-x-w-rwx
chmod 530
-r-x-wx---
chmod 531
-r-x-wx--x
chmod 532
-r-x-wx-w-
chmod 533
-r-x-wx-wx
chmod 534
-r-x-wxr--
chmod 535
-r-x-wxr-x
chmod 536
-r-x-wxrw-
chmod 537
-r-x-wxrwx
chmod 540
-r-xr-----
chmod 541
-r-xr----x
chmod 542
-r-xr---w-
chmod 543
-r-xr---wx
chmod 544
-r-xr--r--
chmod 545
-r-xr--r-x
chmod 546
-r-xr--rw-
chmod 547
-r-xr--rwx
chmod 550
-r-xr-x---
chmod 551
-r-xr-x--x
chmod 552
-r-xr-x-w-
chmod 553
-r-xr-x-wx
chmod 554
-r-xr-xr--
chmod 555
-r-xr-xr-x
chmod 556
-r-xr-xrw-
chmod 557
-r-xr-xrwx
chmod 560
-r-xrw----
chmod 561
-r-xrw---x
chmod 562
-r-xrw--w-
chmod 563
-r-xrw--wx
chmod 564
-r-xrw-r--
chmod 565
-r-xrw-r-x
chmod 566
-r-xrw-rw-
chmod 567
-r-xrw-rwx
chmod 570
-r-xrwx---
chmod 571
-r-xrwx--x
chmod 572
-r-xrwx-w-
chmod 573
-r-xrwx-wx
chmod 574
-r-xrwxr--
chmod 575
-r-xrwxr-x
chmod 576
-r-xrwxrw-
chmod 577
-r-xrwxrwx
chmod 600
-rw-------
chmod 601
-rw------x
chmod 602
-rw-----w-
chmod 603
-rw-----wx
chmod 604
-rw----r--
chmod 605
-rw----r-x
chmod 606
-rw----rw-
chmod 607
-rw----rwx
chmod 610
-rw---x---
chmod 611
-rw---x--x
chmod 612
-rw---x-w-
chmod 613
-rw---x-wx
chmod 614
-rw---xr--
chmod 615
-rw---xr-x
chmod 616
-rw---xrw-
chmod 617
-rw---xrwx
chmod 620
-rw--w----
chmod 621
-rw--w---x
chmod 622
-rw--w--w-
chmod 623
-rw--w--wx
chmod 624
-rw--w-r--
chmod 625
-rw--w-r-x
chmod 626
-rw--w-rw-
chmod 627
-rw--w-rwx
chmod 630
-rw--wx---
chmod 631
-rw--wx--x
chmod 632
-rw--wx-w-
chmod 633
-rw--wx-wx
chmod 634
-rw--wxr--
chmod 635
-rw--wxr-x
chmod 636
-rw--wxrw-
chmod 637
-rw--wxrwx
chmod 640
-rw-r-----
chmod 641
-rw-r----x
chmod 642
-rw-r---w-
chmod 643
-rw-r---wx
chmod 644
-rw-r--r--
chmod 645
-rw-r--r-x
chmod 646
-rw-r--rw-
chmod 647
-rw-r--rwx
chmod 650
-rw-r-x---
chmod 651
-rw-r-x--x
chmod 652
-rw-r-x-w-
chmod 653
-rw-r-x-wx
chmod 654
-rw-r-xr--
chmod 655
-rw-r-xr-x
chmod 656
-rw-r-xrw-
chmod 657
-rw-r-xrwx
chmod 660
-rw-rw----
chmod 661
-rw-rw---x
chmod 662
-rw-rw--w-
chmod 663
-rw-rw--wx
chmod 664
-rw-rw-r--
chmod 665
-rw-rw-r-x
chmod 666
-rw-rw-rw-
chmod 667
-rw-rw-rwx
chmod 670
-rw-rwx---
chmod 671
-rw-rwx--x
chmod 672
-rw-rwx-w-
chmod 673
-rw-rwx-wx
chmod 674
-rw-rwxr--
chmod 675
-rw-rwxr-x
chmod 676
-rw-rwxrw-
chmod 677
-rw-rwxrwx
chmod 700
-rwx------
chmod 701
-rwx-----x
chmod 702
-rwx----w-
chmod 703
-rwx----wx
chmod 704
-rwx---r--
chmod 705
-rwx---r-x
chmod 706
-rwx---rw-
chmod 707
-rwx---rwx
chmod 710
-rwx--x---
chmod 711
-rwx--x--x
chmod 712
-rwx--x-w-
chmod 713
-rwx--x-wx
chmod 714
-rwx--xr--
chmod 715
-rwx--xr-x
chmod 716
-rwx--xrw-
chmod 717
-rwx--xrwx
chmod 720
-rwx-w----
chmod 721
-rwx-w---x
chmod 722
-rwx-w--w-
chmod 723
-rwx-w--wx
chmod 724
-rwx-w-r--
chmod 725
-rwx-w-r-x
chmod 726
-rwx-w-rw-
chmod 727
-rwx-w-rwx
chmod 730
-rwx-wx---
chmod 731
-rwx-wx--x
chmod 732
-rwx-wx-w-
chmod 733
-rwx-wx-wx
chmod 734
-rwx-wxr--
chmod 735
-rwx-wxr-x
chmod 736
-rwx-wxrw-
chmod 737
-rwx-wxrwx
chmod 740
-rwxr-----
chmod 741
-rwxr----x
chmod 742
-rwxr---w-
chmod 743
-rwxr---wx
chmod 744
-rwxr--r--
chmod 745
-rwxr--r-x
chmod 746
-rwxr--rw-
chmod 747
-rwxr--rwx
chmod 750
-rwxr-x---
chmod 751
-rwxr-x--x
chmod 752
-rwxr-x-w-
chmod 753
-rwxr-x-wx
chmod 754
-rwxr-xr--
chmod 755
-rwxr-xr-x
chmod 756
-rwxr-xrw-
chmod 757
-rwxr-xrwx
chmod 760
-rwxrw----
chmod 761
-rwxrw---x
chmod 762
-rwxrw--w-
chmod 763
-rwxrw--wx
chmod 764
-rwxrw-r--
chmod 765
-rwxrw-r-x
chmod 766
-rwxrw-rw-
chmod 767
-rwxrw-rwx
chmod 770
-rwxrwx---
chmod 771
-rwxrwx--x
chmod 772
-rwxrwx-w-
chmod 773
-rwxrwx-wx
chmod 774
-rwxrwxr--
chmod 775
-rwxrwxr-x
chmod 776
-rwxrwxrw-
chmod 777
-rwxrwxrwx

Congratulations!

Here's my custom stat function, which I am definately not finished with, so check back in a couple days and if you find any improvements please hook me up with a comment!

function askapache_stat( $filename ) {
$p=@fileperms($filename);
$s=@stat($filename);
$str='';
$t=decoct($s['mode'] & 0170000);
 
switch (octdec($t)) {
case 0140000: $str = 's'; $stat['type']='socket'; break;
case 0120000: $str = 'l'; $stat['type']='link'; break;
case 0100000: $str = '-'; $stat['type']='file'; break;
case 0060000: $str = 'b'; $stat['type']='block'; break;
case 0040000: $str = 'd'; $stat['type']='dir'; break;
case 0020000: $str = 'c'; $stat['type']='char'; break;
case 0010000: $str = 'p'; $stat['type']='fifo'; break;
default: $str = 'u'; $stat['type']='unknown'; break;
}
 
$stat['type_octal'] = sprintf("%07o", octdec($t));
 
$str .= (($p&0x0100)?'r':'-').(($p&0x0080)?'w':'-').(($p&0x0040)?(($p&0x0800)?'s':'x'):(($p&0x0800)?'S':'-'));
$str .= (($p&0x0020)?'r':'-').(($p&0x0010)?'w':'-').(($p&0x0008)?(($p&0x0400)?'s':'x'):(($p&0x0400)?'S':'-'));
$str .= (($p&0x0004)?'r':'-').(($p&0x0002)?'w':'-').(($p&0x0001)?(($p&0x0200)?'t':'x'):(($p&0x0200)?'T':'-'));
 
$stat['default_umask']=sprintf("%04o",umask());
$stat['perm_human']=$str;
$stat['perm_octal1'] = sprintf( "%o", ( $s['mode'] & 00777 ) );
$stat['perm_octal2'] = sprintf("0%o", 0777 & $p);
$stat['perm_dec'] = sprintf("%04o", $p);
$stat['perm_mode']=$s['mode'];   // File mode.
 
$stat['file'] = @realpath($filename);
$stat['basename'] = basename( $filename );
 
$stat['user_id'] = $s['uid'];
$stat['group_id'] = $s['gid'];
 
$stat['device']=$s['dev'];      // Device
$stat['device_number']=$s['rdev'];    // Device number, if device.
$stat['inode']=$s['ino'];      // File serial number
$stat['link_count']=$s['nlink'];    // link count
if($stat['type']=='link')$stat['link_to']=@readlink( $filename );
 
$stat['size']=$s['size'];    // Size of file, in bytes.
$stat['block_size']=$s['blksize'];  // Optimal block size for I/O.
$stat['blocks']=$s['blocks'];  // Number 512-byte blocks allocated
 
$stat['time_access']=@date( 'Y M D H:i:s',$s['atime']);    // Time of last access.
$stat['time_modified']=@date( 'Y M D H:i:s',$s['mtime']);    // Time of last modification
$stat['time_created']=@date( 'Y M D H:i:s',$s['ctime']);    // Time of last status change
 
clearstatcache();
return $stat;
}
 
header('Content-Type: text/plain');
$stat=askapache_stat(__FILE__);
print_r($stat);

Defining Permission Bits

!defined('S_IFMT') && define('S_IFMT', 0170000); //  mask for all types
!defined('S_IFSOCK') && define('S_IFSOCK', 0140000); // type: socket
!defined('S_IFLNK') && define('S_IFLNK', 0120000); // type:  symbolic link
!defined('S_IFREG') && define('S_IFREG', 0100000); // type:  regular file
!defined('S_IFBLK') && define('S_IFBLK', 0060000); // type:  block device
!defined('S_IFDIR') && define('S_IFDIR', 0040000); // type:  directory
!defined('S_IFCHR') && define('S_IFCHR', 0020000); // type:  character device
!defined('S_IFIFO') && define('S_IFIFO', 0010000); // type:  fifo
 
!defined('S_ISUID') && define('S_ISUID', 0004000); // set-uid bit
!defined('S_ISGID') && define('S_ISGID', 0002000); // set-gid bit
!defined('S_ISVTX') && define('S_ISVTX', 0001000); // sticky bit
!defined('S_IRWXU') && define('S_IRWXU', 00700); //  mask for owner permissions
!defined('S_IRUSR') && define('S_IRUSR', 00400); //  owner: read permission
!defined('S_IWUSR') && define('S_IWUSR', 00200); //  owner: write permission
!defined('S_IXUSR') && define('S_IXUSR', 00100); //  owner: execute permission
!defined('S_IRWXG') && define('S_IRWXG', 00070); //  mask for group permissions
!defined('S_IRGRP') && define('S_IRGRP', 00040); //  group: read permission
!defined('S_IWGRP') && define('S_IWGRP', 00020); //  group: write permission
!defined('S_IXGRP') && define('S_IXGRP', 00010); //  group: execute permission
!defined('S_IRWXO') && define('S_IRWXO', 00007); //  mask for others permissions
!defined('S_IROTH') && define('S_IROTH', 00004); //  others:  read permission
!defined('S_IWOTH') && define('S_IWOTH', 00002); //  others:  write permission
!defined('S_IXOTH') && define('S_IXOTH', 00001); //  others:  execute permission
 
!defined('S_IRWXUGO') && define('S_IRWXUGO', (S_IRWXU | S_IRWXG | S_IRWXO));
!defined('S_IALLUGO') && define('S_IALLUGO', (S_ISUID | S_ISGID | S_ISVTX | S_IRWXUGO));
!defined('S_IRUGO') && define('S_IRUGO', (S_IRUSR | S_IRGRP | S_IROTH));
!defined('S_IWUGO') && define('S_IWUGO', (S_IWUSR | S_IWGRP | S_IWOTH));
!defined('S_IXUGO') && define('S_IXUGO', (S_IXUSR | S_IXGRP | S_IXOTH));
!defined('S_IRWUGO') && define('S_IRWUGO', (S_IRUGO | S_IWUGO));

How File Permissions Work

When PHP is installed on your server by you or whoever runs the server, it uses the file permissions that are used by the Operating System running the server.. If you are smart or just lucky than you are running some type of BSD/Unix/Solaris/Linux/Sun based Operating system and PHP won't have any problems. If you are running on a Locked, proprietary OS like Windows, PHP will still work but it has to use a lot of shortcuts and hacks to basically "Pretend" to act like the OS is BSD/Unix, and some key features just won't be available.

The OS Permission Bits

Here's the file permissions my Linux server uses, and which PHP automatically uses. The code basically just defines the default permissions for files, and defines the file atributes for each file that you can access by using the stat function, which I've improved upon to make things easier.

Download: POSIX Standard: 5.6 File Characteristicssys/stat.h

Protection bits for File Owner

#define S_IRWXU 00700
#define S_IRUSR 00400
#define S_IWUSR 00200
#define S_IXUSR 00100

Protection bits for File Group

#define S_IRWXG 00070
#define S_IRGRP 00040
#define S_IWGRP 00020
#define S_IXGRP 00010

Protection bits for All Others

#define S_IRWXO 00007
#define S_IROTH 00004
#define S_IWOTH 00002
#define S_IXOTH 00001

Some Example Permissions

0477 // owner has read only, other and group has rwx 0677 // owner has rw only, other and group has rwx

0444 // all have read only 0666 // all have rw only

0400 // owner has read only, group and others have no permission 0600 // owner has rw only, group and others have no permission

0470 // owner has read only, group has rwx, others have no permission 0407 // owner has read only, other has rwx, group has no permission

0670 // owner has rw only, group has rwx, others have no permission 0607 // owner has rw only, group has no permission and others have rwx

What's a File

A file is not merely its contents, a name, and a file type. A file also has an owner (a user ID), a group (a group ID), permissions (what the owner can do with the file, what people in the group can do, and what everyone else can do), various timestamps, and other information. Collectively, we call these a file's attributes.

Structure of File Mode Bits

The file mode bits have two parts: the file permission bits, which control ordinary access to the file, and special mode bits, which affect only some files.

There are three kinds of permissions that a user can have for a file:

  1. permission to read the file. For directories, this means permission to list the contents of the directory.
  2. permission to write to (change) the file. For directories, this means permission to create and remove files in the directory.
  3. permission to execute the file (run it as a program). For directories, this means permission to access files in the directory.

There are three categories of users who may have different permissions to perform any of the above operations on a file:

  1. the file's owner.
  2. other users who are in the file's group
  3. everyone else.

Files are given an owner and group when they are created. Usually the owner is the current user and the group is the group of the directory the file is in, but this varies with the operating system, the file system the file is created on, and the way the file is created. You can change the owner and group of a file by using the chown and chgrp commands.

In addition to the three sets of three permissions listed above, the file mode bits have three special components, which affect only executable files (programs) and, on most systems, directories:

  1. Set the process's effective user ID to that of the file upon execution (called the set-user-ID bit, or sometimes the setuid bit). For directories on a few systems, give files created in the directory the same owner as the directory, no matter who creates them, and set the set-user-ID bit of newly-created subdirectories.
  2. Set the process's effective group ID to that of the file upon execution (called the set-group-ID bit, or sometimes the setgid bit). For directories on most systems, give files created in the directory the same group as the directory, no matter what group the user who creates them is in, and set the set-group-ID bit of newly-created subdirectories.
  3. Prevent unprivileged users from removing or renaming a file in a directory unless they own the file or the directory; this is called the restricted deletion flag for the directory, and is commonly found on world-writable directories like /tmp.

For regular files on some older systems, save the program's text image on the swap device so it will load more quickly when run; this is called the sticky bit.

Setting Permissions

The basic symbolic operations on a file's permissions are adding, removing, and setting the permission that certain users have to read, write, and execute or search the file. These operations have the following format:

users operation permissions

The spaces between the three parts above are shown for readability only; symbolic modes cannot contain spaces. The users part tells which users' access to the file is changed. It consists of one or more of the following letters (or it can be empty). When more than one of these letters is given, the order that they are in does not matter.

  • u - the user who owns the file.
  • g - other users who are in the file's group.
  • o - all other users.
  • a - all users; the same as ugo.

The operation part tells how to change the affected users' access to the file, and is one of the following symbols:

  • + - to add the permissions to whatever permissions the users already have for the file.
  • - - to remove the permissions from whatever permissions the users already have for the file.
  • = - to make the permissions the only permissions that the users have for the file.

The permissions part tells what kind of access to the file should be changed; it is normally zero or more of the following letters. As with the users part, the order does not matter when more than one letter is given. Omitting the permissions part is useful only with the = operation, where it gives the specified users no access at all to the file.

  • r - the permission the users have to read the file.
  • w - the permission the users have to write to the file.
  • x - the permission the users have to execute the file, or search it if it is a directory.

For example, to give everyone permission to read and write a regular file, but not to execute it, use:

a=rw

To remove write permission for all users other than the file's owner, use:

go-w

The above command does not affect the access that the owner of the file has to it, nor does it affect whether other users can read or execute the file.

To give everyone except a file's owner no permission to do anything with that file, use the mode below. Other users could still remove the file, if they have write permission on the directory it is in.

go=

Another way to specify the same thing is:

og-rwx

Copying Existing Permissions

You can base a file's permissions on its existing permissions. To do this, instead of using a series of r, w, or x letters after the operator, you use the letter u, g, or o. For example, the mode

o+g

adds the permissions for users who are in a file's group to the permissions that other users have for the file. Thus, if the file started out as mode 664 (rw-rw-r--), the above mode would change it to mode 666 (rw-rw-rw-). If the file had started out as mode 741 (rwxr----x), the above mode would change it to mode 745 (rwxr--r-x). The - and = operations work analogously.

Umask and Protection

If the users part of a symbolic mode is omitted, it defaults to a (affect all users), except that any permissions that are set in the system variable umask are not affected. The value of umask can be set using the umask command. Its default value varies from system to system.

Omitting the users part of a symbolic mode is generally not useful with operations other than +. It is useful with + because it allows you to use umask as an easily customizable protection against giving away more permission to files than you intended to. As an example, if umask has the value 2, which removes write permission for users who are not in the file's group, then the mode:

+w

adds permission to write to the file to its owner and to other users who are in the file's group, but not to other users. In contrast, the mode:

a+w

ignores umask, and does give write permission for the file to all users.

Directories, Set-User-ID and Set-Group-ID Bits

On most systems, if a directory's set-group-ID bit is set, newly created subfiles inherit the same group as the directory, and newly created subdirectories inherit the set-group-ID bit of the parent directory. On a few systems, a directory's set-user-ID bit has a similar effect on the ownership of new subfiles and the set-user-ID bits of new subdirectories. These mechanisms let users share files more easily, by lessening the need to use chmod or chown to share new files.

These convenience mechanisms rely on the set-user-ID and set-group-ID bits of directories. If commands like chmod and mkdir routinely cleared these bits on directories, the mechanisms would be less convenient and it would be harder to share files. Therefore, a command like chmod does not affect the set-user-ID or set-group-ID bits of a directory unless the user specifically mentions them in a symbolic mode, or sets them in a numeric mode. For example, on systems that support set-group-ID inheritance:

# These commands leave the set-user-ID and
# set-group-ID bits of the subdirectories alone,
# so that they retain their default values.
mkdir A B C
chmod 755 A
chmod 0755 B
chmod u=rwx,go=rx C
mkdir -m 755 D
mkdir -m 0755 E
mkdir -m u=rwx,go=rx F

If you want to try to set these bits, you must mention them explicitly in the symbolic or numeric modes, e.g.:

# These commands try to set the set-user-ID
# and set-group-ID bits of the subdirectories.
mkdir G H
chmod 6755 G
chmod u=rwx,go=rx,a+s H
mkdir -m 6755 I
mkdir -m u=rwx,go=rx,a+s J

If you want to try to clear these bits, you must mention them explicitly in a symbolic mode, e.g.:

# This command tries to clear the set-user-ID
# and set-group-ID bits of the directory D.
chmod a-s D

Numeric Modes

The permissions granted to the user, to other users in the file's group, and to other users not in the file's group each require three bits, which are represented as one octal digit. The three special mode bits also require one bit each, and they are as a group represented as another octal digit. Here is how the bits are arranged, starting with the lowest valued bit:

Other users not in the file's group:

1 Execute/search
2 Write
4 Read

Other users in the file's group:

10 Execute/search
20 Write
40 Read

The file's owner:

100 Execute/search
200 Write
400 Read

Special mode bits:

1000 Restricted deletion flag or sticky bit
2000 Set group ID on execution
4000 Set user ID on execution

For example, numeric mode 4755 corresponds to symbolic mode u=rwxs,go=rx, and numeric mode 664 corresponds to symbolic mode ug=rw,o=r. Numeric mode 0 corresponds to symbolic mode a=.

Apache's Internal Bits (hex)

#define APR_FPROT_USETID   0x8000 /* Set user id */
#define APR_FPROT_UREAD   0x0400 /* Read by user */
#define APR_FPROT_UWRITE   0x0200 /* Write by user */
#define APR_FPROT_UEXECUTE 0x0100 /* Execute by user */
 
#define APR_FPROT_GSETID   0x4000 /* Set group id */
#define APR_FPROT_GREAD   0x0040 /* Read by group */
#define APR_FPROT_GWRITE   0x0020 /* Write by group */
#define APR_FPROT_GEXECUTE 0x0010 /* Execute by group */
 
#define APR_FPROT_WSTICKY 0x2000 /* Sticky bit */
#define APR_FPROT_WREAD   0x0004 /* Read by others */
#define APR_FPROT_WWRITE 0x0002 /* Write by others */
#define APR_FPROT_WEXECUTE 0x0001 /* Execute by others */
 
#define APR_FPROT_OS_DEFAULT  0x0FFF /* use OS's default permissions */
 
/* additional permission flags for apr_file_copy  and apr_file_append */
#define APR_FPROT_FILE_SOURCE_PERMS 0x1000 /* Copy source file's permissions */

Download: httpd-2.2.10/srclib/apr/file_io/unix/fileacc.c Here's some interesting bitmasking done by Apache that uses the defined bits set earlier by stat.h

apr_unix_perms2mode(perms){
 mode=0;
 if (perms & APR_USETID) mode |= S_ISUID;
 if (perms & APR_UREAD)  mode |= S_IRUSR;
 if (perms & APR_UWRITE) mode |= S_IWUSR;
 if (perms & APR_UEXECUTE) mode |= S_IXUSR;
 
 if (perms & APR_GSETID) mode |= S_ISGID;
 if (perms & APR_GREAD)  mode |= S_IRGRP;
 if (perms & APR_GWRITE) mode |= S_IWGRP;
 if (perms & APR_GEXECUTE) mode |= S_IXGRP;
 
 if (perms & APR_WSTICKY) mode |= S_ISVTX;
 if (perms & APR_WREAD)  mode |= S_IROTH;
 if (perms & APR_WWRITE) mode |= S_IWOTH;
 if (perms & APR_WEXECUTE) mode |= S_IXOTH;
 return mode;
}
 
apr_unix_mode2perms(mode){
 perms = 0;
 if (mode & S_ISUID)perms |= APR_USETID;
 if (mode & S_IRUSR)perms |= APR_UREAD;
 if (mode & S_IWUSR)perms |= APR_UWRITE;
 if (mode & S_IXUSR)perms |= APR_UEXECUTE;
 
 if (mode & S_ISGID)perms |= APR_GSETID;
 if (mode & S_IRGRP)perms |= APR_GREAD;
 if (mode & S_IWGRP)perms |= APR_GWRITE;
 if (mode & S_IXGRP)perms |= APR_GEXECUTE;
 
 if (mode & S_ISVTX)perms |= APR_WSTICKY;
 if (mode & S_IROTH)perms |= APR_WREAD;
 if (mode & S_IWOTH)perms |= APR_WWRITE;
 if (mode & S_IXOTH)perms |= APR_WEXECUTE;
 return perms;
}

umask

umask(int mask){
 arg1;
 int oldumask;
 int arg_count = ZEND_NUM_ARGS();
 oldumask = umask(077);
 
 if (BG(umask) == -1) BG(umask) = oldumask;
 if (arg_count == 0) umask(oldumask);
 
 convert_to_long_ex(arg1);
 umask(Z_LVAL_PP(arg1));
 RETURN_LONG(oldumask);
}

File Attributes

Each file will have attributes based on the type of OS.. Using the stat command you can view them.

Viewing stat results

* %a - Access rights in octal
* %A - Access rights in human readable form
* %b - Number of blocks allocated (see %B)
* %B - The size in bytes of each block reported by %b
* %d - Device number in decimal
* %D - Device number in hex
* %f - Raw mode in hex
* %F - File type
* %g - Group ID of owner
* %G - Group name of owner
* %h - Number of hard links
* %i - Inode number
* %n - File name
* %N - Quoted file name with dereference if symbolic link
* %o - I/O block size
* %s - Total size, in bytes
* %t - Major device type in hex
* %T - Minor device type in hex
* %u - User ID of owner
* %U - User name of owner
* %x - Time of last access
* %X - Time of last access as seconds since Epoch
* %y - Time of last modification
* %Y - Time of last modification as seconds since Epoch
* %z - Time of last change
* %Z - Time of last change as seconds since Epoch

The OS Attribute Bits

These defined values are what allows your operating system to determine the type of file being accessed.

#define S_IFMT   00170000  /* These bits determine file type. */
#define S_IFSOCK 0140000  /* Socket file */
#define S_IFLNK   0120000  /* Symbolic Link */
#define S_IFREG   0100000  /* Regular file */
#define S_IFDIR   0040000  /* Directory */
#define S_IFIFO  0010000   /* FIFO first-in-first-out file */
 
/* Such devices can be read either a character at a time or a "block" (many characters) at a time,
hence we say there are block special files and character special files. */
#define S_IFBLK   0060000  /* Block device */
#define S_IFCHR  0020000  /* Character device */

Special Permission Bits

#define S_ISUID  0004000  /* Set user ID on execution.  */
#define S_ISGID  0002000  /* Set group ID on execution.  */
#define S_ISVTX  0001000 /* Save swapped text after use (sticky).  */

Bitmasking to determine Filetype

#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)

Default Permission Masks

#define S_IRWXUGO (S_IRWXU|S_IRWXG|S_IRWXO)
#define S_IALLUGO (S_ISUID|S_ISGID|S_ISVTX|S_IRWXUGO)
#define S_IRUGO  (S_IRUSR|S_IRGRP|S_IROTH)
#define S_IWUGO  (S_IWUSR|S_IWGRP|S_IWOTH)
#define S_IXUGO  (S_IXUSR|S_IXGRP|S_IXOTH)

Download: httpd-2.2.10/srclib/apr/file_io/unix/filestat.c, this file shows a simple way to determine the type of file.

filetype_from_mode(mode){
 type;
 switch (mode & S_IFMT) {
  case S_IFREG:  type = APR_REG;  break;
  case S_IFDIR:  type = APR_DIR;  break;
  case S_IFLNK:  type = APR_LNK;  break;
 
  case S_IFCHR:  type = APR_CHR;  break;
  case S_IFBLK:  type = APR_BLK;  break;
  case S_IFFIFO: type = APR_PIPE; break;
  case S_IFSOCK: type = APR_SOCK; break;
  default: type = APR_UNKFILE;
 }
 return type;
}

Apache Stat Bits

#define APR_FINFO_LINK  0x00000001 /* Stat the link not the file itself if it is a link */
#define APR_FINFO_MTIME  0x00000010 /* Modification Time */
#define APR_FINFO_CTIME  0x00000020 /* Creation or inode-changed time */
#define APR_FINFO_ATIME  0x00000040 /* Access Time */
#define APR_FINFO_SIZE  0x00000100 /* Size of the file */
#define APR_FINFO_CSIZE  0x00000200 /* Storage size consumed by the file */
#define APR_FINFO_DEV  0x00001000 /* Device */
#define APR_FINFO_INODE  0x00002000 /* Inode */
#define APR_FINFO_NLINK  0x00004000 /* Number of links */
#define APR_FINFO_TYPE  0x00008000 /* Type */
#define APR_FINFO_USER  0x00010000 /* User */
#define APR_FINFO_GROUP  0x00020000 /* Group */
#define APR_FINFO_UPROT  0x00100000 /* User protection bits */
#define APR_FINFO_GPROT  0x00200000 /* Group protection bits */
#define APR_FINFO_WPROT  0x00400000 /* World protection bits */
#define APR_FINFO_ICASE  0x01000000 /* if dev is case insensitive */
#define APR_FINFO_NAME  0x02000000 /* name in proper case */
#define APR_FINFO_MIN  0x00008170 /* type, mtime, ctime, atime, size */
#define APR_FINFO_IDENT  0x00003000 /* dev and inode */
#define APR_FINFO_OWNER  0x00030000 /* user and group */
#define APR_FINFO_PROT  0x00700000 /* all protections */
#define APR_FINFO_NORM  0x0073b170 /* an atomic unix apr_stat() */
#define APR_FINFO_DIRENT 0x02000000 /* an atomic unix apr_dir_read() */

The Apache file information structure.

apr_uid_t user;  /* The user id that owns the file */
apr_gid_t group;  /* The group id that owns the file */
apr_ino_t inode; /* The inode of the file. */
apr_dev_t device; /* The id of the device the file is on. */
apr_int32_t nlink; /* The number of hard links to the file. */
apr_off_t size;  /* The size of the file */
apr_off_t csize; /* The storage size consumed by the file */
apr_time_t atime; /* The time the file was last accessed */
apr_time_t mtime; /* The time the file was last modified */
apr_time_t ctime; /* The time the file was created, or the inode was last changed */
const char *fname; /* The pathname of the file (possibly unrooted) */
const char *name; /* The file's name (no path) in filesystem case */

File Time Attributes

touch

If changing both the access and modification times to the current time, touch can change the timestamps for files that the user running it does not own but has write permission for. Otherwise, the user must own the files.

Although touch provides options for changing two of the times the times of last access and modification of a file, there is actually a third one as well: the inode change time. This is often referred to as a file's ctime. The inode change time represents the time when the file's meta-information last changed. One common example of this is when the permissions of a file change. Changing the permissions doesn't access the file, so the atime doesn't change, nor does it modify the file, so the mtime doesn't change. Yet, something about the file itself has changed, and this must be noted somewhere. This is the job of the ctime field. This is necessary, so that, for example, a backup program can make a fresh copy of the file, including the new permissions value. Another operation that modifies a file's ctime without affecting the others is renaming. In any case, it is not possible, in normal operations, for a user to change the ctime field to a user-specified value.

Shared hosting user security

WebHost allows you to create multiple users per account. Each user can have domain assigned to its home home directory accessible via FTP or SSH/SCP. The problem with multiple users on the same account is that they share the same default unix group, and default permissions allow their files to be easily modified by the members of this group. Usually this doesn't pose a problem as each user is probably trusted by account owner to not to mess with others files, but if one of the users have their web application hacked then all other users on the same account will be in danger.

By default all files in your account are created with 644 privileges and directories are with 775. That means any user can read your files and any user from the same account can move and add files in your freshly made directories. Your home directory is different, though. By default it carries 751 attribute meaning that only members of your group can see your files, but can't add any new. These group access schemes are possible, because every user in your account has its primary/default group set to "pgxxxxxx", which is assigned to every new file you create by default. The normal way to secure users from web-intrusion is to assign a separate group to the web-server user, removing it from default group. This way, exploited scripts will not be able to traverse into home directories of other users on your account. To allow account users to update centralized web-site they could be added to web-site group explicitly. But this "normal way" doesn't work with DreamHost, because you can't delete web-user from the default group and unless you set access for every new file explicitly, it will be possible for an intruder to read it.

To make managing privileges easier in interactive sessions "umask 007" command can be specified in your .bash_profile - this makes all new files carry xx0 mask. You also need to control your scripts (web based or cron/shell) so that they set mask for critical files explicitly. To secure account users from access by means of hacked user script you would also like to define another group for every user in your account and change group ownership of the user's home directory to that group with "set gid" bit set (and optional umask 007 in .bash_profile).

Therefore, to secure your users from web-intrusion you need to:

  1. Add a separate user and group for every domain where apache will be running
  2. Add a separate group for other user accounts
  3. Change the default group for new files created by your users by changing the group of their home directory and setting "set gid" bit for it (it is impossible to do this with FTP accounts, therefore you will need to login in each account via SSH)
  4. Add users who need access to web-site into the web-user group
  5. Optionally set umask 007 in .bash_profile for every user to tweak default WebHost775/664 permissions to something like 770/660 for directories and files that are not meant to be read by Apache (660 could also be used for all web scripts including .php as they are not read by dhapache CGI, but merely executed)

Apache Security

All your web files that need to be read by Apache should be readable by everyone as Apache itself is run under dhapache user. However, executable scripts like .php are executed under your own user and do not have to be world readable as they are not actually read by Apache, but executed via suEXEC. Quite the opposite - to prevent your code or database settings from being messed by any third-parties you SHOULD set permissions to these files explicitly to something like 640 or even 600 depending on who do you trust.

Multiuser security setup example

For our example, we will create a rainforce_www user and a aapp_www group for serving web files with apache and setup a rainforce user with a 'aapp group to manage mail and keep other files on DH privately. Since these records already exist, you will need to subsitute your own names.

  • Login to create the users rainforce_www and rainforce with shell access.
  • Create two groups - aapp_www and aapp. Note that users created in previous step are still members of the same default pgxxxxxx group.
  • Add rainforce_www to 'the 'aapp_www group and rainforce to both the aapp_www and aapp groups
  • Move your domain to rainforce_www account (mine is rainforce.org)
  • Now login to SSH with your rainforce_www user and change the default group for your home directory with "sgid" bit set to make all current and new files/directories created in this directory have the same aapp_www group.
 $ chgrp -R aapp_www .
 $ chmod 2751 .
 $ chmod 2771 rainforce.org

By setting 2771 the directory will be writable by the owner, the group and will be only executable by others. The contents of an executable only directory cannot be listed, but the files inside it can be read (if the permissions of the file allow it). It is important that the directory can be executable in order to allow static content (e.g. .html files) inside it to be read. Remember that directories you don't want anyone to have web access to, should be 0770 (writable by the owner and group, or 0750 writable by the owner and readable by group). Such strict permissions should by applied to password files, php include files or databases files (such as SQLite, BDB, etc).

  • Do the same for rainforce user, but specify aapp group instead.
 $ chgrp -R aapp .
 $ chmod 2751 .
  • Optionally modify umask in .bash_profile in user's home to 007 to make all files created by this user have 660 permissions set by default. If you want that newly created files by accessible by the web, you need to manually setup it's permissions to 664.

Now I can login as the user "rainforce" and update the web-site in the ../rainforce_www/rainforce.org directory. There is one more setup needed. Because files copied from other accounts can have 644 permissions set instead of 664, you need a script which will update permissions to 664 or 660 to allow other group members modify such files.

SSH key fingerprints

Just gen your own I guess

External Links

Original Article from DreamHost Wiki

Content is available under GNU Free Documentation License 1.2.

Example File Permission Bits

/usr/lib/w3m/cgi-bin/dirlist.cgi

sub utype {
  local($_) = @_;
  local(%T) = (
    0010000, 'PIPE',
    0020000, 'CHR',
    0040000, 'DIR',
    0060000, 'BLK',
    0100000, 'FILE',
    0120000, 'LINK',
    0140000, 'SOCK',
  );
  return $T{($_ & 0170000)} || 'FILE';
}
 
sub umode {
  local($_) = @_;
  local(%T) = (
    0010000, 'p',
    0020000, 'c',
    0040000, 'd',
    0060000, 'b',
    0100000, '-',
    0120000, 'l',
    0140000, 's',
  );
 
  return ($T{($_ & 0170000)} || '-')
     . (($_ & 00400) ? 'r' : '-')
     . (($_ & 00200) ? 'w' : '-')
     . (($_ & 04000) ? 's' :
       (($_ & 00100) ? 'x' : '-'))
     . (($_ & 00040) ? 'r' : '-')
     . (($_ & 00020) ? 'w' : '-')
     . (($_ & 02000) ? 's' :
       (($_ & 00010) ? 'x' : '-'))
     . (($_ & 00004) ? 'r' : '-')
     . (($_ & 00002) ? 'w' : '-')
     . (($_ & 01000) ? 't' :
       (($_ & 00001) ? 'x' : '-'));
}

/usr/lib/perl/5.8.4/linux/stat.ph

        eval 'sub S_IFMT () {00170000;}' unless defined(&S_IFMT);
        eval 'sub S_IFSOCK () {0140000;}' unless defined(&S_IFSOCK);
        eval 'sub S_IFLNK () {0120000;}' unless defined(&S_IFLNK);
        eval 'sub S_IFREG () {0100000;}' unless defined(&S_IFREG);
        eval 'sub S_IFBLK () {0060000;}' unless defined(&S_IFBLK);
        eval 'sub S_IFDIR () {0040000;}' unless defined(&S_IFDIR);
        eval 'sub S_IFCHR () {0020000;}' unless defined(&S_IFCHR);
        eval 'sub S_IFIFO () {0010000;}' unless defined(&S_IFIFO);
        eval 'sub S_ISUID () {0004000;}' unless defined(&S_ISUID);
        eval 'sub S_ISGID () {0002000;}' unless defined(&S_ISGID);
        eval 'sub S_ISVTX () {0001000;}' unless defined(&S_ISVTX);
        eval 'sub S_ISLNK {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFLNK));
        }' unless defined(&S_ISLNK);
        eval 'sub S_ISREG {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFREG));
        }' unless defined(&S_ISREG);
        eval 'sub S_ISDIR {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFDIR));
        }' unless defined(&S_ISDIR);
        eval 'sub S_ISCHR {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFCHR));
        }' unless defined(&S_ISCHR);
        eval 'sub S_ISBLK {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFBLK));
        }' unless defined(&S_ISBLK);
        eval 'sub S_ISFIFO {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFIFO));
        }' unless defined(&S_ISFIFO);
        eval 'sub S_ISSOCK {
            local($m) = @_;
            eval q(((($m) &  &S_IFMT) ==  &S_IFSOCK));
        }' unless defined(&S_ISSOCK);
        eval 'sub S_IRWXU () {00700;}' unless defined(&S_IRWXU);
        eval 'sub S_IRUSR () {00400;}' unless defined(&S_IRUSR);
        eval 'sub S_IWUSR () {00200;}' unless defined(&S_IWUSR);
        eval 'sub S_IXUSR () {00100;}' unless defined(&S_IXUSR);
        eval 'sub S_IRWXG () {00070;}' unless defined(&S_IRWXG);
        eval 'sub S_IRGRP () {00040;}' unless defined(&S_IRGRP);
        eval 'sub S_IWGRP () {00020;}' unless defined(&S_IWGRP);
        eval 'sub S_IXGRP () {00010;}' unless defined(&S_IXGRP);
        eval 'sub S_IRWXO () {00007;}' unless defined(&S_IRWXO);
        eval 'sub S_IROTH () {00004;}' unless defined(&S_IROTH);
        eval 'sub S_IWOTH () {00002;}' unless defined(&S_IWOTH);
        eval 'sub S_IXOTH () {00001;}' unless defined(&S_IXOTH);
    }
    if(defined(&__KERNEL__)) {
        eval 'sub S_IRWXUGO () {( &S_IRWXU| &S_IRWXG| &S_IRWXO);}' unless defined(&S_IRWXUGO);
        eval 'sub S_IALLUGO () {( &S_ISUID| &S_ISGID| &S_ISVTX| &S_IRWXUGO);}' unless defined(&S_IALLUGO);
        eval 'sub S_IRUGO () {( &S_IRUSR| &S_IRGRP| &S_IROTH);}' unless defined(&S_IRUGO);
        eval 'sub S_IWUGO () {( &S_IWUSR| &S_IWGRP| &S_IWOTH);}' unless defined(&S_IWUGO);
        eval 'sub S_IXUGO () {( &S_IXUSR| &S_IXGRP| &S_IXOTH);}' unless defined(&S_IXUGO);
        require 'linux/types.ph';
        require 'linux/time.ph';
    }
 

Mozilla-Source 1.8a2

/* notice that these valuse are octal. */
const PERM_IRWXU = 00700;  /* read, write, execute/search by owner */
const PERM_IRUSR = 00400;  /* read permission, owner */
const PERM_IWUSR = 00200;  /* write permission, owner */
const PERM_IXUSR = 00100;  /* execute/search permission, owner */
const PERM_IRWXG = 00070;  /* read, write, execute/search by group */
const PERM_IRGRP = 00040;  /* read permission, group */
const PERM_IWGRP = 00020;  /* write permission, group */
const PERM_IXGRP = 00010;  /* execute/search permission, group */
const PERM_IRWXO = 00007;  /* read, write, execute/search by others */
const PERM_IROTH = 00004;  /* read permission, others */
const PERM_IWOTH = 00002;  /* write permission, others */
const PERM_IXOTH = 00001;  /* execute/search permission, others */
 
const MODE_RDONLY   = 0x01;
const MODE_WRONLY   = 0x02;
const MODE_RDWR     = 0x04;
const MODE_CREATE   = 0x08;
const MODE_APPEND   = 0x10;
const MODE_TRUNCATE = 0x20;
const MODE_SYNC     = 0x40;
const MODE_EXCL     = 0x80;

/usr/include/libpng12/png.h

/* Transform masks for the high-level interface */
#define PNG_TRANSFORM_IDENTITY       0x0000    /* read and write */
#define PNG_TRANSFORM_STRIP_16       0x0001    /* read only */
#define PNG_TRANSFORM_STRIP_ALPHA    0x0002    /* read only */
#define PNG_TRANSFORM_PACKING        0x0004    /* read and write */
#define PNG_TRANSFORM_PACKSWAP       0x0008    /* read and write */
#define PNG_TRANSFORM_EXPAND         0x0010    /* read only */
#define PNG_TRANSFORM_INVERT_MONO    0x0020    /* read and write */
#define PNG_TRANSFORM_SHIFT          0x0040    /* read and write */
#define PNG_TRANSFORM_BGR            0x0080    /* read and write */
#define PNG_TRANSFORM_SWAP_ALPHA     0x0100    /* read and write */
#define PNG_TRANSFORM_SWAP_ENDIAN    0x0200    /* read and write */
#define PNG_TRANSFORM_INVERT_ALPHA   0x0400    /* read and write */
#define PNG_TRANSFORM_STRIP_FILLER   0x0800    /* WRITE only */

/usr/lib/python2.4/stat.py

# Extract bits from the mode
 
def S_IMODE(mode):
    return mode & 07777
 
def S_IFMT(mode):
    return mode & 0170000
 
# Constants used as S_IFMT() for various file types
# (not all are implemented on all systems)
 
S_IFDIR  = 0040000
S_IFCHR  = 0020000
S_IFBLK  = 0060000
S_IFREG  = 0100000
S_IFIFO  = 0010000
S_IFLNK  = 0120000
S_IFSOCK = 0140000
 
# Functions to test for each file type
 
def S_ISDIR(mode):
    return S_IFMT(mode) == S_IFDIR
 
def S_ISCHR(mode):
    return S_IFMT(mode) == S_IFCHR
 
def S_ISBLK(mode):
    return S_IFMT(mode) == S_IFBLK
 
def S_ISREG(mode):
    return S_IFMT(mode) == S_IFREG
 
def S_ISFIFO(mode):
    return S_IFMT(mode) == S_IFIFO
 
def S_ISLNK(mode):
    return S_IFMT(mode) == S_IFLNK
 
def S_ISSOCK(mode):
    return S_IFMT(mode) == S_IFSOCK
 
# Names for permission bits
 
S_ISUID = 04000
S_ISGID = 02000
S_ENFMT = S_ISGID
S_ISVTX = 01000
S_IREAD = 00400
S_IWRITE = 00200
S_IEXEC = 00100
S_IRWXU = 00700
S_IRUSR = 00400
S_IWUSR = 00200
S_IXUSR = 00100
S_IRWXG = 00070
S_IRGRP = 00040
S_IWGRP = 00020
S_IXGRP = 00010
S_IRWXO = 00007
S_IROTH = 00004
S_IWOTH = 00002
S_IXOTH = 00001

/usr/include/bits/stat.h

/* Encoding of the file mode.  */
 
#define __S_IFMT        0170000 /* These bits determine file type.  */
 
/* File types.  */
#define __S_IFDIR       0040000 /* Directory.  */
#define __S_IFCHR       0020000 /* Character device.  */
#define __S_IFBLK       0060000 /* Block device.  */
#define __S_IFREG       0100000 /* Regular file.  */
#define __S_IFIFO       0010000 /* FIFO.  */
#define __S_IFLNK       0120000 /* Symbolic link.  */
#define __S_IFSOCK      0140000 /* Socket.  */
 
/* POSIX.1b objects.  Note that these macros always evaluate to zero.  But
   they do it by enforcing the correct use of the macros.  */
#define __S_TYPEISMQ(buf)  ((buf)->st_mode - (buf)->st_mode)
#define __S_TYPEISSEM(buf) ((buf)->st_mode - (buf)->st_mode)
#define __S_TYPEISSHM(buf) ((buf)->st_mode - (buf)->st_mode)
 
/* Protection bits.  */
 
#define __S_ISUID       04000   /* Set user ID on execution.  */
#define __S_ISGID       02000   /* Set group ID on execution.  */
#define __S_ISVTX       01000   /* Save swapped text after use (sticky).  */
#define __S_IREAD       0400    /* Read by owner.  */
#define __S_IWRITE      0200    /* Write by owner.  */
#define __S_IEXEC       0100    /* Execute by owner.  */

/usr/include/linux/nfs.h

#define NFS_FIFO_DEV    (-1)
#define NFSMODE_FMT     0170000
#define NFSMODE_DIR     0040000
#define NFSMODE_CHR     0020000
#define NFSMODE_BLK     0060000
#define NFSMODE_REG     0100000
#define NFSMODE_LNK     0120000
#define NFSMODE_SOCK    0140000
#define NFSMODE_FIFO    0010000

/usr/include/linux/nfs3.h

#define NFS3_FIFO_DEV           (-1)
#define NFS3MODE_FMT            0170000
#define NFS3MODE_DIR            0040000
#define NFS3MODE_CHR            0020000
#define NFS3MODE_BLK            0060000
#define NFS3MODE_REG            0100000
#define NFS3MODE_LNK            0120000
#define NFS3MODE_SOCK           0140000
#define NFS3MODE_FIFO           0010000
 
/* Flags for access() call */
#define NFS3_ACCESS_READ        0x0001
#define NFS3_ACCESS_LOOKUP      0x0002
#define NFS3_ACCESS_MODIFY      0x0004
#define NFS3_ACCESS_EXTEND      0x0008
#define NFS3_ACCESS_DELETE      0x0010
#define NFS3_ACCESS_EXECUTE     0x0020
#define NFS3_ACCESS_FULL        0x003f

/usr/include/linux/stat.h

#define S_IFMT  00170000
#define S_IFSOCK 0140000
#define S_IFLNK  0120000
#define S_IFREG  0100000
#define S_IFBLK  0060000
#define S_IFDIR  0040000
#define S_IFCHR  0020000
#define S_IFIFO  0010000
#define S_ISUID  0004000
#define S_ISGID  0002000
#define S_ISVTX  0001000
 
#define S_ISLNK(m)      (((m) & S_IFMT) == S_IFLNK)
#define S_ISREG(m)      (((m) & S_IFMT) == S_IFREG)
#define S_ISDIR(m)      (((m) & S_IFMT) == S_IFDIR)
#define S_ISCHR(m)      (((m) & S_IFMT) == S_IFCHR)
#define S_ISBLK(m)      (((m) & S_IFMT) == S_IFBLK)
#define S_ISFIFO(m)     (((m) & S_IFMT) == S_IFIFO)
#define S_ISSOCK(m)     (((m) & S_IFMT) == S_IFSOCK)
 
#define S_IRWXU 00700
#define S_IRUSR 00400
#define S_IWUSR 00200
#define S_IXUSR 00100
 
#define S_IRWXG 00070
#define S_IRGRP 00040
#define S_IWGRP 00020
#define S_IXGRP 00010
 
#define S_IRWXO 00007
#define S_IROTH 00004
#define S_IWOTH 00002
#define S_IXOTH 00001

Further File Permissions Reading

Related PHP Functions

Special file types

Changing file attributes

Chmod, Umask, Stat, Fileperms, and File Permissions originally appeared on AskApache.com


Mod_Rewrite Security

$
0
0

AskApache.com

Here are some specific htaccess examples taken mostly from my WordPress Password Protection plugin, which does alot more than password protection as you will see from the following mod_rewrite examples. These are a few of the mod_rewrite uses that BlogSecurity declared pushed the boundaries of Mod_Rewrite! Some of these snippets are quite exotic and unlike anything you may have seen before, also only for those who understand them as they can kill a website pretty quick.

Directory Protection

Enable the DirectoryIndex Protection, preventing directory index listings and defaulting. [Disable]

Options -Indexes
DirectoryIndex index.html index.php /index.php

Password Protect wp-login.php

Requires a valid user/pass to access the login page[401]

<Files wp-login.php>
Order Deny,Allow
Deny from All
Satisfy Any
AuthName "Protected By AskApache"
AuthUserFile /home/askapache.com/.htpasswda1
AuthType Basic
Require valid-user
</Files>

Password Protect wp-admin

Requires a valid user/pass to access any non-static (css, js, images) file in this directory.[401]

Options -ExecCGI -Indexes +FollowSymLinks -Includes
DirectoryIndex index.php /index.php
Order Deny,Allow
Deny from All
Satisfy Any
AuthName "Protected By AskApache"
AuthUserFile /home/askapache.com/.htpasswda1
AuthType Basic
Require valid-user
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$">
Allow from All
</FilesMatch>
<FilesMatch "(async-upload)\.php$">
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
Allow from All
</FilesMatch>

Protect wp-content

Denies any Direct request for files ending in .php with a 403 Forbidden.. May break plugins/themes [401]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /wp-content/.*$ [NC]
RewriteCond %{REQUEST_FILENAME} !^.+flexible-upload-wp25js.php$
RewriteCond %{REQUEST_FILENAME} ^.+\.(php|html|htm|txt)$
RewriteRule .* - [F,NS,L]

Protect wp-includes

Denies any Direct request for files ending in .php with a 403 Forbidden.. May break plugins/themes [403]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /wp-includes/.*$ [NC]
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ /wp-includes/js/.+/.+\ HTTP/ [NC]
RewriteCond %{REQUEST_FILENAME} ^.+\.php$
RewriteRule .* - [F,NS,L]

Common Exploits

Block common exploit requests with 403 Forbidden. These can help alot, may break some plugins. [403]

RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ ///.*\ HTTP/ [NC,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\?\=?(http|ftp|ssl|https):/.*\ HTTP/ [NC,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\?\?.*\ HTTP/ [NC,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.(asp|ini|dll).*\ HTTP/ [NC,OR]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.(htpasswd|htaccess|aahtpasswd).*\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]

Stop Hotlinking

Denies any request for static files (images, css, etc) if referrer is not local site or empty. [403]

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{HTTP_REFERER} !^http://www.askapache.com.*$ [NC]
RewriteRule \.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$ - [F,NS,L]

Safe Request Methods

Denies any request not using GET,PROPFIND,POST,OPTIONS,PUT,HEAD[403]

RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST|PROPFIND|OPTIONS|PUT)$ [NC]
RewriteRule .* - [F,NS,L]

Forbid Proxies

Denies any POST Request using a Proxy Server. Can still access site, but not comment. See Perishable Press [403]

RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:VIA}%{HTTP:FORWARDED}%{HTTP:USERAGENT_VIA}%{HTTP:X_FORWARDED_FOR}%{HTTP:PROXY_CONNECTION} !^$ [OR]
RewriteCond %{HTTP:XPROXY_CONNECTION}%{HTTP:HTTP_PC_REMOTE_ADDR}%{HTTP:HTTP_CLIENT_IP} !^$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]

Real wp-comments-post.php

Denies any POST attempt made to a non-existing wp-comments-post.php[403]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*/wp-comments-post\.php.*\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]

HTTP PROTOCOL

Denies any badly formed HTTP PROTOCOL in the request, 0.9, 1.0, and 1.1 only[403]

RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ .+\ HTTP/(0\.9|1\.0|1\.1) [NC]
RewriteRule .* - [F,NS,L]

SPECIFY CHARACTERS

Denies any request for a url containing characters other than "a-zA-Z0-9.+/-?=&" - REALLY helps but may break your site depending on your links. [403]

RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ [a-zA-Z0-9\.\+_/\-\?\=\&amp;]+\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]

BAD Content Length

Denies any POST request that doesnt have a Content-Length Header[403]

RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:Content-Length} ^$
RewriteCond %{REQUEST_URI} !^/(wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]

BAD Content Type

Denies any POST request with a content type other than application/x-www-form-urlencoded|multipart/form-data[403]

RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:Content-Type} !^(application/x-www-form-urlencoded|multipart/form-data.*(boundary.*)?)$ [NC]
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]

Missing HTTP_HOST

Denies requests that dont contain a HTTP HOST Header.[403]

RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{HTTP_HOST} ^$
RewriteRule .* - [F,NS,L]

Bogus Graphics Exploit

Denies obvious exploit using bogus graphics[403]

RewriteCond %{HTTP:Content-Disposition} \.php [NC]
RewriteCond %{HTTP:Content-Type} image/.+ [NC]
RewriteRule .* - [F,NS,L]

No UserAgent, Not POST

Denies POST requests by blank user-agents. May prevent a small number of visitors from POSTING. [403]

RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP_USER_AGENT} ^-?$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteRule .* - [F,NS,L]

No Referer, No Comment

Denies any comment attempt with a blank HTTP_REFERER field, highly indicative of spam. May prevent some visitors from POSTING. [403]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*/wp-comments-post\.php.*\ HTTP/ [NC]
RewriteCond %{HTTP_REFERER} ^-?$
RewriteRule .* - [F,NS,L]

Trackback Spam

Denies obvious trackback spam. See Holy Shmoly! [403]

RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP_USER_AGENT} ^.*(opera|mozilla|firefox|msie|safari).*$ [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.+/trackback/?\ HTTP/ [NC]
RewriteRule .* - [F,NS,L]

Map all URIs except those corresponding to existing files to a handler

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule . /script.php

Map any request to a handler

In the case where all URIs should be sent to the same place (including potentially requests for static content) the method to use depends on the type of the handler. For php scripts, use: For other handlers such as php scripts, use:

RewriteEngine On
RewriteCond %{REQUEST_URI} !=/script.php
RewriteRule .* /script.php

And for CGI scripts:

ScriptAliasMatch .* /var/www/script.cgi

Map URIs corresponding to existing files to a handler instead

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f
RewriteCond %{REQUEST_URI} !=/script.php
RewriteRule .* /script.php

If the existing files you wish to have handled by your script have a common set of file extensions distinct from that of the hander, you can bypass mod_rewrite and use instead mod_actions. Let's say you want all .html and .tpl files to be dealt with by your script:

Action foo-action /script.php
AddHandler foo-action html tpl

Deny access if var=val contains the string foo.

RewriteCond %{QUERY_STRING} foo
RewriteRule ^/url - [F]

Removing the Query String

RewriteRule ^/url /url?

Adding to the Query String

Keep the existing query string using the Query String Append flag, but add var=val to the end.

RewriteRule ^/url /url?var=val [QSA]

Rewriting For Certain Query Strings

Rewrite URLs like http://askapache.com/url1?var=val to http://askapache.com/url2?var=val but don't rewrite if val isn't present.

RewriteCond %{QUERY_STRING} val
RewriteRule ^/url1 /url2

Modifying the Query String

Change any single instance of val in the query string to other_val when accessing /path. Note that %1 and %2 are back-references to the matched part of the regular expression in the previous RewriteCond.

RewriteCond %{QUERY_STRING} ^(.*)val(.*)$
RewriteRule /path /path?%1other_val%2

Mod_Rewrite Security originally appeared on AskApache.com


Optimized Vimrc with 256 Colorscheme

$
0
0

AskApache.com

This is 90% geared for purely console/terminal/pty/tty/ssh/putty/telnet/tmux/screen users. I've only just the past couple years started understanding why it was key to learn vim, in the past I never had the patience for it and preferred nano-like editors. Now vim is all I use when on linux, it's so much more productive.. especially with a customized vimrc file. This doesn't require a git checkout, a vim update, a bash update, an OS update, a plugin. No. This is a single file that I use on Arch Linux, NetBSD, FreeBSD, OpenBSD, Debian, Ubuntu, Cent OS, Red Hat, and that's it so far. This is geared for users who use SSH more than anything else. Of course, it works perfect on an X enabled box locally as well.

ScreenShot

Screenshot of this vimrc in action

Setup

I install this as /etc/vimrc if possible. Individual users can use a vim config file in their home directories.

source /etc/vimrc

To install for a single user just save it in their home dir at /home/username/.vimrc

Portability

For the portability needed to work on many different systems, this doesn't rely on any plugins other than those built into the default installation of vim 7.0. It works well on all types of consoles, and depending on the TERM environment variable (and whether it has the right term capabilities) it will load 256 color support or not. Usually on a new system I just scp this right over and it works without any modifications. But an ongoing Work in progress.

Optimized Vimrc

Download - Optimized vimrc

" Updated: Wed Feb 22 13:25:23 2012 by galileo@galileo
 
" For all key mappings like ', .' to reload vimrc
let maplocalleader=','
 
" BACKUPS, SWAPFILES, VIEWDIR, TMPDIR  "{{{1
" ================================================================================================================================================================
 
" SET RUNTIMEPATH {{{3
if isdirectory(expand("$HOME/.vim"))
  let $VIMRUNTIME=expand("$HOME/.vim")
  set runtimepath=$VIMRUNTIME
endif
 
" IF BKDIR IS NOT SET OR EMPTY, SET {{{3
if $BKDIR == ""
  let $BKDIR=expand("$HOME/.bk")
  if !isdirectory(expand("$BKDIR"))
    call mkdir(expand("$BKDIR"), "p", 0700)
  endif
endif
 
" MAKE DIRS IF mkdir exists {{{3
if exists("*mkdir")
  if !isdirectory(expand("$BKDIR/.vim/viewdir"))|call mkdir(expand("$BKDIR/.vim/viewdir"), "p", 0700)|endif
  if !isdirectory(expand("$BKDIR/.vim/tmp"))|call mkdir(expand("$BKDIR/.vim/tmp"), "p", 0700)|endif
  if !isdirectory(expand("$BKDIR/.vim/backups"))|call mkdir(expand("$BKDIR/.vim/backups"), "p", 0700)|endif
endif
 
" SETTINGS USING NEW DIRS {{{3
let &dir=expand("$BKDIR") . "/.vim"
let &viewdir=expand("$BKDIR") . "/.vim/viewdir"
let &backupdir=expand("$BKDIR") . "/.vim/backups"
"let &verbosefile=expand("$BKDIR") . "/.vim/vim-messages.
 
" VIMINFO {{{3
" COMMENTED OUT {{{4
"  "       Maximum number of lines saved for each register
"  %       When included, save and restore the buffer lis
"  '       Maximum number of previously edited files for which the marks are remembere
"  /       Maximum number of items in the search pattern history to be saved
"  :        Maximum number of items in the command-line history
"  <       Maximum number of lines saved for each register.
"   @       Maximum number of items in the input-line history
"  h       Disable the effect of 'hlsearch' when loading the viminfo
"  n       Name of the viminfo file.  The name must immediately follow the 'n'.  Must be the last oneEnvironment variables are expanded when opening the file, not when setting the option
"  r       Removable media.  The argument is a string
"  s       Maximum size of an item in Kbyte
"   }}}4 COMMENTED OUT
let &viminfo="%200,'200,/800,h,<500,:500,s150,r/tmp,r" . expand("$BKDIR") . "/.vim/tmp,n" . expand("$BKDIR") ."/.vim/.vinfo"
 
" CUSTOM FUNCTIONS "{{{1
" ================================================================================================================================================================
if !exists("AskApacheLoaded")
  let AskApacheLoaded=1
 
  " FUNCTION - LastMod {{{3
  " Warning, this is controlled by an autocmd triggered when closing the file that updates the file (in a great way)
  " Updated: Wed Feb 22 13:25:23 2012 by galileo@galileo
  function! LastMod()
    exe "silent! 1,20s/Updated: .*/" . printf('Updated: %s by %s@%s', strftime("%c"), expand("$LOGNAME"), hostname()) . "/e"
  endfunction
 
  " FUNCTION - LastModNow {{{3
  " An even better version than LastMod()
  function! LastModNow()
    call setline(line('.'), printf('%sUpdated: %s by %s@%s', printf(&commentstring, ' '), strftime("%c"), expand("$LOGNAME"), hostname()))
    "printf('%sUpdated: %s by %s@%s', printf(&commentstring, ' '), strftime("%c"), expand("$LOGNAME"), hostname())\|dd\|j\|dd<CR><ESC>
    "printf('Updated: %s by %s %s', strftime("%c"), expand("$LOGNAME@$HOSTNAME")) ."/e"
  endfunction
 
  " FUNCTION - AppendModeline {{{3
  " Append modeline after last line in buffer.  Use substitute() instead of printf() to handle '%%s' modeline
  function! AppendModeline()
    let l:modeline = printf(" vim: set ft=%s ts=%d sw=%d tw=%d foldmethod=%s :", &filetype, &tabstop, &shiftwidth, &textwidth, &foldmethod)
    let l:modeline = substitute(&commentstring, "%s", l:modeline, "")
    call append(line("$"), l:modeline)
  endfunction
 
  " FUNCTION - LastModAAZZZ {{{3
  " AA_UPDATED='01/24/12-00:56:00'
  function! LastModAAZZZ()
    exe "1,50s/AA_UPDATED=.*/AA_UPDATED='" . strftime("%c") . "'"
  endfunction
 
  " FUNCTION - StripTrailingWhitespace {{{3
  " automatically remove trailing whitespace before write
  function! StripTrailingWhitespace()
    normal mZ
    %s/\s\+$//e
    if line("'Z") != line(".")|echo "Stripped whitespace\n"|endif
    normal `Z
  endfunction
 
  " FUNCTION - MyTabL {{{3
  function! MyTabL()
    let s = ''|let t = tabpagenr()|let i = 1
    while i <= tabpagenr('$')
      let bl = tabpagebuflist(i)|let wn = tabpagewinnr(i)
      let s .= '%' . i . 'T'. (i == t ? '%1*' : '%2*') . '%*' . (i == t ? ' %#TabLineSel# ' : '%#TabLine#')
      let file = (i == t ? fnamemodify(bufname(bl[wn - 1]), ':p') : fnamemodify(bufname(bl[wn - 1]), ':t') )|if file == ''|let file = '[No Name]'|endif
      let s .= i.' '. file .(i == t ? ' ' : '')|let i += 1
    endwhile
    let s .= '%T%#TabLineFill#%=' . (tabpagenr('$') > 1 ? '%999XX' : 'X')
    return s
  endfunction
 
  " FUNCTION - DiffWithSaved {{{3
  " Diff with saved version of the file
  function! s:DiffWithSaved()
    let filetype=&ft
    diffthis
    vnew | r # | normal! 1Gdd
    diffthis
    exe "setlocal bt=nofile bh=wipe nobl noswf ro ft=" . filetype
  endfunction
  com! DiffSaved call s:DiffWithSaved()
 
  " FUNCTION - ShowWhitespace() {{{3
  function! ShowWhitespace(flags)
    let bad = ''
    let pat = []
    for c in split(a:flags, '\zs')
      if c == 'e'
        call add(pat, '\s\+$')
      elseif c == 'i'
        call add(pat, '^\t*\zs \+')
      elseif c == 's'
        call add(pat, ' \+\ze\t')
      elseif c == 't'
        call add(pat, '[^\t]\zs\t\+')
      else
        let bad .= c
      endif
    endfor
 
    if len(pat) > 0
      let s = join(pat, '\|')
      exec 'syntax match ExtraWhitespace "'.s.'" containedin=ALL'
    else
      syntax clear ExtraWhitespace
    endif
 
    if len(bad) > 0|echo 'ShowWhitespace ignored: '.bad|endif
  endfunction
 
  " FUNCTION - ToggleShowWhitespace {{{3
  " I use this all the time, it's mapped to , ts
  function! ToggleShowWhitespace()
    if !exists('b:ws_show')|let b:ws_show = 0|endif
    if !exists('b:ws_flags')|let b:ws_flags = 'est'|endif
    let b:ws_show = !b:ws_show
    if b:ws_show|call ShowWhitespace(b:ws_flags)|else|call ShowWhitespace('')|endif
  endfunction
 
endif
 
" DYNAMIC SETTINGS / COLORS / TERMINAL {{{1
" ================================================================================================================================================================
 
" DISABLE MOUSE NO GOOEYS {{{3
if has('mouse')|set mouse=|endif
 
" SET TITLESTRING {{{3
if has('title')|set titlestring=%t%(\ [%R%M]%)|endif
 
" SET TABLINE {{{3
if exists("*s:MyTabL")|set tabline=%!MyTabL()|endif
 
let g:vimsyn_folding='af'
 
"DISABLE FILETYPE-SPECIFIC MAPS {{{3
let no_plugin_maps=1
 
"}}}1 DYNAMIC SETTINGS / COLORS / TERMINAL
 
" OPTIONS "{{{1
" ===========================================================================================================================================================================
 
" BACKUP, FILE OPTIONS {{{2
" ================================================================================
set backup        " Make a backup before overwriting a file.  Leave it around after the file has been successfully written.
set backupcopy=auto " When writing a file and a backup is made, this option tells how it's done.  This is a comma separated list of words. - value: yes,no,auto - no:rename the file and write a new one
 
set swapfile
set swapsync=fsync
 
"}}}2 BACKUP, FILE OPTIONS
 
" BASIC SETTINGS "{{{2
" ================================================================================
set nocompatible    " vim, not vi.. must be first, because it changes other options as a side effect
set modeline
 
set statusline=%M%h%y\ %t\ %F\ %p%%\ %l/%L\ %=[%{&ff},%{&ft}]\ [a=\%03.3b]\ [h=\%02.2B]\ [%l,%v]
set title titlelen=150 titlestring=%(\ %M%)%(\ (%{expand(\"%:p:h\")})%)%(\ %a%)\ -\ %{v:servername}
 
"set tags=tags;/      " search recursively up for tags
 
set ttyfast        " we have a fast terminal
set scrolljump=5    " when scrolling up down, show at least 5 lines
"set ttyscroll=999    " make vim redraw screen instead of scrolling when there are more than 3 lines to be scrolled
 
"set tw=500        " default textwidth is a max of 5
 
set undolevels=10    " 50 undos - saved in memory
set updatecount=250    " switch every 250 chars, save swap
 
set whichwrap+=b,s,<,>,h,l,[,]      " backspaces and cursor keys wrap to
"set wildignore+=*.o,*~,.lo,*.exe,*.bak  " ignore object files
"set wildmenu              " menu has tab completion
"set wildmode=longest:full        " *wild* mode
set nowrap
 
set autoindent smartindent    " auto/smart indent
 
set autoread          " watch for file changes
 
set backspace=indent,eol,start  " backspace over all kinds of things
 
set cmdheight=1          " command line two lines high
set complete=.,w,b,u,U,t,i,d  " do lots of scanning on tab completion
set cursorline          " show the cursor line
"set enc=utf-8 fenc=utf-8    " utf-8
 
set history=3000        " keep 3000 lines of command line history
 
set keywordprg=TERM=mostlike\ man\ -s\ -Pless
 
set laststatus=2
 
"set lazyredraw          " don't redraw when don't have to
set linebreak          " wrap at 'breakat' instead of last char
set magic            " Enable the "magic"
 
set maxmem=25123  " 24 MB -  max mem in Kbyte to use for one buffer.  Max is 2000000
 
set noautowrite          " don't automagically write on :next
 
set noexpandtab          " no expand tabs to spaces"
set noruler          " show the line number on the bar
set nospell
set nohidden          " close the buffer when I close a tab (I use tabs more than buffers)
 
set noerrorbells visualbell t_vb= " Disable ALL bells
 
set number          " line numbers
 
set pastetoggle=<F11>
 
set scrolloff=3        " keep at least 3 lines above/below
set shiftwidth=3      " shift width
 
set showcmd          " Show us the command we're typing
set showfulltag        " show full completion tags
set showmode        " show the mode all the time
 
set sidescroll=2      " if wrap is off, this is fasster for horizontal scrolling
set sidescrolloff=2      "keep at least 5 lines left/right
 
set noguipty
 
set splitright
set splitbelow
 
set restorescreen=on " restore screen contents when vim exits -  disable withset t_ti= t_te=
 
"set sessionoptions=word,blank,buffers,curdir,folds,globals,help,localoptions,resize,sesdir,tabpages,winpos,winsize
set winheight=25
set winminheight=1  " minimal value for window height
"set winheight=30  " set the minimal window height
set equalalways    " all the windows are automatically sized same
set eadirection=both  " only equalalways for horizontally split windows
 
set hlsearch
 
set laststatus=2
 
set tabstop=4
set softtabstop=4
 
set shiftwidth=3
set switchbuf=usetab
 
set commentstring=#%s
 
set tabpagemax=55
set showtabline=2    " 2 always, 1 only if multiple tabs
set smarttab      " tab and backspace are smart
 
set foldmethod=marker
set foldenable
set foldcolumn=6        " the blank left-most bar left of the numbered lines
 
set incsearch          " incremental search
"set ignorecase          " search ignoring case
set sc              " override 'ignorecase' when pattern has upper case characters
set smartcase          " Ignore case when searching lowercase
 
set showmatch          " show matching bracket
set diffopt=filler,iwhite    " ignore all whitespace and sync"
set stal=2
 
"}}}1 OPTIONS
 
" PLUGIN SETTINGS {{{1
" ================================================================================================================================================================
" Settings for :TOhtml "{{{3
let html_number_lines=1
let html_use_css=1
let use_xhtml=1
"}}}1 PLUGIN SETTINGS
 
" COLORSCHEME IF MORE THAN 2 COLORS lol {{{1
" ================================================================================================================================================================
if &t_Co > 2
 
  if &term =~ "256"
 
    set bg=dark t_Co=256 vb
    let &t_vb="\<Esc>[?5h\<Esc>[?5l"  " flash screen for visual bell
 
    if filereadable(expand("$VIMRUNTIME/colors/askapachecode.vim"))
      colorscheme askapachecode
    elseif filereadable(expand("$HOME/.vim/colors/askapachecode.vim"))
      colorscheme askapachecode
    else
      colorscheme default
    endif
 
    filetype indent plugin on
    syntax on
 
  else
    " things like cfdisk, crontab -e, visudo, vless, etc.
    set term=linux
    set t_Co=8
    syntax off
    filetype indent plugin off
 
  endif
 
endif
 
"}}}1
 
" AUTOCOMMANDS "{{{1
" ===========================================================================================================================================================================
"if !exists(":DiffOrig") | command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis | endif
 
" auto load extensions for different file types
if has('autocmd')
 
  if !exists("autocommands_loaded")
    let autocommands_loaded = 1
 
    " JUMP TO LAST POS {{{3
    " When editing a file, always jump to the last known cursor position. Don't do it when the position is invalid or when inside an event handler
    " (happens when dropping a file on gvim). Also don't do it when the mark is in the first line, that is the default position when opening a file.
    au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif
 
    " CLEARMATCHES ON BUFWINLEAVE {{{3
    au BufWinLeave * call clearmatches()
 
    " STRIP TRAILING WHITESPACE {{{3
    autocmd BufWritePre *.cpp,*.hpp,*.i :call StripTrailingWhitespace()
 
    " AA_ZZZ LAST MOD {{{3
    autocmd BufWritePre,FileWritePre,TabLeave zzz_askapache-bash.sh ks|call LastModAAZZZ()|'s
 
    " SET VIM SETTINGS FOR AA_ZZZ SCRIPTS {{{3
    autocmd BufRead /etc/ZZZ/*.sh,.bash_profile,.bash_login,.bashrc,.bash_login_user,.bash_logout setlocal ts=4 sw=3 ft=sh foldmethod=marker tw=500 foldcolumn=7
 
    " INSERT CURRENT DATE AND TIME IN A *.SH FILE WHEN WRITING IT {{{3
    autocmd BufWritePre,FileWritePre *.*   ks|call LastMod()|'s
 
    " IMPROVE LEGIBILITY {{{3
    autocmd BufRead quickfix setlocal nobuflisted wrap number
 
    " SAVE BACKUPFILE AS BACKUPDIR/FILENAME-06-13-1331 {{{3
    autocmd BufWritePre * let &bex = strftime("-%m-%d-%H%M")
 
    " TMUX FILETYPE {{{3
    autocmd BufRead tmux.conf,.tmux.conf,.tmux*,*/tmux-sessions/* setlocal filetype=tmux foldmethod=marker
 
    " APACHE2 FILETYPE {{{3
    autocmd BufRead /opt/a*/conf/*,/etc/httpd/*.conf setlocal filetype=apache
 
    " SH FILETYPES {{{3
    autocmd BufRead *.sh,*.cron,*.bash setlocal filetype=sh
 
    " SYSLOG-NG FILETYPE {{{3
    autocmd BufRead syslog-ng.conf setlocal filetype=syslog-ng
 
    " COMMENTSTRING FOR VIM "{{{3
    au FileType vim setlocal commentstring="%s
 
    " COMMENTSTRING FOR XDEFAULTS "{{{3
    au FileType xdefaults setlocal foldmethod=marker foldlevel=2 commentstring=!%s
 
    " VIMRC {{{3
    augroup vimrc
      au BufReadPre * setlocal foldmethod=indent
      au BufWinEnter * if &fdm == 'indent' | set foldmethod=manual | endif
      au BufRead *.vim,vimrc,*.vimrc set filetype=vim ts=3 sw=3 tw=500 foldmethod=marker foldcolumn=6
    augroup END
 
    " AUTOMKVIEWS {{{3
    " Warning - this will save your settings for each file you edit and restore those settings when opened again - can fill up quick
    au BufWinLeave *.sh,*.conf,*.vim,*.c,*.txt,.htaccess,*.cgi,*.php,*.html,*.conf,vimrc mkview
    au BufWinEnter *.sh,*.conf,*.vim,*.c,*.txt,.htaccess,*.cgi,*.php,*.html,*.conf,vimrc silent loadview
    " }}}3
 
    " MAN RUNTIME - TODO REPLACE WITH TMUXES CTRL-M BINDING {{{3
    " Lets you type :Man anymanpage and it will load in vim, color-coded and searchable
    "runtime ftplugin/man.vim
 
  endif
 
endif
"}}}1
 
" MAPS "{{{1
" ===========================================================================================================================================================================
 
" FUNCTION MAPS {{{2
" ---------------------------------
" APPEND MODELINE {{{3
map <silent> <LocalLeader>ml :call AppendModeline()<CR>
 
" SHOW WHITESPACE {{{3
nnoremap <LocalLeader>ts :call ToggleShowWhitespace()<CR>
 
" SUDO A WRITE {{{3
command! W :execute ':silent w !sudo tee % > /dev/null' | :edit!
"cmap w!! %!sudo tee > /dev/null %
" :w !sudo tee > /dev/null %
 
" SET TABLINE {{{3
" My Personal Fav, inserts last-modified manually on current line when you press <F12> key
" call setline(1, printf('%sUpdated: %s by %s@%s', printf(&commentstring, ' '), strftime("%c"), expand("$LOGNAME"), hostname()))
if exists("*s:LastModNow")
  map <silent> <F12> :call LastModNow()<CR>
endif
 
" RELOAD VIMRC FILES {{{3
map <LocalLeader>. :mkview<CR>:unlet! AskApacheLoaded autocommands_loaded<CR>:mapclear<CR>:source /etc/vimrc<CR>:echoerr 'VIMRC RELOADED'<CR>
 
" SCROLLING MAPS {{{3
map <PageDown> :set scroll=0<CR>:set scroll^=2<CR>:set scroll-=1<CR><C-D>:set scroll=0<CR>
map <PageUp> :set scroll=0<CR>:set scroll^=2<CR>:set scroll-=1<CR><C-U>:set scroll=0<CR>
nnoremap <silent> <PageUp> <C-U><C-U>
vnoremap <silent> <PageUp> <C-U><C-U>
inoremap <silent> <PageUp> <C-\><C-O><C-U><C-\><C-O><C-U>
nnoremap <silent> <PageDown> <C-D><C-D>
vnoremap <silent> <PageDown> <C-D><C-D>
inoremap <silent> <PageDown> <C-\><C-O><C-D><C-\><C-O><C-D>
"}}}3
 
" KEY MAPS {{{2
" physically map keys to produce different key, type CTRL-V in insert mode followed by any key to see how vim sees it
" ----------------------------------------
imap <ESC>[8~ <End>
map <ESC>[8~ <End>
 
imap <ESC>[7~ <Home>
map <ESC>[7~ <Home>
 
" Basic Maps  {{{2
" ----------------------------------------
" TOGGLE PASTE MODE {{{3
map <LocalLeader>pm :set nonumber! foldcolumn=0<CR>
 
" REINDENT FILE {{{3
map <LocalLeader>ri G=gg<CR>
 
" CLEAR SPACES AT END OF LINE {{{3
map <LocalLeader>cs :%s/\s\+$//e<CR>
 
" Y YANKS FROM CURSOR TO $ {{{3
map Y y$
 
" DON'T USE EX MODE, USE Q FOR FORMATTING {{{3
map Q gq
map! ^H ^?
 
" NEXT SEARCH RESULT {{{3
map <silent> <LocalLeader>cn :cn<CR>
 
" WRAP? {{{3
map <silent> <LocalLeader>ww :ww
 
" ERR INSERTION {{{3
"map <silent> <LocalLeader>e <Home>A<C-R>=printf('%s', '_err "$0 $FUNCNAME:$LINENO FAILED WITH ARGS= $*"')<CR><Home><Esc>
 
" CUSTOM LINES FOR CODING {{{3
map <silent> <LocalLeader>l1 <Home>A<C-R>=printf('%s%s', printf(&commentstring, ' '), repeat('=', 160))<CR><Home><Esc>
map <silent> <LocalLeader>l2 <Home>A<C-R>=printf('%s%s', printf(&commentstring, ' '), repeat('=', 80))<CR><Home><Esc>
map <silent> <LocalLeader>l3 <Home>A<C-R>=printf('%s%s', printf(&commentstring, ' '), repeat('-', 40))<CR><Home><Esc>
map <silent> <LocalLeader>l4 <Home>A<C-R>=printf('%s%s', printf(&commentstring, ' '), repeat('-', 20))<CR><Home><Esc>
 
" CHANGE DIRECTORY TO THAT OF CURRENT FILE {{{3
nmap <LocalLeader>cd :cd%:p:h<CR>
 
" CHANGE LOCAL DIRECTORY TO THAT OF CURRENT FILE {{{3
nmap <LocalLeader>lcd :lcd%:p:h<CR>
 
" TOGGLE WRAPPING {{{3
nmap <LocalLeader>ww :set wrap!<CR>
nmap <LocalLeader>wo :set wrap<CR>
 
" TABS "{{{2
" ---------------------------------
 
" CREATE A NEW TAB {{{3
map <LocalLeader>tc :tabnew %<CR>
 
" LAST TAB {{{3
map <LocalLeader>t<Space> :tablast<CR>
 
" CLOSE A TAB {{{3
map <LocalLeader>tk :tabclose<CR>
 
" NEXT TAB {{{3
map <LocalLeader>tn :tabnext<CR>
 
" PREVIOUS TAB {{{3
map <LocalLeader>tp :tabprev<CR>
 
" FOLDS   "{{{2
" ---------------------------------
" Fold with paren begin/end matching
nmap F zf%
 
" When I use ,sf - return to syntax folding with a big foldcolumn
nmap <LocalLeader>sf :set foldcolumn=6 foldmethod=syntax<cr>
"}}}2
 
"}}}1
 
" HILITE "{{{1
" ===========================================================================================================================================================================
hi NonText cterm=NONE ctermfg=NONE
hi Search cterm=bold ctermbg=99 ctermfg=17
"}}}
 

Colorscheme

Here is a colorscheme file optimized for 256 colors. It will work if saved in ~/.vim/colors/askapachecode.vim or likewise in your runtimepath. Additionally, you could just paste it in the bottom of the above vimrc. The code really needs to be cleaned up, but it looks awesome.

Download - askapachecode - 256 Colors Vim Colorscheme

~/.vim/colors/askapachecode.vim

" Vim color file -- askapachecode
" Maintainer: AskApache <webmaster@askapache.com>
" Updated: Wed Feb 22 14:10:54 2012 by galileo@galileo
 
set background=dark
hi clear
 
if exists("syntax_on")|syntax reset|endif
 
let g:colors_name="askapachecode"
 
" Vim >= 7.0 specific colors
if version >= 700
 hi CursorLine ctermbg=236
 hi CursorColumn ctermbg=236
 hi MatchParen ctermfg=157 ctermbg=237 cterm=bold
 hi Pmenu ctermfg=255 ctermbg=238
 hi PmenuSel ctermfg=0 ctermbg=148
endif
 
" General colors
hi Cursor ctermbg=241
hi Normal ctermfg=253 ctermbg=232
hi NonText ctermfg=244 ctermbg=235
hi LineNr ctermfg=244 ctermbg=232
hi StatusLine ctermfg=253 ctermbg=238 cterm=italic
hi StatusLineNC ctermfg=246 ctermbg=238
hi VertSplit ctermfg=238 ctermbg=238
hi Folded ctermbg=4 ctermfg=248
hi Title ctermfg=254 cterm=bold
hi Visual ctermfg=254 ctermbg=4
hi SpecialKey ctermfg=244 ctermbg=236
 
hi pythonOperator ctermfg=103
 
hi Search cterm=NONE  
 
" basic highlight groups (:help highlight-groups) {{{1
 
" text {{{2
hi Normal ctermfg=white ctermbg=black cterm=NONE
hi Folded ctermfg=lightgray ctermbg=black cterm=underline
hi LineNr ctermfg=darkgray ctermbg=NONE cterm=NONE
hi Directory ctermfg=cyan ctermbg=NONE cterm=NONE
hi NonText ctermfg=yellow ctermbg=NONE cterm=NONE
hi SpecialKey ctermfg=green ctermbg=NONE cterm=NONE
 
hi DiffAdd ctermfg=white ctermbg=darkblue cterm=NONE
hi DiffChange ctermfg=black ctermbg=darkmagenta cterm=NONE
hi DiffDelete ctermfg=black ctermbg=red cterm=bold
hi DiffText ctermfg=white ctermbg=green cterm=bold
 
" borders / separators / menus {{{2
hi FoldColumn ctermfg=lightgray ctermbg=darkgray cterm=NONE
hi SignColumn ctermfg=lightgray ctermbg=darkgray cterm=NONE
hi Pmenu ctermfg=white ctermbg=darkgray cterm=NONE
hi PmenuSel ctermfg=white ctermbg=lightblue cterm=NONE
hi PmenuSbar ctermfg=black ctermbg=black cterm=NONE
hi PmenuThumb ctermfg=gray ctermbg=gray cterm=NONE
 
hi StatusLine ctermfg=black ctermbg=white cterm=bold
hi StatusLineNC ctermfg=darkgray ctermbg=white cterm=NONE
hi WildMenu ctermfg=white ctermbg=darkblue cterm=bold
hi VertSplit ctermfg=white ctermbg=white cterm=NONE
 
if &t_Co == 256|hi TabLine ctermfg=15 ctermbg=242 term=underline|else|hi TabLine ctermfg=grey ctermbg=white term=underline|endif
"hi TabLine ctermfg=white ctermbg=white cterm=NONE
hi TabLineFill ctermfg=grey ctermbg=white cterm=NONE
"hi TabLineSel ctermfg=black ctermbg=green cterm=NONE
hi TabLineSel ctermfg=green ctermbg=black term=bold
"hi TabLineSel term=bold cterm=bold
"hi TabLineFill term=reverse cterm=reverse 
"hi TabLine term=underline cterm=underline ctermfg=15 ctermbg=242
 
"hi Menu
"hi Scrollbar
"hi Tooltip
 
" cursor / dynamic / other {{{2
hi Cursor ctermfg=black ctermbg=white cterm=NONE
hi CursorIM ctermfg=black ctermbg=white cterm=reverse
hi CursorLine ctermfg=NONE ctermbg=NONE cterm=NONE
hi CursorColumn ctermfg=NONE ctermbg=NONE cterm=NONE
 
hi Visual ctermfg=white ctermbg=lightblue cterm=NONE
hi IncSearch ctermfg=white ctermbg=yellow cterm=NONE
hi Search ctermfg=white ctermbg=darkgreen cterm=NONE
 
" LISTINGS / MESSAGES {{{2
hi ModeMsg ctermfg=yellow ctermbg=NONE cterm=NONE
hi Title ctermfg=red ctermbg=NONE cterm=bold
hi Question ctermfg=green ctermbg=NONE cterm=NONE
hi MoreMsg ctermfg=green ctermbg=NONE cterm=NONE
hi ErrorMsg ctermfg=white ctermbg=red cterm=bold
hi WarningMsg ctermfg=yellow ctermbg=NONE cterm=bold
 
hi Directory term=bold ctermfg=4 "{{{
hi ErrorMsg term=standout ctermfg=15 ctermbg=1  
hi IncSearch term=reverse cterm=reverse 
hi Search term=NONE ctermfg=255 ctermbg=135
hi MoreMsg term=bold ctermfg=2  
hi ModeMsg term=bold cterm=bold 
hi LineNr term=underline ctermfg=244 ctermbg=232  
hi Question term=standout ctermfg=2  
hi StatusLine term=bold,reverse cterm=italic ctermfg=253 ctermbg=238   
hi StatusLineNC term=reverse cterm=reverse ctermfg=246 ctermbg=238  
hi VertSplit term=reverse cterm=reverse ctermfg=238 ctermbg=238  
hi Title term=bold cterm=bold ctermfg=254  
hi Visual term=reverse ctermfg=254 ctermbg=4  
hi VisualNOS term=bold,underline cterm=bold,underline
hi WarningMsg term=standout ctermfg=1 
hi WildMenu term=standout ctermfg=0 ctermbg=11  
hi Folded term=standout cterm=BOLD ctermfg=7 ctermbg=27
hi FoldColumn term=NONE cterm=NONE ctermfg=75 ctermbg=16
hi IncSearch term=bold,underline cterm=bold,underline ctermfg=7 ctermbg=9
hi DiffAdd term=bold ctermbg=12 
hi DiffChange term=bold ctermbg=13 
hi DiffDelete term=bold ctermfg=12 ctermbg=14   
hi DiffText term=reverse cterm=bold ctermbg=9  
hi SpellBad term=reverse ctermbg=9  
hi SpellCap term=reverse ctermbg=12  
hi SpellRare term=reverse ctermbg=13  
hi SpellLocal term=underline ctermbg=14  
hi Pmenu ctermfg=255 ctermbg=238  
hi PmenuSel ctermfg=0 ctermbg=148  
hi PmenuSbar ctermbg=7 
hi PmenuThumb cterm=reverse 
hi TabLine term=underline cterm=underline ctermfg=0 ctermbg=7  
hi TabLineSel term=bold cterm=bold 
hi TabLineFill term=reverse cterm=reverse 
hi CursorLine term=underline cterm=bold ctermbg=234
hi Cursor ctermbg=241 
hi MatchParen term=reverse cterm=bold ctermfg=157 ctermbg=237   
hi Error term=reverse ctermfg=15 ctermbg=9  
 
" :hi TabLineSel|hi TabLineFill|hi TabLine
"hi TabLineSel term=bold cterm=bold 
"hi TabLineFill term=reverse cterm=reverse 
"hi TabLine term=underline cterm=underline ctermfg=15 ctermbg=242 
hi ExtraWhitespace ctermbg=red
hi Comment term=none ctermfg=darkgrey 
hi Constant term=underline ctermfg=Magenta 
hi Special term=bold ctermfg=DarkMagenta 
hi Identifier term=underline cterm=bold ctermfg=Cyan 
hi Statement term=bold ctermfg=Yellow 
hi PreProc term=underline ctermfg=LightBlue 
hi Type term=underline ctermfg=LightGreen 
hi Repeat term=underline ctermfg=White 
hi Operator ctermfg=Red 
hi Ignore ctermfg=black 
hi Error term=reverse ctermbg=Red ctermfg=White 
hi Todo term=standout ctermbg=Yellow ctermfg=Black 
 
" COMMON GROUPS THAT LINK TO DEFAULT HIGHLIGHTING.
 
hi Function ctermfg=85
hi String ctermfg=204
hi Statement term=bold cterm=bold ctermfg=81
hi Function term=bold cterm=bold ctermfg=32
hi Number ctermfg=129
hi Conditional term=bold cterm=bold ctermfg=47
hi Special term=underline ctermfg=191
hi Normal ctermfg=7
hi PreProc ctermfg=141
" Syntax highlighting
hi Comment ctermfg=244
hi Todo ctermfg=245
hi Boolean ctermfg=148
hi String ctermfg=148
hi Identifier ctermfg=148
hi Function ctermfg=124
hi Type ctermfg=103
hi Statement ctermfg=103
hi Keyword ctermfg=81
hi Constant ctermfg=81
hi Number ctermfg=81
hi Special ctermfg=81
hi PreProc ctermfg=230
" Code-specific colors
 
 
" SYNTAX HIGHLIGHTING GROUPS (:HELP GROUP-NAME) {{{2
hi FoldColumn ctermbg=0 ctermfg=2
hi Folded cterm=none ctermfg=2
hi NonText cterm=NONE ctermfg=NONE 
hi StatusLine ctermfg=black ctermbg=White cterm=bold
hi StatusLineNC ctermfg=White ctermbg=green cterm=NONE
hi CursorLine cterm=bold term=bold
 
" FINAL THOUGHTS "{{{2
"syn region myFold start="{" end="}" transparent fold
hi Search term=reverse ctermfg=0 ctermbg=11
hi LineNr term=underline ctermfg=244 ctermbg=232
hi MatchParen ctermfg=15 ctermbg=242
hi String ctermfg=10
hi Constant ctermfg=14
hi Identifier ctermfg=14
hi Operator ctermfg=13
hi NonText cterm=NONE ctermfg=NONE
hi Search cterm=bold ctermbg=99 ctermfg=17

Additional Resources

  1. The perfect .vimrc vim config file

Optimized Vimrc with 256 Colorscheme originally appeared on AskApache.com


Show or Hide WordPress Admin Bar Plugin

$
0
0

AskApache.com

WordPress No Admin BarThe Admin Bar in WordPress is always shown when in the backend administration area no matter what.

You are given the option to show/hide the admin bar when viewing the site, but there is no option to show/hide the admin bar when using the backend... So I created a plugin to provide that option on profile pages.

Why hide the admin bar in backend?
Normally I like the admin-bar and usually have it enabled, but it's nice to be able to switch it on/off from the "Edit Profile" page. The biggest reason for not loading/showing the admin_bar in the backend is SPEED. Here are 2 instances where I hide it-

    · Sites with many authors/admins
    · Moderating Comments on a Mobile Phone

I occasionally enjoy moderating blog comments using my Android mobile phone and a browser like Opera or Dolphin.... hiding the admin_bar improves Load Speed, Page Rendering Speed, and Scroll Speed. Basically everything.

The wp-admin-bar causes additional CSS, JavaScript, and HTML to be added to every page, increasing request size and time of every request! The jQuery used for the admin_bar keeps it floating at the top using javascript, meaning it gets executed on resize/scroll/load - MAJOR PAIN!

Plugin for Hiding/Showing the WP AdminBar

WordPress with Admin Bar





This plugin provides the option of hiding the admin bar when in_admin. It not only hides the admin_bar, it actually prevents the admin_bar class from even loading, at least in WP version 3.4-beta2-20509 thanks to the wp_admin_bar_class filter.

Follow the Installation steps below and/or read on to see how it works.. it's an incredibly simple plugin and easy to extend for other purposes.

Installation Steps

  1. Download the plugin file: askapache-adminbar-prefs.txt
  2. Save to /wp-content/plugins/askapache-adminbar-prefs/askapache-adminbar-prefs.php
  3. Enable/Disable the plugin from the Plugins Page
  4. Show/Hide admin_bar from the 'Edit Profile' Page

Add Checkbox Option to Profile Page

function askapache_adminbar_personal_options( $profileuser )
{
 global $wpdb, $wp_query;
 $show_admin_bar_backend=_get_admin_bar_pref( 'backend', $profileuser->ID );
?>
<tr class="show-admin-bar-backend">
<th scope="row">Toolbar2</th>
<td><fieldset><legend class="screen-reader-text"><span>Toolbar2</span></legend>
<label for="admin_bar_backend">
<input name="admin_bar_backend" type="checkbox" id="admin_bar_backend" value="1"<?php checked( _get_admin_bar_pref( 'backend', $profileuser->ID ) ); ?> />
Show Toolbar when in backend</label><br />
</fieldset>
</td>
</tr><?php
}
add_action( 'personal_options', 'askapache_adminbar_personal_options', 10, 1 );

Save preference when a profile updated

function askapache_adminbar_handle_post($useridtoedit)
{
 global $wpdb, $wp_query, $current_user;
 $show_admin_bar_backend=_get_admin_bar_pref( 'backend', $useridtoedit );
 
 $userID=(int)$useridtoedit;
 if ( !current_user_can('edit_user', $userID) ) wp_die(__('You do not have permission to edit this user.'));
 
 $show_admin_bar_backend=(isset( $_POST['admin_bar_backend'] ) ? 'true' : 'false');
 update_user_option($userID, "show_admin_bar_backend", $show_admin_bar_backend);
}
add_action( 'personal_options_update', 'askapache_adminbar_handle_post', 10, 1);
add_action( 'edit_user_profile_update', 'askapache_adminbar_handle_post', 10, 1);

Remove admin_bar from backend

Now we need to hook into init to either show/hide the admin_bar while in the backend (in_admin()) based on the users preference.

  1. Fetches the users preference for showing the admin_bar in the backend
  2. Removes the wp_admin_bar class from even loading (wp_admin_bar_class filter)
  3. Returns false to the show_admin_bar filter
  4. Overrules the admin-bar css applied to the body
function askapache_adminbar_personal_options_init()
{
 global $wpdb, $wp_query, $current_user;
 $show_admin_bar_backend=_get_admin_bar_pref( 'backend', $current_user->ID );
 if(!$show_admin_bar_backend && is_admin())
 {
  add_filter('wp_admin_bar_class', create_function('', 'return "none".rand(1000,666666);'), 9999999);
  add_filter('show_admin_bar', create_function('', 'return false;'), 999999);
  add_action('admin_head', create_function('', 'echo \'<style type="text/css">body.admin-bar {padding-top:0 !important;}</style>\';'));
 }
}
add_action( 'init', 'askapache_adminbar_personal_options_init',0); 

Add to Core WordPress

I'm sure this will be added to the dev version of WordPress by someone (volunteers?) and eventually integrated into stable. Note this was built and used on WordPress 3.4-beta2-20509.

Show or Hide WordPress Admin Bar Plugin originally appeared on AskApache.com


Mod_Rewrite Variables Cheatsheet

$
0
0

AskApache.com

We've figured out what mod_rewrite variables look like so we can create rewriterules and condition patterns based on the actual value. This cheatsheet is where we'll lay them all out for quick reference. This cheatsheet changed my life, way more than 301 redirect htaccess.

mod_rewrite Variable Value Cheat-Sheet

Jump to: API_VERSION, AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, DOCUMENT_ROOT, GATEWAY_INTERFACE, HTTPS, HTTP_ACCEPT, HTTP_ACCEPT_CHARSET, HTTP_ACCEPT_ENCODING, HTTP_ACCEPT_LANGUAGE, HTTP_CACHE_CONTROL, HTTP_CONNECTION, HTTP_COOKIE, HTTP_FORWARDED, HTTP_HOST, HTTP_KEEP_ALIVE, HTTP_PROXY_CONNECTION, HTTP_REFERER, HTTP_USER_AGENT, IS_SUBREQ, ORIG_PATH_INFO, ORIG_PATH_TRANSLATED, ORIG_SCRIPT_FILENAME, ORIG_SCRIPT_NAME, PATH, PATH_INFO, PHP_SELF, QUERY_STRING, REDIRECT_QUERY_STRING, REDIRECT_REMOTE_USER, REDIRECT_STATUS, REDIRECT_URL, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_PORT, REMOTE_USER, REQUEST_FILENAME, REQUEST_METHOD, REQUEST_TIME, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_GROUP, SCRIPT_NAME, SCRIPT_URI, SCRIPT_URL, SCRIPT_USER, SERVER_ADDR, SERVER_ADMIN, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, SERVER_SIGNATURE, SERVER_SOFTWARE, SSL_CIPHER, SSL_CIPHER_ALGKEYSIZE, SSL_CIPHER_EXPORT, SSL_CIPHER_USEKEYSIZE, SSL_CLIENT_VERIFY, SSL_PROTOCOL, SSL_SERVER_A_KEY, SSL_SERVER_A_SIG, SSL_SERVER_CERT, SSL_SERVER_I_DN, SSL_SERVER_I_DN_C, SSL_SERVER_I_DN_CN, SSL_SERVER_I_DN_L, SSL_SERVER_I_DN_O, SSL_SERVER_I_DN_OU, SSL_SERVER_I_DN_ST, SSL_SERVER_M_SERIAL, SSL_SERVER_M_VERSION, SSL_SERVER_S_DN, SSL_SERVER_S_DN_CN, SSL_SERVER_S_DN_O, SSL_SERVER_S_DN_OU, SSL_SERVER_V_END, SSL_SERVER_V_START, SSL_SESSION_ID, SSL_VERSION_INTERFACE, SSL_VERSION_LIBRARY, THE_REQUEST, TIME, TIME_DAY, TIME_HOUR, TIME_MIN, TIME_MON, TIME_SEC, TIME_WDAY, TIME_YEAR, TZ, UNIQUE_ID

Htaccess Time Cheatsheet

#      300   5 MIN
#      600  10 MIN
#      900  15 MIN
#     1800  30 MIN
#     2700  45 MIN
#     3600   1 HR
#     7200   2 HR
#    10800   3 HR
#    14400   4 HR
#    18000   5 HR
#    36000  10 HR
#    39600  11 HR
#    43200  12 HR
#    46800  13 HR
#    50400  14 HR
#    54000  15 HR
#    86400   1 DAY
#   172800   2 DAY
#   259200   3 DAY
#   345600   4 DAY
#   432000   5 DAY
#   518400   6 DAY
#   604800   1 WEEK
#  1209600   2 WEEK
#  1814400   3 WEEK
#  2419200   1 MONTH
#  4838400   2 MONTH
#  7257600   3 MONTH
#  9676800   4 MONTH
# 12096000   5 MONTH
# 14515200   6 MONTH
# 16934400   7 MONTH
# 19353600   8 MONTH
# 21772800   9 MONTH
# 24192000  10 MONTH
# 26611200  11 MONTH
# 29030400  1 YEAR

API_VERSION: 20020903:12
RewriteCond %{API_VERSION} ^(.*)$
RewriteRule .* http://www.askapache.com?API_VERSION=%1 [R=307,L]

AUTH_TYPE: Digest
RewriteRule .* - [E=IN_AUTH_TYPE:%{AUTH_TYPE}]
RequestHeader set AUTH_TYPE "%{IN_AUTH_TYPE}e"

CACHE_CONTROL: max-age=0
RewriteCond %{ENV:CACHE_CONTROL} no-cache [NC]
RewriteRule . %{REQUEST_URI}?nocache [L]

CONNECTION: keep-alive

CONTENT_LENGTH: (null)
RewriteCond %{REQUEST_METHOD} =POST
RewriteCond %{HTTP:Content-Length}%{CONTENT_LENGTH} ^$
RewriteRule .* - [F,NS,L]

CONTENT_TYPE: (null)

DOCUMENT_ROOT: /home/webroot/askapache.com
RewriteCond %{DOCUMENT_ROOT}/cache%{REQUEST_URI}/index.html -f
RewriteRule . /cache%{REQUEST_URI}/index.html

HOST: www.askapache.com
RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
RewriteRule . http://www.askapache.com%{REQUEST_URI} [R=301,L]

HTTP:
RewriteCond %{HTTP:Accept-Encoding} gzip [NC]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.gz -f
RewriteRule . %{REQUEST_URI}.gz [L]

HTTPS: off
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

HTTP_COOKIE: __qca=1176541205adf28-5553185; ASKAPACHEID=fdadfa4f33e62a878468; __utmc=1df3893
RewriteCond %{HTTP_COOKIE} ^.*autostart=on.*$
RewriteRule ^(.*)\.swf$ /$1\?autostart=true [NE,L]

HTTP_HOST: www.askapache.com

HTTP_REFERER: http://www.askapache.com/pro/mod_rewrite/catch.php?k=i
RewriteCond %{HTTP_REFERER} badhost [NC]
RewriteRule . - [F]

HTTP_USER_AGENT: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Firefox/3.0.1
RewriteCond %{HTTP_USER_AGENT} ^.*(Android|2.0\ MMP|240x320|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|hiptop|IEMobile|iPhone).*$ [NC]
RewriteRule ^(.+)$ /mobile/$1 [L]

IS_SUBREQ: false

KEEP_ALIVE: 300

PATH: /bin:/usr/bin:/sbin:/usr/sbin

QUERY_STRING: k=i
RewriteCond %{QUERY_STRING} showtime [NC]
RewriteCond T:%{TIME}_TY:%{TIME_YEAR}_TMO:%{TIME_MON}_TWD:%{TIME_WDAY}_TD:%{TIME_DAY}_TH:%{TIME_HOUR}_TMI:%{TIME_MIN}_TS:%{TIME_SEC} ^(.*)$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}?time=%1 [R,L]

REMOTE_ADDR: 22.162.134.211
RewriteCond %{REMOTE_ADDR} !^22\.162\.134\.211$
RewriteRule . http://www.askapache.com/maintenance-in-progress.html [R=307,L]

REMOTE_HOST: 22.162.134.211

REMOTE_PORT: 4220

REMOTE_USER: askapache
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

REQUEST_FILENAME: /home/webroot/askapache.com/pro/mod_rewrite/index.php

REQUEST_METHOD: GET
RewriteCond %{REQUEST_METHOD} !^(POST|GET|HEAD|PROPFIND|OPTIONS)$
RewriteRule .* - [F,L]

REQUEST_PROTOCOL: HTTP/1.1
RewriteCond %{REQUEST_PROTOCOL} !^HTTP/(0\.9|1\.[01])$
RewriteRule . [F,L]

REQUEST_URI: /pro/mod_rewrite/index.php
RewriteCond %{REQUEST_URI} ^(robots\.txt|favicon\|ico)$ [NC]
RewriteRule . - [S=1]
RewriteCond %{HTTP_HOST} ^www
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

SCRIPT_FILENAME: /home/webroot/askapache.com/pro/mod_rewrite/index.php

SCRIPT_GROUP: daemong

SCRIPT_URI: http://www.askapache.com/pro/mod_rewrite/index.php

SCRIPT_URL: /pro/mod_rewrite/index.php

SCRIPT_USER: askapache

SERVER_ADDR: 208.113.134.190

SERVER_ADMIN: webmaster@askapache.com

SERVER_NAME: www.askapache.com

SERVER_PORT: 80

SERVER_PROTOCOL: HTTP/1.1

SERVER_SOFTWARE: Apache/2.0.61 (Unix) PHP/5.5 OpenSSL/0.9.7e

SSL_CIPHER: DHE-RSA-AES256-SHA

SSL_CIPHER_ALGKEYSIZE: 256

SSL_CIPHER_EXPORT: false

SSL_CIPHER_USEKEYSIZE: 256

SSL_CLIENT_VERIFY: NONE

SSL_PROTOCOL: TLSv1

SSL_SERVER_A_KEY: rsaEncryption

SSL_SERVER_A_SIG: sha1WithRSAEncryption

SSL_SERVER_CERT: -----BEGIN CERTIFICATE----- ... MIIFkTC ... -----END CERTIFICATE-----

SSL_SERVER_I_DN: /C=US/ST=Arizona/L=Scottsdale/O=Starfield Technologies, Inc./OU=http://certificates.starfieldtech.com/repository/CN=Starfield Secure Certification Authority/serialNumber=10688435

SSL_SERVER_I_DN_C: US

SSL_SERVER_I_DN_CN: Starfield Secure Certification Authority

SSL_SERVER_I_DN_L: Scottsdale

SSL_SERVER_I_DN_O: Starfield Technologies, Inc.

SSL_SERVER_I_DN_OU: http://certificates.starfieldtech.com/repository

SSL_SERVER_I_DN_ST: Arizona

SSL_SERVER_M_SERIAL: 042840B88A2352

SSL_SERVER_M_VERSION: 3

SSL_SERVER_S_DN: /O=www.askapache.com/OU=Domain Control Validated/CN=www.askapache.com

SSL_SERVER_S_DN_CN: www.askapache.com

SSL_SERVER_S_DN_O: www.askapache.com

SSL_SERVER_S_DN_OU: Domain Control Validated

SSL_SERVER_V_END: Jul 14 16:53:43 2012 GMT

SSL_SERVER_V_START: Jul 14 20:25:17 2010 GMT

SSL_SESSION_ID: 4184083DD1C74547553018174950D88987BD7ED03CE54EBB6638539C34814376

SSL_VERSION_INTERFACE: mod_ssl/2.2.16

SSL_VERSION_LIBRARY: OpenSSL/0.9.8e-fips-rhel5

THE_REQUEST: GET /pro/mod_rewrite/index.php?k=i HTTP/1.1
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /.*\?(s|search)=(.+)\ HTTP/ [NC]
RewriteRule .* http://www.askapache.com/search/%3/? [R=302,L,NE]

TIME: 20080915152142
RewriteCond %{QUERY_STRING} showtime [NC]
RewriteCond T:%{TIME}_TY:%{TIME_YEAR}_TMO:%{TIME_MON}_TWD:%{TIME_WDAY}_TD:%{TIME_DAY}_TH:%{TIME_HOUR}_TMI:%{TIME_MIN}_TS:%{TIME_SEC} ^(.*)$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}?time=%1 [R,L]

TIME_DAY: 15

TIME_HOUR: 15

TIME_MIN: 21

TIME_MON: 09

TIME_SEC: 42

TIME_WDAY: 1

TIME_YEAR: 2008

UNIQUE_ID: qOr5tEBvcm8AAE-VoiUAAAAQ

This article is meant to prepare us for the advanced mod_rewrite examples that are soon to be published. The upcoming article is going to be examples using mod_rewrite to achieve some crazy stuff... Here the focus is on identifying mod_rewrite variables and defining the limits of the module by checking the mod_rewrite source code.

For a broader mod_rewrite cheat sheet, check this printable cheat sheet.

Directives in Mod_Rewrite

RewriteEngine
RewriteEngine on|off
On or Off to enable or disable (default) the whole rewriting engine
RewriteOptions
RewriteOptions Options
List of option strings to set
RewriteBase
RewriteBase URL-path
the base URL of the per-directory context
RewriteCond
RewriteCond TestString CondPattern
an input string and a to be applied regexp-pattern
RewriteRule
RewriteRule Pattern Substitution [flags]
an URL-applied regexp-pattern and a substitution URL
RewriteMap
RewriteMap MapName MapType:MapSource
a mapname and a filename
RewriteLock
RewriteLock file-path
the filename of a lockfile used for inter-process synchronization
RewriteLog
RewriteLog file-path
the filename of the rewriting logfile
RewriteLogLevel
RewriteLogLevel Level
the level of the rewriting logfile verbosity (0=none, 1=std, .., 9=max)

RewriteRule Flags

C
Using the [Chain], or [C] flag, allows you to indicate that several rules should be chained together as a single logical transation. This is usually used when a transformation is sufficiently complicated to warrant breaking into several smaller steps.
CO
cookie|CO=Name:Value:Domain[:Lifetime[:Path]]

This sets a cookie on the client's browser. The cookie's name is specified by NAME and the value is VAL. The domain field is the domain of the cookie, such as '.apache.org',the optional lifetime is the lifetime of the cookie in minutes, and the optional path is the path of the cookie.
E
'env|E=VAR:VAL' (set environment variable)

RewriteRule (root|cmd)\.exe - [E=worm:nimda]
F
'forbidden|F' (force URL to be forbidden)

G
'gone|G' (force URL to be gone)

H
'handler|H=Content-handler' (force Content handler)

L
'last|L' (last rule)

N
'next|N' (next round)

NC
'nocase|NC' (no case)

NE
'noescape|NE' (no URI escaping of output)

NS
'nosubreq|NS' (not for internal sub-requests)

P
'proxy|P' (force proxy)

PT
'passthrough|PT' (pass through to next handler)

QSA
'qsappend|QSA' (query string append)

R
'redirect|R  [=code]' (force redirect)

S
'skip|S=num' (skip next rule(s))

This flag forces the rewriting engine to skip the next num rules in sequence, if the current rule matches. Use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes skip=N, where N is the number of rules in the else-clause. (This is not the same as the 'chain|C' flag!)
T
'type|T=MIME-type' (force MIME type)

Force the MIME-type of the target file to be MIME-type. This can be used to set up the content-type based on some conditions. For example, the following snippet allows .php files to be displayed by mod_php if they are called with the .phps extension:

Rules and Conditions Processing Order

  1. The Pattern of the RewriteRule (^/.*$) is checked first.
  2. If the pattern matches, then the RewriteCond's are checked.
  3. If the RewriteConditions also match, the RewriteRule is applied.

RewriteRule Special Variables

  1. ENV_
  2. SSL_
  3. HTTP_
  4. LA-U_
  5. LA-F_

RewriteCond Tests

  • f - FILE_EXISTS
  • s - FILE_SIZE
  • l - FILE_LINK
  • d - FILE_DIR
  • x - FILE_XBIT
  • U - LU_URL
  • F - LU_FILE
  • > - STR_GT
  • < - STR_LT
  • = - STR_EQ

Special Rewrite Redirects

  1. "permanent" - HTTP_MOVED_PERMANENTLY
  2. "temp" - HTTP_MOVED_TEMPORARILY
  3. "seeother" - HTTP_SEE_OTHER
  4. digit

Recognized by Mod_Rewrite

  1. ajp://
  2. balancer://
  3. ftp://
  4. gopher://
  5. http://
  6. https://
  7. ldap://
  8. mailto:
  9. news:
  10. nntp://

Mod_Rewrite Variables, from Source

  • TIME - %04d%02d%02d%02d%02d%02d
  • HTTPS - flag ? "on" : "off"
  • TIME_DAY
  • TIME_SEC
  • TIME_MIN
  • TIME_HOUR
  • TIME_MON
  • TIME_WDAY
  • TIME_YEAR
  • IS_SUBREQ - (main ? "true" : "false");
  • PATH_INFO - path_info;
  • AUTH_TYPE - ap_auth_type;
  • HTTP_HOST - lookup_header("Host", ctx);
  • SERVER_NAME - ap_get_server_name(r);
  • REMOTE_ADDR - connection->remote_ip;
  • SERVER_ADDR - connection->local_ip;
  • HTTP_ACCEPT - lookup_header("Accept", ctx);
  • THE_REQUEST - the_request;
  • API_VERSION - "%d:%d",MODULE_MAGIC_NUMBER_MAJOR,MODULE_MAGIC_NUMBER_MINOR);
  • HTTP_COOKIE - lookup_header("Cookie", ctx);
  • SERVER_PORT - ap_get_server_port(r);
  • REMOTE_HOST
  • REMOTE_NAME, NULL);
  • REMOTE_PORT - r->connection->remote_addr->port
  • REMOTE_USER - user;
  • SCRIPT_USER - "<unknown>";
  • APR_FINFO_USER
  • REQUEST_URI - uri;
  • SCRIPT_GROUP - "<unknown>";
  • REMOTE_IDENT - ap_get_remote_logname(r);
  • HTTP_REFERER - lookup_header("Referer", ctx);
  • QUERY_STRING - args;
  • SERVER_ADMIN - server->server_admin;
  • DOCUMENT_ROOT - ap_document_root(r);
  • HTTP_FORWARDED - lookup_header("Forwarded", ctx);
  • REQUEST_METHOD - method;
  • HTTP_USER_AGENT - lookup_header("User-Agent", ctx);
  • SCRIPT_FILENAME - same as request_filename
  • REQUEST_FILENAME - same as script_filename
  • SERVER_PROTOCOL - protocol
  • SERVER_SOFTWARE - ap_get_server_banner();
  • HTTP_PROXY_CONNECTION - lookup_header("Proxy-Connection", ctx);

REGEX Rewrite Guides

Mod_Rewrite Terms and Definitions

pattern
the RegExp pattern string
regexp
the RegExp pattern compilation
flags
Flags which control the substitution
forced_mimetype
forced MIME type of substitution
forced_handler
forced content handler of subst.
forced_responsecode
forced HTTP response status
env
added environment variables
cookie
added cookies
skip
number of next rules to skip
state
the RewriteEngine state
options
the RewriteOption state
rewritelogfile
the RewriteLog filename
rewritelogfp
the RewriteLog open filepointer
rewritelog: level
the RewriteLog level of verbosity
rewritemaps
the RewriteMap entries
rewriteconds
the RewriteCond entries (temp.)
rewriterules
the RewriteRule entries
directory
the directory where it applies
baseurl
the base-URL where it applies

Mod_Rewrite Errors

  • Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden: %s
  • RewriteCond: bad argument line
  • RewriteCond: NoCase option for non-regex pattern %s is not supported and will be ignored.
  • RewriteCond: cannot compile regular expression
  • RewriteRule: invalid HTTP response code %s for flag R
  • RewriteRule: unknown flag
  • RewriteRule: cannot compile regular expression
  • RewriteOptions: MaxRedirects option has been removed in favor of the global LimitInternalRecursion directive and will be ignored.
  • RewriteOptions: unknown option
  • RewriteMap: bad path to txt map:
  • RewriteMap: bad path to rnd map:
  • RewriteMap: bad map:
  • RewriteMap: bad path to dbm map:
  • RewriteMap: dbm type
  • RewriteMap: bad path to prg map:
  • RewriteMap: internal map not found:
  • RewriteMap: bad path to txt map:
  • RewriteMap: file for map not found:
  • Invalid RewriteLock path
  • RewriteBase: only valid in per-directory config files
  • RewriteBase: empty URL not allowed
  • RewriteBase: argument is not a valid URL
  • RewriteCond: bad flag delimiters
  • RewriteCond: unknown flag
  • RewriteLog and RewriteLogLevel are not supported by this build of mod_rewrite because it was compiled using the -DREWRITELOG_DISABLED compiler option. You have to recompile mod_rewrite WITHOUT this option in order to use the rewrite log.
  • mod_rewrite: Invalid RewriteLog path %s
  • mod_rewrite: could not open reliable pipe to RewriteLog filter %s
  • mod_rewrite: Invalid RewriteLog path %s
  • mod_rewrite: could not open RewriteLog file %s
  • mod_rewrite: Running external rewrite maps without defining a RewriteLock is DANGEROUS!
  • mod_rewrite: could not start RewriteMap program %s
  • mod_rewrite: cant access text RewriteMap file %s
  • mod_rewrite: cant access DBM RewriteMap file %s
  • mod_rewrite: Parent could not create RewriteLock file %s
  • mod_rewrite: Parent could not set permissions on RewriteLock check User and Group directives
  • mod_rewrite: could not create rewrite_log_lock
  • mod_rewrite: Could not set permissions on rewrite_log_lock check User and Group directives
  • mod_rewrite: could not init rewrite_mapr_lock_acquire in child
  • mod_rewrite: could not init rewrite log lock in child
  • mod_rewrite: could not init map cache in child
  • split uri=%s -> uri=%s, args=%s
  • reduce %s -> %s
  • strip matching prefix: %s -> %s
  • add subst prefix: %s -> %s
  • cant open RewriteMap file, see error log
  • cache lookup FAILED, forcing new map lookup
  • map lookup FAILED: map=%s[txt] key=%s
  • map lookup OK: map=%s[txt] key=%s -> val=%s
  • cache lookup OK: map=%s[txt] key=%s -> val=%s
  • randomly chosen the subvalue `%s
  • cant open DBM RewriteMap file, see error log
  • cache lookup FAILED, forcing new map lookup
  • map lookup FAILED: map=%s[dbm] key=%s
  • map lookup OK: map=%s[dbm] key=%s -> val=%s
  • cache lookup OK: map=%s[dbm] key=%s -> val=%s
  • map lookup FAILED: map=%s key=%s
  • map lookup OK: map=%s key=%s -> val=%s
  • map lookup FAILED: map=%s key=%s
  • map lookup OK: map=%s key=%s -> val=%s
  • lookahead: path=%s var=%s -> val=%s
  • lookahead: path=%s var=%s -> val=%s
  • RESULT=%s
  • escaping backreference %s to %s
  • setting env variable %s to %s
  • setting cookie %s, cookie
  • skipping already set cookie %s
  • RewriteCond URI (-U) check: path=%s -> status=%d
  • RewriteCond file (-F) check: path=%s -> file=%s status=%d
  • RewriteCond: input=%s pattern=%s%s%s%s => %s
  • remember %s to have MIME-type %s
  • remember %s to have Content-handler %s
  • add path info postfix: %s -> %s%s
  • strip per-dir prefix: %s -> %s
  • applying pattern %s to uri %s
  • rewrite %s -> %s, ctx->uri
  • forcing responsecode %d for %s
  • add per-dir prefix: %s -> %s%s
  • forcing proxy-throughput with %s
  • explicitly forcing redirect with %s
  • implicitly forcing redirect (rc=%d) with %s
  • forcing %s to get passed through to next API URI-to-filename handler
  • init rewrite engine with requested uri %s
  • go-ahead with proxy request %s [OK]
  • dconf->directory,trying to replace prefix %s with %s
  • escaping %s for redirect
  • redirect to %s [REDIRECT/%d]
  • initial URL equal rewritten URL: %s [IGNORING REWRITE]
  • dconf->directory, trying to replace prefix %s with %s
  • strip document_root prefix: %s -> %s
  • internal redirect with %s [INTERNAL REDIRECT]
  • pass through %s
  • force filename %s to have MIME-type %s
  • force filename %s to have the Content-handler %s,
  • init rewrite engine with requested uri %s
  • init rewrite engine with passed filename %s. Original uri = %s
  • uri already rewritten. Status %s, Uri %s, %s
  • attempt to make remote request from mod_rewrite without proxy enabled: %s
  • go-ahead with proxy request %s [OK]
  • escaping %s for redirect
  • redirect to %s [REDIRECT/%d]
  • local path result: %s
  • prefixing with document_root of %s FAILED
  • prefixed with document_root to %s
  • go-ahead with %s [OK]
  • pass through %s

URL Rewriting Module

This module uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly.

It supports an unlimited number of additional rule conditions (which can operate on a lot of variables, even on HTTP headers) for granular matching and even external database lookups (either via plain text tables, DBM hash files or even external processes) for advanced URL substitution.

It operates on the full URLs (including the PATH_INFO part) both in per-server context (httpd.conf) and per-dir context (.htaccess) and even can generate QUERY_STRING parts on result. The rewriting result finally can lead to internal subprocessing, external request redirection or even to internal proxy throughput.

This module was originally written in April 1996 and gifted exclusively to the The Apache Software Foundation in July 1997 by

Ralf S. Engelschall

Htaccess Time Cheatsheet

#      300   5 MIN
#      600  10 MIN
#      900  15 MIN
#     1800  30 MIN
#     2700  45 MIN
#     3600   1 HR
#     7200   2 HR
#    10800   3 HR
#    14400   4 HR
#    18000   5 HR
#    36000  10 HR
#    39600  11 HR
#    43200  12 HR
#    46800  13 HR
#    50400  14 HR
#    54000  15 HR
#    86400   1 DAY
#   172800   2 DAY
#   259200   3 DAY
#   345600   4 DAY
#   432000   5 DAY
#   518400   6 DAY
#   604800   1 WEEK
#  1209600   2 WEEK
#  1814400   3 WEEK
#  2419200   4 WEEK
#  4838400   2 MONTH
#  7257600   3 MONTH
#  9676800   4 MONTH
# 12096000   5 MONTH
# 14515200   6 MONTH
# 16934400   7 MONTH
# 19353600   8 MONTH
# 21772800   9 MONTH
# 24192000  10 MONTH
# 26611200  11 MONTH
# 29030400  12 MONTH

Mod_Rewrite Variables Cheatsheet originally appeared on AskApache.com


DNS Round Robin Configuration using Rsync over SSH

$
0
0

AskApache.com

Round Robin DNS

My traffic is growing, alot, and I need to plan how I'm going to maintain scalability, high availability, and redundancy. Scalability is an application's ability to support a growing number of users. High availability can be defined as redundancy or speed. I decided to setup Round Robin DNS for static.askapache.com, which is the "static" subdomain of AskApache that serves all the static assets like images, javascript, css, etc.. (BTW, the z stands for ZAP).. All I needed to attempt setting this up was another hosting account on a separate server. I have hosting accounts with around 10 different companies from working with various clients over the years, like Powweb and I don't use them because they suck in terms of the unix environment. Many of these web hosts are actually very fast bandwidth-wise..

Round Robin Concept

A few months ago I was given a free hosting account on HostGator to evaluate and tempt me away from DreamHost to become a Gator. I get a lot of these types of offers from time to time from the smaller Web companies who read AskApache.. but when I noticed the SSH access was jailed and saw how restrictive the shell was I felt like I was on a windows box.. I want a shell, cpanel sucks. I compile and run everything from the shell so thats was a deal-breaker and I sorta forgot all about it.

The goal is to add the HostGator server to be an exact mirror of the static.askapache.com domain, then to add that server as a 2nd A record to my DNS zone. That way half the visitors to the size will be taking up resources and bandwidth on the HostGator server instead of mine.

Round Robin A records in DNS are intended to evenly distribute queries between each host of the same name. Using some tricks straight out of a hackers toolbox we can verify if the distribution is taking place. (It is.)

DNS - Domain Name System

The Domain Name System is often analogized as a "phone book" for the Internet because it translates human-friendly computer hostnames into IP addresses. For example, www.askapache.com translates to 208.113.134.190. Every request for a human-friendly hostname first needs to be translated to the IP before the server can be queried. Normally each hostname corresponds to exactly 1 IP address. But in a Round Robin setup, the idea is to have the hostname correspond to multiple IP addresses, which are different servers that house the exact same content, resulting in some hosts requesting files from one server, and another host requesting files from the other server, resulting in less CPU resources and bandwidth.

Here is an the zone for static.askapache.com Round Robin records:

QUERYTTLCLASSTYPEANSWER
static.askapache.com13084INA64.111.114.111
static.askapache.com13084INA69.56.174.114

Round Robin DNS

Round robin DNS is a technique of load distribution, load balancing, or fault-tolerance provisioning multiple, redundant Internet Protocol service hosts, e.g., Web servers, FTP servers, by managing the Domain Name System's (DNS) responses to address requests from client computers according to an appropriate statistical model.

In its simplest implementation Round-robin DNS works by responding to DNS requests not only with a single IP address, but a list of IP addresses of several servers that host identical services. The order in which IP addresses from the list are returned is the basis for the term round robin. With each DNS response, the IP address sequence in the list is permuted. Usually, basic IP clients attempt connections with the first address returned from a DNS query so that on different connection attempts clients would receive service from different providers, thus distributing the overall load among servers.

Round robin DNS is often used for balancing the load of geographically-distributed Web servers. For example, a company has one domain name and three identical web sites residing on three servers with three different IP addresses. When one user accesses the home page it will be sent to the first IP address. The second user who accesses the home page will be sent to the next IP address, and the third user will be sent to the third IP address. In each case, once the IP address is given out, it goes to the end of the list. The fourth user, therefore, will be sent to the first IP address, and so forth.

Although easy to implement, round robin DNS has problematic drawbacks, such as those arising from record caching in the DNS hierarchy itself, as well as client-side address caching and reuse, the combination of which can be difficult to manage. Round robin DNS should not solely be relied upon for service availability. If a service at one of the addresses in the list fails, the DNS will continue to hand out that address and clients will still attempt to reach the inoperable service.

Does Round Robin Work

Definately. I can look at the access logs for both servers and see that they are splitting the requests nicely. It is definately not an exact split however, look at these statistics and you'll see what I mean.

$ dig @ns1.dreamhost.com +authority +all static.askapache.com
 
;; ANSWER SECTION:
static.askapache.com.        14400   IN      A       69.56.174.114
static.askapache.com.        14400   IN      A       64.111.114.111
 
$ dig @ns1.dreamhost.com +authority +all static.askapache.com
 
;; ANSWER SECTION:
static.askapache.com.        14400   IN      A       64.111.114.111
static.askapache.com.        14400   IN      A       69.56.174.114

The effects of caching will distort the effectiveness of any IP address allocation algorithm unless a 0 TTL is used which has the effect of significantly increasing the load on the DNS (and is not always implemented consistently). In this case the cure may be worse than the disease Good news we have good load balancing on our web servers. Bad news we need 17 more DNS servers!. Intuitively, and without running any experiments to verify, we would suggest that given a normal TTL (12 hours or more) and ANY IP allocation algorithm other than a single static list, loads should be reasonably balanced .


Full root server query

Tracing to static.askapache.com[a] via A.ROOT-SERVERS.NET, maximum of 3 retries
A.ROOT-SERVERS.NET [.] (198.41.0.4)
 |\___ L.GTLD-SERVERS.NET [com] (192.41.162.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ D.GTLD-SERVERS.NET [com] (192.31.80.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ J.GTLD-SERVERS.NET [com] (192.48.79.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ H.GTLD-SERVERS.NET [com] (192.54.112.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ E.GTLD-SERVERS.NET [com] (192.12.94.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ F.GTLD-SERVERS.NET [com] (192.35.51.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ I.GTLD-SERVERS.NET [com] (192.43.172.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ G.GTLD-SERVERS.NET [com] (192.42.93.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ B.GTLD-SERVERS.NET [com] (2001:0503:231d:0000:0000:0000:0002:0030) Not queried
 |\___ B.GTLD-SERVERS.NET [com] (192.33.14.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ A.GTLD-SERVERS.NET [com] (2001:0503:a83e:0000:0000:0000:0002:0030) Not queried
 |\___ A.GTLD-SERVERS.NET [com] (192.5.6.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ C.GTLD-SERVERS.NET [com] (192.26.92.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 |\___ M.GTLD-SERVERS.NET [com] (192.55.83.30)
 |     |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
 |     |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
 |      \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
  \___ K.GTLD-SERVERS.NET [com] (192.52.178.30)
       |\___ ns3.dreamhost.com [askapache.com] (66.33.216.216) Got authoritative answer
       |\___ ns2.dreamhost.com [askapache.com] (208.96.10.221)
        \___ ns1.dreamhost.com [askapache.com] (66.33.206.206) Got authoritative answer
 
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 64.111.114.111
  ns1.dreamhost.com (66.33.206.206)       static.askapache.com -> 69.56.174.114
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 64.111.114.111
  ns3.dreamhost.com (66.33.216.216)       static.askapache.com -> 69.56.174.114

Live Online DNS Tools

More Reading

RFC's related to DNS

  • RFC 920: Specified original TLDs: .arpa, .com, .edu, .org, .gov, .mil and two-character country codes
  • RFC 1032: Domain administrators guide
  • RFC 1033: Domain administrators operations guide
  • RFC 1034: Domain Names - Concepts and Facilities.
  • RFC 1035: Domain Names - Implementation and Specification
  • RFC 1101: DNS Encodings of Network Names and Other Types
  • RFC 1123: Requirements for Internet Hosts -- Application and Support
  • RFC 1912: Common DNS Operational and Configuration Errors
  • RFC 1995: Incremental Zone Transfer in DNS
  • RFC 1996: A Mechanism for Prompt Notification of Zone Changes (DNS NOTIFY)
  • RFC 2136: Dynamic Updates in the domain name system (DNS UPDATE)
  • RFC 2181: Clarifications to the DNS Specification
  • RFC 2182: Selection and Operation of Secondary DNS Servers
  • RFC 2308: Negative Caching of DNS Queries (DNS NCACHE)
  • RFC 2317: Classless IN-ADDR.ARPA delegation
  • RFC 2671: Extension Mechanisms for DNS (EDNS0)
  • RFC 3597: Handling of Unknown DNS Resource Record (RR) Types
  • RFC 3696: Application Techniques for Checking and Transformation of Names
  • RFC 4343: Domain Name System (DNS) Case Insensitivity Clarification
  • RFC 4592: The Role of Wildcards in the Domain Name System
  • RFC 4892: Requirements for a Mechanism Identifying a Name Server Instance
  • RFC 5001: DNS Name Server Identifier Option (NSID)
  • RFC 5395: Domain Name System (DNS) IANA Considerations

This page contains content by Author of Article from Wikipedia and is licensed under the GNU FDL.

DNS Round Robin Configuration using Rsync over SSH originally appeared on AskApache.com



Using PHP shorthand and short_open_tag

$
0
0

AskApache.com

Using PHP shorthand and short open tag

I hope this will pursuade you to stop using short_open_tag syntax.

<?= or <?

Reasons to NOT use PHP Shorthand syntax

  1. WordPress Coding Standards - Using php style short open tag syntax is EXPRESSLY forbidden in the WordPress Codex
    No Shorthand PHP tags Important: Never use shorthand PHP start tags. Always use full PHP tags.
  2. WordPress VIP Coding Standards - They enforce the WordPress Coding Standards but much more strictly, claiming to go line by line in any plugin or theme to make sure.
  3. PEAR Coding Standards: http://pear.php.net/manual/en/standards.tags.php
    Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups.
  4. There is talk that short_open_tag and asp style tags will be DISABLED in php 6.
    They are already working to decouple <?= from short_open_tag for php 6
  5. PHP Best Practices and Recommendations (taken right from recommended php.ini comments).
    • php < 5.2
      Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.
    • php > 5.3
      It's been recommended for several years that you not use the short tag "short cut" and instead to use the full <?php and ?> tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them.
  6. Ever since php 5.1 was released, both the recommended and production sample php.ini files that come with the php release by default have short_open_tag set to OFF
    php.ini values : short_open_tag PHP 4, 5_0 * Default behaviour : on * php.ini-dist : on * php.ini-recommended : on PHP 5_1, 5_2: * Default behaviour : on * php.ini-dist : on * php.ini-recommended : off PHP 5_3: * Default behaviour : on * php.ini-development : off * php.ini-production : off
  7. Parser Speed - As far as parser speed is concerned, as long as short_open_tag is set to on in the php.ini and not set using a runtime config like ini_set the actual parsing speed won't be slower. What is slower is the actual parsing of the document with short_open_tag turned on because the parser reads anything starting with <? instead of just <?php.
  8. Security, on all the sites and servers I administer, short_open_tag is ALWAYS disabled in the php.ini file by me. This prevents additional checking from having to take place for cleaning user-input, makes evalling code easier and safer (1 less thing to worry about), and keeps the parser from having a more wild acceptance of code it accepts.
  9. XML Errors, XSLT Translations, Validation, PHP Editors, color syntax highlighting Lets say in php you want to output an xml document (or parse .html files as php). Well if short_open_tag is turned on what happens to this code?
<?php // output xml header ?>
<?xml version="1.0" encoding="utf-8"?>

Well that results in a PHP error: Parse error: syntax error, unexpected T_STRING in ... on line ... The workaround is pretty simple, just do:

<?php // output xml header
echo '<?xml version="1.0" encoding="utf-8"?>';

More Info from PHP RFC

Also read: https://wiki.php.net/rfc/shortags.

Other Reasons not to use PHP ShortHand

not making use of short tags, means your source code will also be a valid XML document, which allows you to do many things with it such as validation, XSLT translations, etc, as well as allowing your text editor to parse your code for syntax colouring. Every PHP tag will simply be interpreted as an XML processing instruction (commonly referred to as PI). The reason why all the other suggested methods are not advisable is because they contain the characters ?> inside the PHP tag, which the XML parser will interpret as the end of the processing instruction. A processing instruction is defined in XML as: PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' In other words, it explicitly forbids the characters ?> to occur together within a processing instruction, unless they are delimiting the end of the tag. It also requires a PITarget (an identifier starting with a letter) immediately after the initial start delimiter, which means that all short tag formats are also invalid XML. Following these guidelines will result in code that is portable to servers with any configuration and allow you perform many useful tasks on your XML or XHTML source documents. Even if you do not intend to validate or translate your source documents, and you can ignore some incorrect syntax colouring in your text editor, it is still best to get into good habits early.

Recommendation: Do not use PHP shorthand

So I recommend from now on use the full <?php ?> style. Here's one of my old bad coding habits, using a loop with processing in it instead of out of it:

<?php
$array=array();
while (sizeof($array)>10) { }

instead of

<?php
$array=array();
$count=sizeof($array);
while ($count > 10) {}

Break The Habit

What I do to break the bad habit is I slap myself on both sides of my face when I notice I did it and immediately correct it after the slap. You may have a different bad-habit fixer, but feel free to use mine, it works really well for me :)

Using PHP shorthand and short_open_tag originally appeared on AskApache.com


SUDO – sudoers Config File

$
0
0

AskApache.com

Options Guide for SUDO

always_set_home
If set, sudo will set the HOME environment variable to the home directory of the target user (which is root unless the -u option is used). This effectively means that the -H option is always implied. [D: OFF]
askpass
The askpass option specifies the fully qualified path to a helper program used to read the user's password when no terminal is available. This may be the case when sudo is executed from a graphical (as opposed to text-based) application. The program specified by askpass should display the argument passed to it as the prompt and write the user's password to the standard output. The value of askpass may be overridden by the SUDO_ASKPASS environment variable.
authenticate
If set, users must authenticate themselves via a password (or other means of authentication) before they may run commands. This default may be overridden via the PASSWD and NOPASSWD tags. This flag is on by default .closefrom_override If set, the user may use sudo's -C option which overrides the default starting point at which sudo begins closing open file descriptors. [D: OFF]
closefrom
Before it executes a command, sudo will close all open file descriptors other than standard input, standard output and standard error (ie: file descriptors 0-2). The closefrom option can be used to specify a different file descriptor at which to start closing. The default is 3.
editor
A colon (':') separated list of editors allowed to be used with visudo. visudo will choose the editor that matches the user's EDITOR environment variable if possible, or the first editor in the list that exists and is executable. The default is the path to vi on your system.
env_check
Environment variables to be removed from the user's environment if the variable's value contains % or / characters. This can be used to guard against printf- style format vulnerabilities in poorly-written programs. The argument may be a double-quoted, space- separated list or a single value without double-quotes. The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators respectively. Regardless of whether the env_reset option is enabled or disabled, variables specified by env_check will be preserved in the environment if they pass the aforementioned check. The default list of environment variables to check is displayed when sudo is run by root with the -V option.
env_delete
Environment variables to be removed from the user's environment when the env_reset option is not in effect. The argument may be a double-quoted, space-separated list or a single value without double-quotes. The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators respectively. The default list of environment variables to remove is displayed when sudo is run by root with the -V option .Note that many operating systems will remove potentially dangerous variables from the environment of any setuid process (such as sudo).
env_editor
If set, visudo will use the value of the EDITOR or VISUAL environment variables before falling back on the default editor list. Note that this may create a security hole as it allows the user to run any arbitrary command as root without logging. A safer alternative is to place a colon-separated list of editors in the editor variable. visudo will then only use the EDITOR or VISUAL if they match a value specified in editor. This flag is on by default.
env_file
The env_file options specifies the fully qualified path to a file containing variables to be set in the environment of the program being run. Entries in this file should either be of the form VARIABLE=value or export VARIABLE=value. The value may optionally be surrounded by single or double quotes. Variables in this file are subject to other sudo environment settings such as env_keep and env_check .exempt_group Users in this group are exempt from password and PATH requirements. This is not set by default.
env_keep
Environment variables to be preserved in the user's environment when the env_reset option is in effect. This allows fine-grained control over the environment sudo-spawned processes will receive. The argument may be a double-quoted, space-separated list or a single value without double-quotes. The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators respectively. The default list of variables to keep is displayed when sudo is run by root with the -V option .When logging via syslog(3), sudo accepts the following values for the syslog facility (the value of the syslog Parameter): authpriv (if your OS supports it), auth, daemon, user, local0, local1, local2, local3, local4, local5, local6, and local7. The following syslog priorities are supported: alert, crit, debug, emerg, err, info, notice, and warning.
env_reset
If set, sudo will reset the environment to only contain the LOGNAME, SHELL, USER, USERNAME and the SUDO_* variables. Any variables in the caller's environment that match the env_keep and env_check lists are then added. The default contents of the env_keep and env_check lists are displayed when sudo is run by root with the -V option. If the secure_path option is set, its value will be used for the PATH environment variable. This flag is on by default.
fast_glob
Normally, sudo uses the glob(3) function to do shell- style globbing when matching pathnames. However, since it accesses the file system, glob(3) can take a long time to complete for some patterns, especially when the pattern references a network file system that is mounted on demand (automounted). The fast_glob option causes sudo to use the fnmatch(3) function, which does not access the file system to do its matching .The disadvantage of fast_glob is that it is unable to match relative pathnames such as ./ls or ../bin/ls. [D: OFF]
fqdn
Set this flag if you want to put fully qualified hostnames in the sudoers file. I.e., instead of myhost you would use myhost.mydomain.edu. You may still use the short form if you wish (and even mix the two). Beware that turning on fqdn requires sudo to make DNS lookups which may make sudo unusable if DNS stops working (for example if the machine is not plugged into the network). Also note that you must use the host's official name as DNS knows it. That is, you may not use a host alias (CNAME entry) due to performance issues and the fact that there is no way to get all aliases from DNS. If your machine's hostname (as returned by the hostname command) is already fully qualified you shouldn't need to set fqdn. [D: OFF]
ignore_dot
If set, sudo will ignore '.' or '' (current dir) in the PATH environment variable; the PATH itself is not modified. [D: OFF].ignore_local_sudoers If set via LDAP, parsing of /etc/sudoers will be skipped. This is intended for Enterprises that wish to prevent the usage of local sudoers files so that only LDAP is used. This thwarts the efforts of rogue operators who would attempt to add roles to /etc/sudoers. When this option is present, /etc/sudoers does not even need to exist. Since this option tells sudo how to behave when no specific LDAP entries have been matched, this sudoOption is only meaningful for the cn=defaults section. [D: OFF]
insults
If set, sudo will insult users when they enter an incorrect password. This flag is on by default.
lecture
This option controls when a short lecture will be printed along with the password prompt. It has the following possible values:
  • [always] Always lecture the user.
  • [never] Never lecture the user.
  • [once] Only lecture the user the first time they run sudo.
If no value is specified, a value of once is implied. Negating the option results in a value of never being used.
listpw
This option controls when a password will be required when a user runs sudo with the -l option. It has the following possible values:
  • [all] All the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
  • [always] The user must always enter a password to use the -l option.
  • [any] At least one of the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
  • [never] The user need never enter a password to use the -l option.
If no value is specified, a value of any is implied. Negating the option results in a value of never being used. The default value is any.
logfile
Path to the sudo log file (not the syslog log file). Setting a path turns on logging to a file; negating this option turns it off. By default, sudo logs via syslog .mailerflags Flags to use when invoking mailer. Defaults to -t.
log_host
If set, the hostname will be logged in the (non-syslog) sudo log file. [D: OFF]
loglinelen
Number of characters per line for the file log. This value is used to decide when to wrap lines for nicer log files. This has no effect on the syslog log file, only the file log. The default is 80 (use 0 or negate the option to disable word wrap).
log_year
If set, the four-digit year will be logged in the (non- syslog) sudo log file. [D: OFF].long_otp_prompt When validating with a One Time Password (OPT) scheme such as S/Key or OPIE, a two-line prompt is used to make it easier to cut and paste the challenge to a local window. It's not as pretty as the default but some people find it more convenient. [D: OFF]
mail_always
Send mail to the mailto user every time a users runs sudo
mail_badpass
Send mail to the mailto user if the user running sudo does not enter the correct password. [D: OFF]
mailerpath
Path to mail program used to send warning mail. Defaults to the path to sendmail found at configure time.
mailfrom
Address to use for the "from" address when sending warning and error mail. The address should be enclosed in double quotes (") to protect against sudo interpreting the @ sign. Defaults to the name of the user running sudo.
mail_no_host
If set, mail will be sent to the mailto user if the invoking user exists in the sudoers file, but is not allowed to run commands on the current host. [D: OFF]
mail_no_perms
If set, mail will be sent to the mailto user if the invoking user is allowed to use sudo but the command they are trying is not listed in their sudoers file entry or is explicitly denied. [D: OFF]
mail_no_user
If set, mail will be sent to the mailto user if the invoking user is not in the sudoers file. This flag is on by default.
mailsub
Subject of the mail sent to the mailto user. The escape %h will expand to the hostname of the machine. Default is *** SECURITY information for %h ***.
mailto
Address to send warning and error mail to. The address should be enclosed in double quotes (") to protect against sudo interpreting the @ sign. Defaults to root .secure_path Path used for every command run from sudo. If you don't trust the people running sudo to have a sane PATH environment variable you may want to use this. Another use is if you want to have the "root path" be separate from the "user path." Users in the group specified by the exempt_group option are not affected by secure_path. This option is not set by default.
noexec
If set, all commands run via sudo will behave as if the NOEXEC tag has been set, unless overridden by a EXEC tag. See the description of NOEXEC and EXEC below as well as the "PREVENTING SHELL ESCAPES" section at the end of this manual. [D: OFF]
noexec_file
Path to a shared library containing dummy versions of the execv(), execve() and fexecve() library functions that just return an error. This is used to implement the noexec functionality on systems that support LD_PRELOAD or its equivalent. Defaults to /usr/libexec/sudo_noexec.so.
passprompt
The default prompt to use when asking for a password; can be overridden via the -p option or the SUDO_PROMPT environment variable. The following percent (%) escapes are supported:
  • [%H] expanded to the local hostname including the domain name (on if the machine's hostname is fully qualified or the fqdn option is set)
  • [%h] expanded to the local hostname without the domain name
  • [%p] expanded to the user whose password is being asked for (respects the rootpw, targetpw and runaspw flags in sudoers)
  • [%U] expanded to the login name of the user the command will be run as (defaults to root)
  • [%u] expanded to the invoking user's login name
  • [%%] two consecutive % characters are collapsed into a single % character
The default value is SUDO Password: .
passwd_timeout
Number of minutes before the sudo password prompt times. The default is 150; set this to 0 for no password timeout. timestamp_timeout Number of minutes that can elapse before sudo will ask for a passwd again. The default is 1440. Set this to 0 to always prompt for a password. If set to a value less than 0 the user's timestamp will never expire. This can be used to allow users to create or delete their own timestamps via sudo -v and sudo -k respectively.
passwd_tries
The number of tries a user gets to enter his/her password before sudo logs the failure and exits. The default is 8 .Integers that can be used in a boolean context:
path_info
Normally, sudo will tell the user when a command could not be found in their PATH environment variable. Some sites may wish to disable this as it could be used to gather information on the location of executables that the normal user does not have access to. The disadvantage is that if the executable is simply not in the user's PATH, sudo will tell the user that they are not allowed to run it, which can be confusing. This flag is on by default .passprompt_override The password prompt specified by passprompt will normally only be used if the passwod prompt provided by systems such as PAM matches the string "Password:". If passprompt_override is set, passprompt will always be used. [D: OFF].preserve_groups By default, sudo will initialize the group vector to the list of groups the target user is in. When preserve_groups is set, the user's existing group vector is left unaltered. The real and effective group IDs, however, are still set to match the target user. [D: OFF]
pwfeedback
By default, sudo reads the password like most other Unix programs, by turning off echo until the user hits the return (or enter) key. Some users become confused by this as it appears to them that sudo has hung at this point. When pwfeedback is set, sudo will provide visual feedback when the user presses a key. Note that this does have a security impact as an onlooker may be able to determine the length of the password being entered .[D: OFF]
requiretty
If set, sudo will only run when the user is logged in to a real tty. When this flag is set, sudo can only be run from a login session and not via other means such as cron(8) or cgi-bin scripts. [D: OFF]
rootpw
If set, sudo will prompt for the root password instead of the password of the invoking user. [D: OFF]
root_sudo
If set, root is allowed to run sudo too. Disabling this prevents users from "chaining" sudo commands to get a root shell by doing something like "sudo sudo /bin/sh". Note, however, that turning off root_sudo will also prevent root and from running sudoedit. Disabling root_sudo provides no real additional security; it exists purely for historical reasons. This flag is on by default.
runas_default
The default user to run commands as if the -u option is not specified on the command line. This defaults to root. Note that if runas_default is set it must occur before any Runas_Alias specifications.
runaspw
If set, sudo will prompt for the password of the user defined by the runas_default option (defaults to root) instead of the password of the invoking user. [D: OFF]
setenv
Allow the user to disable the env_reset option from the command line. Additionally, environment variables set via the command line are not subject to the restrictions imposed by env_check, env_delete, or env_keep. As such, only trusted users should be allowed to set variables in this manner. [D: OFF]
set_home
If set and sudo is invoked with the -s option the HOME environment variable will be set to the home directory of the target user (which is root unless the -u option is used). This effectively makes the -s option imply -H. [D: OFF]
set_logname
Normally, sudo will set the LOGNAME, USER and USERNAME environment variables to the name of the target user (usually root unless the -u option is given). However, since some programs (including the RCS revision control system) use LOGNAME to determine the real identity of the user, it may be desirable to change this behavior. This can be done by negating the set_logname option. Note that if the env_reset option has not been disabled, entries in the env_keep list will override the value of set_logname. [D: OFF]
shell_noargs
If set and sudo is invoked with no arguments it acts as if the -s option had been given. That is, it runs a shell as root (the shell is determined by the SHELL environment variable if it is set, falling back on the shell listed in the invoking user's /etc/passwd entry if not). [D: OFF]
stay_setuid
Normally, when sudo executes a command the real and effective UIDs are set to the target user (root by default). This option changes that behavior such that the real UID is left as the invoking user's UID. In other words, this makes sudo act as a setuid wrapper. This can be useful on systems that disable some potentially dangerous functionality when a program is run setuid. This option is only effective on systems with either the setreuid() or setresuid() function. [D: OFF]
sudoers_locale
Locale to use when parsing the sudoers file. Note that changing the locale may affect how sudoers is interpreted. Defaults to "C".
syslog
Syslog facility if syslog is being used for logging (negate to disable syslog logging). Defaults to local2.
syslog_badpri
Syslog priority to use when user authenticates successfully. Defaults to alert.
syslog_goodpri
Syslog priority to use when user authenticates successfully. Defaults to notice.
targetpw
If set, sudo will prompt for the password of the user specified by the -u option (defaults to root) instead of the password of the invoking user. Note that this precludes the use of a uid not listed in the passwd database as an argument to the -u option. [D: OFF]
timestampdir
The directory in which sudo stores its timestamp files. The default is /var/run/sudo.
timestampowner
The owner of the timestamp directory and the timestamps stored therein. The default is root .Strings that can be used in a boolean context:
tty_tickets
If set, users must authenticate on a per-tty basis. Normally, sudo uses a directory in the ticket dir with the same name as the user running it. With this flag enabled, sudo will use a file named for the tty the user is logged in on in that directory. [D: OFF]
umask
Umask to use when running the command. Negate this option or set it to 0777 to preserve the user's umask. The actual umask that is used will be the union of the user's umask and 0022. This guarantees that sudo never lowers the umask when running a command. Note on systems that use PAM, the default PAM configuration may specify its own umask which will override the value set in sudoers .Strings: badpass_message Message that is displayed if a user enters an incorrect. The default is AHHH, bad password! Try again! unless insults are enabled.
umask_override
If set, sudo will set the umask as specified by sudoers without modification. This makes it possible to specify a more permissive umask in sudoers than the user's own umask and matches historical behavior. If umask_override is not set, sudo will set the umask to be the union of the user's umask and what is specified in sudoers. [D: OFF]
verifypw
This option controls when a password will be required when a user runs sudo with the -v option. It has the following possible values:
  • [all] All the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
  • [always] The user must always enter a password to use the -v option.
  • [any] At least one of the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
  • [never] The user need never enter a password to use the -v option.
If no value is specified, a value of all is implied. Negating the option results in a value of never being used. The default value is all
visiblepw
By default, sudo will refuse to run if the user must enter a password but it is not possible to disable echo on the terminal. If the visiblepw flag is set, sudo will prompt for a password even when it would be visible on the screen. This makes it possible to run things like "rsh somehost sudo ls" since rsh(1) does not allocate a tty. [D: OFF].

Defaults /etc/sudoers Cheatsheet

Here is a commented out list of all the options available to use with the Defaults command in /etc/sudoers. The idea is to copy and paste this in your sudoers files and then make changes.

sudoers-defaults-cheatsheet

#Defaults       always_set_home
# always_set_home: If enabled, sudo will set the HOME environment variable to the home directory of the target user (which is root unless the -u option is used).  This effectively means that the -H op
#     always_set_home is only effective for configurations where either env_reset is disabled or HOME is present in the env_keep list.  This flag is off by default.
 
#Defaults       authenticate
# authenticate: If set, users must authenticate themselves via a password (or other means of authentication) before they may run commands.  This default may be overridden via the PASSWD and NOPASSWD t
 
#Defaults       closefrom_override
# closefrom_override: If set, the user may use sudo's -C option which overrides the default starting point at which sudo begins closing open file descriptors.  This flag is off by default.
 
#Defaults       compress_io
# compress_io: If set, and sudo is configured to log a command's input or output, the I/O logs will be compressed using zlib.  This flag is on by default when sudo is compiled with zlib support.
 
#Defaults       env_editor
# env_editor: If set, visudo will use the value of the EDITOR or VISUAL environment variables before falling back on the default editor list.  Note that this may create a security hole as it allows th
#   separated list of editors in the editor variable.  visudo will then only use the EDITOR or VISUAL if they match a value specified in editor.  This flag is on by default.
 
#Defaults       env_reset
# env_reset: If set, sudo will run the command in a minimal environment containing the TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER, USERNAME and SUDO_* variables.  Any variables in the caller's envir
#   in the file specified by the env_file option (if any).  The default contents of the env_keep and env_check lists are displayed when sudo is run by root with the -V option.  If the secure_path opti
#   default.
 
#Defaults       fast_glob
# fast_glob: Normally, sudo uses the glob(3) function to do shell-style globbing when matching path names.  However, since it accesses the file system, glob(3) can take a long time to complete for som
#   (automounted).  The fast_glob option causes sudo to use the fnmatch(3) function, which does not access the file system to do its matching.  The disadvantage of fast_glob is that it is unable to ma
#   names that include globbing characters are used with the negation operator, '!', as such rules can be trivially bypassed.  As such, this option should not be used when sudoers contains rules that
 
#Defaults       fqdn
# fqdn: Set this flag if you want to put fully qualified host names in the sudoers file.  I.e., instead of myhost you would use myhost.mydomain.edu.  You may still use the short form if you wish (and
#   sudo unusable if DNS stops working (for example if the machine is not plugged into the network).  Also note that you must use the host's official name as DNS knows it.  That is, you may not use a
#     all aliases from DNS.  If your machine's host name (as returned by the hostname command) is already fully qualified you shouldn't need to set fqdn.  This flag is off by default.
 
#Defaults       ignore_dot
# ignore_dot: If set, sudo will ignore '.' or '' (current dir) in the PATH environment variable; the PATH itself is not modified.  This flag is off by default.
 
#Defaults       ignore_local_sudoers
# ignore_local_sudoers: If set via LDAP, parsing of /etc/sudoers will be skipped.  This is intended for Enterprises that wish to prevent the usage of local sudoers files so that only LDAP is used.  Th
#   present, /etc/sudoers does not even need to exist. Since this option tells sudo how to behave when no specific LDAP entries have been matched, this sudoOption is only meaningful for the cn=default
 
#Defaults       insults
# insults: If set, sudo will insult users when they enter an incorrect password.  This flag is off by default.
 
#Defaults       log_host
# log_host: If set, the host name will be logged in the (non-syslog) sudo log file.  This flag is off by default.
 
#Defaults       log_input
# log_input: If set, sudo will run the command in a pseudo tty and log all user input.  If the standard input is not connected to the user's tty, due to I/O redirection or because the command is part
#   Input is logged to the directory specified by the iolog_dir option (/var/log/sudo-io by default) using a unique session ID that is included in the normal sudo log line, prefixed with TSID=.  The i
#   Note that user input may contain sensitive information such as passwords (even if they are not echoed to the screen), which will be stored in the log file unencrypted.  In most cases, logging the
 
#Defaults       log_output
# log_output: If set, sudo will run the command in a pseudo tty and log all output that is sent to the screen, similar to the script(1) command.  If the standard output or standard error is not connec
#   is also captured and stored in separate log files.
#   Output is logged to the directory specified by the iolog_dir option (/var/log/sudo-io by default) using a unique session ID that is included in the normal sudo log line, prefixed with TSID=.  The
#   Output logs may be viewed with the sudoreplay(8) utility, which can also be used to list or search the available logs.
 
#Defaults       log_year
# log_year: If set, the four-digit year will be logged in the (non-syslog) sudo log file.  This flag is off by default.
 
#Defaults       long_otp_prompt
# long_otp_prompt: When validating with a One Time Password (OTP) scheme such as S/Key or OPIE, a two-line prompt is used to make it easier to cut and paste the challenge to a local window.  It's not
 
#Defaults       mail_always
# mail_always: Send mail to the mailto user every time a users runs sudo.  This flag is off by default.
 
#Defaults       mail_badpass
# mail_badpass: Send mail to the mailto user if the user running sudo does not enter the correct password.  This flag is off by default.
 
#Defaults       mail_no_host
# mail_no_host: If set, mail will be sent to the mailto user if the invoking user exists in the sudoers file, but is not allowed to run commands on the current host.  This flag is off by default.
 
#Defaults       mail_no_perms
# mail_no_perms: If set, mail will be sent to the mailto user if the invoking user is allowed to use sudo but the command they are trying is not listed in their sudoers file entry or is explicitly den
 
#Defaults       mail_no_user
# mail_no_user: If set, mail will be sent to the mailto user if the invoking user is not in the sudoers file.  This flag is on by default.
 
#Defaults       noexec
# noexec: If set, all commands run via sudo will behave as if the NOEXEC tag has been set, unless overridden by a EXEC tag.  See the description of NOEXEC and EXEC below as well as the "PREVENTING SHE
 
#Defaults       path_info
# path_info: Normally, sudo will tell the user when a command could not be found in their PATH environment variable.  Some sites may wish to disable this as it could be used to gather information on t
#   the executable is simply not in the user's PATH, sudo will tell the user that they are not allowed to run it, which can be confusing.  This flag is on by default.
 
#Defaults       passprompt_override
# passprompt_override: The password prompt specified by passprompt will normally only be used if the password prompt provided by systems such as PAM matches the string "Password:".  If passprompt_over
 
#Defaults       preserve_groups
# preserve_groups: By default, sudo will initialize the group vector to the list of groups the target user is in.  When preserve_groups is set, the user's existing group vector is left unaltered.  The
#   default.
 
#Defaults       pwfeedback
# pwfeedback: By default, sudo reads the password like most other Unix programs, by turning off echo until the user hits the return (or enter) key.  Some users become confused by this as it appears to
#   the user presses a key.  Note that this does have a security impact as an onlooker may be able to determine the length of the password being entered.  This flag is off by default.
 
#Defaults       requiretty
# requiretty: If set, sudo will only run when the user is logged in to a real tty.  When this flag is set, sudo can only be run from a login session and not via other means such as cron(8) or cgi-bin
 
#Defaults       root_sudo
# root_sudo: If set, root is allowed to run sudo too.  Disabling this prevents users from "chaining" sudo commands to get a root shell by doing something like "sudo sudo /bin/sh".  Note, however, that
#   real additional security; it exists purely for historical reasons.  This flag is on by default.
 
#Defaults       rootpw
# rootpw: If set, sudo will prompt for the root password instead of the password of the invoking user.  This flag is off by default.
 
#Defaults       runaspw
# runaspw: If set, sudo will prompt for the password of the user defined by the runas_default option (defaults to root) instead of the password of the invoking user.  This flag is off by default.
 
#Defaults       set_home
# set_home: If enabled and sudo is invoked with the -s option the HOME environment variable will be set to the home directory of the target user (which is root unless the -u option is used).  This eff
#   is enabled, so set_home is only effective for configurations where either env_reset is disabled or HOME is present in the env_keep list.  This flag is off by default.
 
#Defaults       set_logname
# set_logname: Normally, sudo will set the LOGNAME, USER and USERNAME environment variables to the name of the target user (usually root unless the -u option is given).  However, since some programs (
#   may be desirable to change this behavior.  This can be done by negating the set_logname option.  Note that if the env_reset option has not been disabled, entries in the env_keep list will override
 
#Defaults       set_utmp
# set_utmp: When enabled, sudo will create an entry in the utmp (or utmpx) file when a pseudo-tty is allocated.  A pseudo-tty is allocated by sudo when the log_input, log_output or use_pty flags are e
#   the tty, time, type and pid fields updated.  This flag is on by default.
 
#Defaults       setenv
# setenv: Allow the user to disable the env_reset option from the command line via the -E option.  Additionally, environment variables set via the command line are not subject to the restrictions impo
#   variables in this manner.  This flag is off by default.
 
#Defaults       shell_noargs
# shell_noargs: If set and sudo is invoked with no arguments it acts as if the -s option had been given.  That is, it runs a shell as root (the shell is determined by the SHELL environment variable if
#   is off by default.
 
#Defaults       stay_setuid
# stay_setuid: Normally, when sudo executes a command the real and effective UIDs are set to the target user (root by default).  This option changes that behavior such that the real UID is left as the
#   systems that disable some potentially dangerous functionality when a program is run setuid.  This option is only effective on systems with either the setreuid() or setresuid() function.  This flag
 
#Defaults       targetpw
# targetpw: If set, sudo will prompt for the password of the user specified by the -u option (defaults to root) instead of the password of the invoking user.  In addition, the timestamp file name will
#   passwd database as an argument to the -u option.  This flag is off by default.
 
#Defaults       tty_tickets
# tty_tickets: If set, users must authenticate on a per-tty basis.  With this flag enabled, sudo will use a file named for the tty the user is logged in on in the user's time stamp directory.  If disa
 
#Defaults       umask_override
# umask_override: If set, sudo will set the umask as specified by sudoers without modification.  This makes it possible to specify a more permissive umask in sudoers than the user's own umask and matc
#   user's umask and what is specified in sudoers.  This flag is off by default.
 
#Defaults       use_pty
# use_pty: If set, sudo will run the command in a pseudo-pty even if no I/O logging is being gone.  A malicious program run under sudo could conceivably fork a background process that retains to the u
#   that impossible.  This flag is off by default.
 
#Defaults       utmp_runas
# utmp_runas: If set, sudo will store the name of the runas user when updating the utmp (or utmpx) file.  By default, sudo stores the name of the invoking user.  This flag is off by default.
 
#Defaults       visiblepw
# visiblepw: By default, sudo will refuse to run if the user must enter a password but it is not possible to disable echo on the terminal.  If the visiblepw flag is set, sudo will prompt for a passwor
#   somehost sudo ls" since rsh(1) does not allocate a tty.  This flag is off by default.
 
#Defaults       closefrom
# closefrom: Before it executes a command, sudo will close all open file descriptors other than standard input, standard output and standard error (ie: file descriptors 0-2).  The closefrom option can
 
#Defaults       passwd_tries
# passwd_tries: The number of tries a user gets to enter his/her password before sudo logs the failure and exits.  The default is 3.
 
#Defaults       loglinelen
# loglinelen: Number of characters per line for the file log.  This value is used to decide when to wrap lines for nicer log files.  This has no effect on the syslog log file, only the file log.  The
 
#Defaults       passwd_timeout
# passwd_timeout: Number of minutes before the sudo password prompt times out, or 0 for no timeout.  The timeout may include a fractional component if minute granularity is insufficient, for example 2
 
#Defaults       timestamp_timeout
# timestamp_timeout: Number of minutes that can elapse before sudo will ask for a passwd again.  The timeout may include a fractional component if minute granularity is insufficient, for example 2.5.
#   timestamp will never expire.  This can be used to allow users to create or delete their own timestamps via sudo -v and sudo -k respectively.
 
#Defaults       umask
# umask: Umask to use when running the command.  Negate this option or set it to 0777 to preserve the user's umask.  The actual umask that is used will be the union of the user's umask and the value o
#   running a command.  Note on systems that use PAM, the default PAM configuration may specify its own umask which will override the value set in sudoers.
 
#Defaults       badpass_message
# badpass_message: Message that is displayed if a user enters an incorrect password.  The default is Sorry, try again. unless insults are enabled.
 
#Defaults       editor
# editor: A colon (':') separated list of editors allowed to be used with visudo.  visudo will choose the editor that matches the user's EDITOR environment variable if possible, or the first editor in
 
#Defaults       iolog_dir
# iolog_dir: The top-level directory to use when constructing the path name for the input/output log directory.  Only used if the log_input or log_output options are enabled or when the LOG_INPUT or L
#   directory.  The default is "/var/log/sudo-io".
#   The following percent (%) escape sequences are supported:
#     %{seq} - expanded to a monotonically increasing base-36 sequence number, such as 0100A5, where every two digits are used to form a new directory, e.g. 01/00/A5
#     %{user} - expanded to the invoking user's login name
#     %{group} - expanded to the name of the invoking user's real group ID
#     %{runas_user} - expanded to the login name of the user the command will be run as (e.g. root)
#     %{runas_group} - expanded to the group name of the user the command will be run as (e.g. wheel)
#     %{hostname} - expanded to the local host name without the domain name
#     %{command} - expanded to the base name of the command being run
#   In addition, any escape sequences supported by the system's strftime() function will be expanded.
#   To include a literal % character, the string %% should be used.
 
#Defaults       iolog_file
# iolog_file: The path name, relative to iolog_dir, in which to store input/output logs when the log_input or log_output options are enabled or when the LOG_INPUT or LOG_OUTPUT tags are present for a
#   See the iolog_dir option above for a list of supported percent (%) escape sequences.
#   In addition to the escape sequences, path names that end in six or more Xs will have the Xs replaced with a unique combination of digits and letters, similar to the mktemp() function.
 
#Defaults       mailsub
# mailsub: Subject of the mail sent to the mailto user. The escape %h will expand to the host name of the machine.  Default is *** SECURITY information for %h ***.
 
#Defaults       noexec_file
# noexec_file: This option is no longer supported.  The path to the noexec file should now be set in the /etc/sudo.conf file.
 
#Defaults       passprompt
# passprompt: The default prompt to use when asking for a password; can be overridden via the -p option or the SUDO_PROMPT environment variable.  The following percent (%) escape sequences are suppo
#     %H  expanded to the local host name including the domain name (only if the machine's host name is fully qualified or the fqdn option is set)
#     %h  expanded to the local host name without the domain name
#     %p  expanded to the user whose password is being asked for (respects the rootpw, targetpw and runaspw flags in sudoers)
#     %U  expanded to the login name of the user the command will be run as (defaults to root)
#     %u  expanded to the invoking user's login name
#     %%  two consecutive % characters are collapsed into a single % character
#   The default value is Password:.
 
#Defaults       runas_default
# runas_default: The default user to run commands as if the -u option is not specified on the command line.  This defaults to root.
 
#Defaults       syslog_badpri
# syslog_badpri: Syslog priority to use when user authenticates unsuccessfully.  Defaults to alert.
#   The following syslog priorities are supported: alert, crit, debug, emerg, err, info, notice, and warning.
 
#Defaults       syslog_goodpri
# syslog_goodpri: Syslog priority to use when user authenticates successfully.  Defaults to notice.
#   See syslog_badpri for the list of supported syslog priorities.
 
#Defaults       sudoers_locale
# sudoers_locale: Locale to use when parsing the sudoers file, logging commands, and sending email.  Note that changing the locale may affect how sudoers is interpreted.  Defaults to "C".
 
#Defaults       timestampdir
# timestampdir: The directory in which sudo stores its timestamp files.  The default is /var/db/sudo.
 
#Defaults       timestampowner
# timestampowner: The owner of the timestamp directory and the timestamps stored therein.  The default is root.
 
#Defaults       env_file
# env_file: The env_file option specifies the fully qualified path to a file containing variables to be set in the environment of the program being run.  Entries in this file should either be of the f
#   quotes.  Variables in this file are subject to other sudo environment settings such as env_keep and env_check.
 
#Defaults       exempt_group
# exempt_group: Users in this group are exempt from password and PATH requirements.  The group name specified should not include a % prefix.  This is not set by default.
 
#Defaults       group_plugin
# group_plugin: A string containing a sudoers group plugin with optional arguments.  This can be used to implement support for the nonunix_group syntax described earlier.  The string should consist of
#   configuration arguments the plugin requires.  These arguments (if any) will be passed to the plugin's initialization function.  If arguments are present, the string must be enclosed in double quot
#   For example, given /etc/sudo-group, a group file in Unix group format, the sample group plugin can be used:
#   Defaults group_plugin="sample_group.so /etc/sudo-group"
#   For more information see sudo_plugin(5).
 
#Defaults       lecture
# lecture: This option controls when a short lecture will be printed along with the password prompt.  It has the following possible values:
#     always  Always lecture the user.
#     never   Never lecture the user.
#     once    Only lecture the user the first time they run sudo.
#   If no value is specified, a value of once is implied.  Negating the option results in a value of never being used.  The default value is once.
 
#Defaults       lecture_file
# lecture_file: Path to a file containing an alternate sudo lecture that will be used in place of the standard lecture if the named file exists.  By default, sudo uses a built-in lecture.
 
#Defaults       listpw
# listpw: This option controls when a password will be required when a user runs sudo with the -l option.  It has the following possible values:
#     all     All the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
#     always  The user must always enter a password to use the -l option.
#     any     At least one of the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
#     never   The user need never enter a password to use the -l option.
#   If no value is specified, a value of any is implied.  Negating the option results in a value of never being used.  The default value is any.
 
#Defaults       logfile
# logfile: Path to the sudo log file (not the syslog log file).  Setting a path turns on logging to a file; negating this option turns it off.  By default, sudo logs via syslog.
 
#Defaults       mailerflags
# mailerflags: Flags to use when invoking mailer. Defaults to -t.
 
#Defaults       mailerpath
# mailerpath: Path to mail program used to send warning mail.  Defaults to the path to sendmail found at configure time.
 
#Defaults       mailfrom
# mailfrom: Address to use for the "from" address when sending warning and error mail.  The address should be enclosed in double quotes (") to protect against sudo interpreting the @ sign.  Defaults t
 
#Defaults       mailto
# mailto: Address to send warning and error mail to.  The address should be enclosed in double quotes (") to protect against sudo interpreting the @ sign.  Defaults to root.
 
#Defaults       secure_path
# secure_path: Path used for every command run from sudo.  If you don't trust the people running sudo to have a sane PATH environment variable you may want to use this.  Another use is if you want to
#   option are not affected by secure_path.  This option is not set by default.
 
#Defaults       syslog
# syslog: Syslog facility if syslog is being used for logging (negate to disable syslog logging).  Defaults to auth.
#   The following syslog facilities are supported: authpriv (if your OS supports it), auth, daemon, user, local0, local1, local2, local3, local4, local5, local6, and local7.
 
#Defaults       verifypw
# verifypw: This option controls when a password will be required when a user runs sudo with the -v option.  It has the following possible values:
#     all     All the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
#     always  The user must always enter a password to use the -v option.
#     any     At least one of the user's sudoers entries for the current host must have the NOPASSWD flag set to avoid entering a password.
#     never   The user need never enter a password to use the -v option.
#   If no value is specified, a value of all is implied.  Negating the option results in a value of never being used.  The default value is all.
 
#Defaults       env_check
# env_check: Environment variables to be removed from the user's environment if the variable's value contains % or / characters.  This can be used to guard against printf-style format vulnerabilities
#   value without double-quotes.  The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators respectively.  Regardless of whether the env_reset option is ena
#   they pass the aforementioned check.  The default list of environment variables to check is displayed when sudo is run by root with the -V option.
 
#Defaults       env_delete
# env_delete: Environment variables to be removed from the user's environment when the env_reset option is not in effect.  The argument may be a double-quoted, space-separated list or a single value w
#   +=, -=, and ! operators respectively.  The default list of environment variables to remove is displayed when sudo is run by root with the -V option.  Note that many operating systems will remove p
 
#Defaults       env_keep
# env_keep: Environment variables to be preserved in the user's environment when the env_reset option is in effect.  This allows fine-grained control over the environment sudo-spawned processes will r
#   quotes.  The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators respectively.  The default list of variables to keep is displayed when sudo is run by

SUDO – sudoers Config File originally appeared on AskApache.com


Adding a Trailing “/” to WordPress Permalinks

$
0
0

AskApache.com

Problem: You use a custom permalink structure that doesn't end in a /, which causes ALL permalinks (pages, categories, etc) to NOT have an ending /.

Solution: Either hook into the user_trailingslashit filter, or use htaccess RedirectMatch

Custom Permalinks

Let's say that like AskApache your permalink structure is something that doesn't end in a '/' like:

/%category%/%postname%.html

The WP_Rewrite class has a var named $use_trailing_slashes that is set dynamically based upon whether or not your custom permalink structure ends in a '/'.

$this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );

This means that all WP generated links (the_permalink, category_link, the_permalink_rss, etc.) will not end in a '/'. So for category pages WP will show '/category/category' instead of '/category/category/'.

Sample user_trailingslashit Filter

The user_trailingslashit function applies the 'user_trailingslashit' filter to the result prior to returning it. It provides the url and the type of url to the filter.

$string = apply_filters('user_trailingslashit', $string, $type_of_url);

So to hook into this and add a trailing slash to all urls other than single posts add this code to a plugin file or your functions.php theme file.

function fix_trailingsss($s='',$t='single')
{
  if($t!='single')$s=rtrim($s,'/').'/';
  return preg_replace('/^(.*)([^l\/])$/i', '\\1\\2/',$s);
}
add_filter('user_trailingslashit', 'fix_trailingsss', 9999,2);

Htaccess RedirectMatch

You can setup an .htaccess redirect to force category urls to always use a trailing slash like this:

RedirectMatch 301 ^/category/([^/]+)$ /category/$1/

Adding a Trailing “/” to WordPress Permalinks originally appeared on AskApache.com


Linux Debugging using a Bootloader with Kernel Parameters

$
0
0

AskApache.com

The grub menu.lst provides for a convenient way to add a number of entries with extended kernel parameters to configure all sorts of advanced settings to enable you to quickly and conveniently boot into your existing system with varying levels of debugging output. It's very easy and useful to create several levels of debugging just by adding additional entries to your grub configuration. And if you ever have issues or problems down the road due to a power-failure or hardware failure, it can save you hours of trouble, and of course nothing can beat debugging output when it comes to learning about your system.

Useful Menu.lst Entries

If you are interested in debugging, then you deserve some grub entries for powerusers, here are a few that I like (just add to your menu.lst).

title Shutdown the Computer
halt
 
title Reboot the Computer
reboot
 
title Command Line
commandline
 
title Install GRUB to hd0 MBR
root (hd0,0)
setup (hd0)
 
title Matrix
color green/black light-green/green
 
title Scan for /boot/grub/menu.lst
find --set-root --ignore-floppies /boot/grub/menu.lst
configfile /boot/grub/menu.lst
 
title Scan for /boot/menu.lst
find --set-root --ignore-floppies /menu.lst
configfile /boot/menu.lst
 
# http://www.vortex.prodigynet.co.uk/x86test/
title    Run x86test (CPU Info)
kernel /boot/x86test_zImage.bin
#wget http://www.vortex.prodigynet.co.uk/x86test/x86test_zImage.bin
 
# http://www.memtest.org/
title    Run memtest86+ (Memory Testing)
kernel /boot/memtest86+-1.70.bin

Light Debug

A quick way to see more verbose messages on your console is to bootup your normal grub entry after appending verbose to the kernel line. This simple word added to your kernel line turns on more logging thanks to the /etc/rc.sysinit file, which at the top of the file runs:

if /bin/grep -q " verbose" /proc/cmdline; then /bin/dmesg -n 8; fi

Very simple way to get a bit more messages and debug output in your logs.

title  Arch Linux DEBUG Light
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro rootwait verbose
initrd /kernel26.img

Medium Debug

This example menu.lst entry turns on real logging that is set by the kernel and not in an init script. Adding the debug kernel parameter to your kernel line is recognized by a lot of linux internals and enables quite a bit of debugging compared to the default.

title Arch Linux DEBUG Medium
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro rootdelay=5 panic=10 debug
initrd /kernel26.img

Heavy Debug

An even more impressive kernel parameter is the ignore_loglevel, which causes the system to ignore any loglevel and keeps the internal loglevel at the maximum debugging level, basically rendering dmesg unable to lower the debug level.

title Arch Linux DEBUG Heavy
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro rootdelay=5 panic=10 debug ignore_loglevel
initrd /kernel26.img

Extreme Debug

If the "Heavy Debug" seemed like a lot of output, thats about 1/2 of the logging that occurs with this example. This does a couple things, it uses the earlyprintk parameter to setup your kernel for "early" "printing" of messages to your "vga" screen. The ,keep just lets it stay on the screen longer. This will let you see logs that normally are hidden due to the boot-up process. This also changes the log buffer length to 10MB, and also instructs that any fatal signals be printed with print_fatal_signals. The last one, sched_debug, you can look up in the very excellent kernel documentation on kernel parameters.

title Arch Linux DEBUG Extreme
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro debug ignore_loglevel log_buf_len=10M print_fatal_signals=1 LOGLEVEL=8 earlyprintk=vga,keep sched_debug
initrd /kernel26.img

Insane Debug

The first few debugging examples showed some really nice kernel parameters to turn on really verbose debugging. This kind of debugging is absolutely critical if you want to max out your system or just learn more about what is going on behind the scenes. But there is a final trick that is my favorite, it's the ability to set both environment variables, and more importantly, module parameters at boot.

As an example, here is the boot line that I am using at the moment on an older Dell Desktop, just to illustrate module parameters and environment vars.

title  Arch Linux X-256
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro rootwait pause_on_oops=5 panic=60 i915.modeset=1 no_console_suspend ipv6.disable=1 TERM=xterm-256color quiet 5
initrd /kernel26.img

Since it's low on both memory and CPU, I disable ipv6. I also turn on kernel modesetting for the i915 video card, set my terminal to be xterm-256color, and boot straight into X. This lets me use a very optimized arch-linux configuration, amazing how fast thanks to using slim as the login manager, ratpoison as my window manager, and terminal with tmux as my login shell, all from boot, as the pstree shows (plus Synergy!).

init,1
  |-slim,3096
  |   |-X,3098 -nolisten tcp vt07 -auth /var/run/slim.auth
  |   `-ratpoison,3107,askapache
  |       |-terminal,5341 -x sh -c exec /usr/bin/tmux -2 -l -u -q attach -d -t tmux-askapache
  |       |   |-bash,11165
  |       |   |-tmux,5345 -2 -l -u -q attach -d -t tmux-askapache
  |       |   `-{terminal},5346
  |       `-xscreensaver,3113 -no-splash
  |-synergyc,6121,galileo -f --name galileo-fire --restart 10.66.66.2:26666
  |
  `-tmux,5348,askapache -2 -l -u -q attach -d -t tmux-askapache
      |-bash,5351
      |   `-ssh,9969 lug@askapache.com
      `-bash,5868
         `-vim,11149 -p sda1/grub/menu.lst /boot/grub/menu.lst

That kind of optimized system is only possible if you first can figure out your system, by debugging both the kernel as previously illustrated, debugging the init process, and most importantly, by debugging the modules enabled for your system's hardware/firmware/software. Debugging modules is challenging but worth the effort, and then you are able to do some truly insane debugging from grub like the following example, note that the actual grub entry is all on one line, but I split it into 4 lines so you could see it all. This basically turns on every module on this little Dell desktop to be at the absolute max debug level. There is so much logging when I boot this that the system grinds to a halt and is slower than a TI-89 calculator (See Improve Boot Performance).

title  Arch Linux DEBUG INSANE
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro rootwait ignore_loglevel debug debug_locks_verbose=1 sched_debug initcall_debug mminit_loglevel=4 udev.log_priority=8
       loglevel=8 earlyprintk=vga,keep log_buf_len=10M print_fatal_signals=1 apm.debug=Y i8042.debug=Y drm.debug=1 scsi_logging_level=1 usbserial.debug=Y
       option.debug=Y pl2303.debug=Y firewire_ohci.debug=1 hid.debug=1 pci_hotplug.debug=Y pci_hotplug.debug_acpi=Y shpchp.shpchp_debug=Y apic=debug
       show_lapic=all hpet=verbose lmb=debug pause_on_oops=5 panic=10 sysrq_always_enabled
initrd /kernel26.img

A couple key items from that grub entry are sysrq_always_enabled which forces on the sysrq magic, which really is a lifesaver when debugging at this level as your machine will freeze/stop-responding sometimes and it's nice to use sysrq to kill all tasks, change the loglevel, unmount all filesystems, or do a hard reboot. Another key parameter is the initcall_debug, which debugs the init process in excruciating detail. Very useful at times. The last parametery I find very useful is the udev.log_priority=8 to turn on udev logging.

Break Into Init

For instance, If you add break=y to your kernel cmdline, init will pause early in the boot process (after loading modules) and launch an interactive sh shell which can be used for troubleshooting purposes. (Normal boot continues after logout.) This is very similar to the shell that shows up if your computer gets turned off before it is able to shutdown properly. But using this parameter lets you enter into this mode differently at will.

title  Arch Linux Init Break
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro rootwait break=y
initrd /kernel26.img

Debugging init

This awesome parameter udev.log_priority=8 does the same thing as editing the file /etc/udev/udev.conf except it executes earlier, turning on debugging output for udev. If you want to know your hardware, that is the key parameter right there. Another trick is if you change the /etc/udev/udev.conf to be verbose, then you can make your initrd image include that file to turn on verbose udeb debugging by adding it to your {{Filename|/etc/mkinitcpio.conf} like:

FILES="/etc/modprobe.d/modprobe.conf /etc/udev/udev.conf"

, which on arch is as easy as

# mkinitcpio -p kernel26

Debugging udev is key because the initrd performs a root change at the end of its run to usually launch a program like /sbin/init as part of a chroot, and unless the new file system has a valid /dev directory, udev must be initialized before invoking chroot in order to provide /dev/console.

exec chroot . /sbin/init <dev/console >dev/console 2>&1

So basically, you aren't able to view the logs that are generated before /dev/console is initialized by udev or by a special initrd you compiled yourself. One method the kernel developers use to be able to still get the log messages generated before /dev/console is available is to provide an alternative console that you can enable or disable from grub.

Net Console

If you read through the kernel documentation regarding debugging, you will hear about Netconsole, which can be loaded from the kernel line in GRUB, compiled into your kernel, or loaded at runtime as a module. Having a netconsole entry in your menu.lst is most excellent for debugging slower computers like old laptops or thin-clients. It's easy to use. Just setup a 2nd computer (running arch) to accept syslog requests on a remote port, very fast and quick to do on arch-linux, 1 line to syslog.conf. Then you could use a log-color-parser like ccze to view all syslog logs, or just tail your everything.log. Then on your laptop, boot up and select the netconsole entry from the grub menu, and you will start seeing as much logging as you want on your syslog system. This logging lets you view even earlier log output than is available with the earlyprintk=vga kernel parameter, as netconsole is used by kernel hackers and developers, so it's very powerful.

title  Arch Linux DEBUG Netconsole
kernel /vmlinuz26 root=/dev/disk/by-label/ROOT ro netconsole=514@10.0.0.2/12:34:56:78:9a:bc debug ignore_loglevel
initrd /kernel26.img

Hijacking cmdline

If you do not have access to GRUB or the kernel boottime cmdline, like on a server or virtual machine, as long as you have root permissions you can still enable this kind of simplistic verbose logging using a neat hack. While you cannot modify the /proc/cmdline even as root, you can place your own cmdline file on top of /proc/cmdline, so that accessing /proc/cmdline actually accesses your file.

For example if I cat /proc/cmdline, I have the following:

root=/dev/disk/by-label/ROOT ro console=tty1 logo.nologo quiet

So I use a simple sed command to replace quiet with verbose like:

sed 's/ quiet/ verbose/' /proc/cmdline > /root/cmdline

Then I bind mount /root/cmdline so that it becomes /proc/cmdline, using the -n option to mount so that this mount won't be recorded in the systems mtab.

mount -n --bind -o ro /root/cmdline /proc/cmdline

Now if I cat /proc/cmdline, I have the following:

root=/dev/disk/by-label/ROOT ro console=tty1 logo.nologo verbose

This is part of the GRUB article on the Arch Linux wiki that I contributed. As of now, just a copy.

Linux Debugging using a Bootloader with Kernel Parameters originally appeared on AskApache.com


No Budget Developer Wishlist

$
0
0

AskApache.com

Night Sky

  • I need no software, I lack for nothing when it comes to software. winners don't do warez
  • Well obviously if I could have anything I would want access to NSA computing power, googles server farms as a backup, and the worlds most expensive computer monitor the size of my wall with virtual screens as big as I want and touch screen and 3d and holograms.
  • I would want the best office chair made for comfort.
  • an iphone docking station to keep my phone charging and docked on my desk
  • an F5 device I could beat up gangland style with a baseball bat, and an F5 device I could install locally and experiment with until I had it mastered
  • an ipad to read emails on the treadmill and view websites while mobile
  • I would love to have my adobe software paid for, it's costing me like 50/month for dreamweaver and photoshop
  • love to have a enterprise battery backup
  • love to have a satellite link for fast internet access even during a power outage and anywhere on the planet so i could use encrypted shells and be on a safe network anywhere
  • really wish I had a a few thousand terabytes of raid storage for redundant and safe back ups and storage of everything.. EVERYTHING.
  • wish I had a new ti-92 (not 89) calculator which I used to use all the time for CSS work and programming.. then it broke :(
  • it would be great to get a mainframe in my office to run virtual servers off of
  • wouldn't mind access to a work vehicle, preferably electric like googles employee electric cars
  • I'd love a dedicated computer and monitor just for my email
  • I'd love a million dollar gift certificate to buy tech books on amazon
  • How about a 5k worth of high-end super tiny thumb drives so I can bring live operating systems with me to run from ram
  • I need a high end (or heck low end) ear phones for my iphone with a mic so I can use skype without having to hold my phone so i can type
  • i wish I had a small fridge in my office stocked with mountain dew and starbucks double shots and candy, the good kind
  • gosh I could really go on for days and days and days and love drooling but gotta crash..

No Budget Developer Wishlist originally appeared on AskApache.com

Optimized Vimrc with 256 Colorscheme

$
0
0

AskApache.com

This is 90% geared for purely console/terminal/pty/tty/ssh/putty/telnet/tmux/screen users. I've only just the past couple years started understanding why it was key to learn vim, in the past I never had the patience for it and preferred nano-like editors. Now vim is all I use when on linux, it's so much more productive.. especially with a customized vimrc file. This doesn't require a git checkout, a vim update, a bash update, an OS update, a plugin. No. This is a single file that I use on Arch Linux, NetBSD, FreeBSD, OpenBSD, Debian, Ubuntu, Cent OS, Red Hat, and that's it so far. This is geared for users who use SSH more than anything else. Of course, it works perfect on an X enabled box locally as well.

ScreenShot

Screenshot of this vimrc in action

Setup

I install this as /etc/vimrc if possible. Individual users can use a vim config file in their home directories.

source /etc/vimrc

To install for a single user just save it in their home dir at /home/username/.vimrc

Portability

For the portability needed to work on many different systems, this doesn't rely on any plugins other than those built into the default installation of vim 7.0. It works well on all types of consoles, and depending on the TERM environment variable (and whether it has the right term capabilities) it will load 256 color support or not. Usually on a new system I just scp this right over and it works without any modifications. But an ongoing Work in progress.

Optimized Vimrc

Download - Optimized vimrc

" Updated: Wed Feb 22 13:25:23 2012 by galileo@galileo
 
" For all key mappings like ', .' to reload vimrc
let maplocalleader=','
 
" BACKUPS, SWAPFILES, VIEWDIR, TMPDIR  "{{{1
" ================================================================================================================================================================
 
" SET RUNTIMEPATH {{{3
if isdirectory(expand("$HOME/.vim"))
  let $VIMRUNTIME=expand("$HOME/.vim")
  set runtimepath=$VIMRUNTIME
endif
 
" IF BKDIR IS NOT SET OR EMPTY, SET {{{3
if $BKDIR == ""
  let $BKDIR=expand("$HOME/.bk")
  if !isdirectory(expand("$BKDIR"))
    call mkdir(expand("$BKDIR"), "p", 0700)
  endif
endif
 
" MAKE DIRS IF mkdir exists {{{3
if exists("*mkdir")
  if !isdirectory(expand("$BKDIR/.vim/viewdir"))|call mkdir(expand("$BKDIR/.vim/viewdir"), "p", 0700)|endif
  if !isdirectory(expand("$BKDIR/.vim/tmp"))|call mkdir(expand("$BKDIR/.vim/tmp"), "p", 0700)|endif
  if !isdirectory(expand("$BKDIR/.vim/backups"))|call mkdir(expand("$BKDIR/.vim/backups"), "p", 0700)|endif
endif
 
" SETTINGS USING NEW DIRS {{{3
let &dir=expand("$BKDIR") . "/.vim"
let &viewdir=expand("$BKDIR") . "/.vim/viewdir"
let &backupdir=expand("$BKDIR") . "/.vim/backups"
"let &verbosefile=expand("$BKDIR") . "/.vim/vim-messages.
 
" VIMINFO {{{3
" COMMENTED OUT {{{4
"  "       Maximum number of lines saved for each register
"  %       When included, save and restore the buffer lis
"  '       Maximum number of previously edited files for which the marks are remembere
"  /       Maximum number of items in the search pattern history to be saved
"  :        Maximum number of items in the command-line history
"  <       Maximum number of lines saved for each register.
"   @       Maximum number of items in the input-line history
"  h       Disable the effect of 'hlsearch' when loading the viminfo
"  n       Name of the viminfo file.  The name must immediately follow the 'n'.  Must be the last oneEnvironment variables are expanded when opening the file, not when setting the option
"  r       Removable media.  The argument is a string
"  s       Maximum size of an item in Kbyte
"   }}}4 COMMENTED OUT
let &viminfo="%200,'200,/800,h,<500,:500,s150,r/tmp,r" . expand("$BKDIR") . "/.vim/tmp,n" . expand("$BKDIR") ."/.vim/.vinfo"
 
" CUSTOM FUNCTIONS "{{{1
" ================================================================================================================================================================
if !exists("AskApacheLoaded")
  let AskApacheLoaded=1
 
  " FUNCTION - LastMod {{{3
  " Warning, this is controlled by an autocmd triggered when closing the file that updates the file (in a great way)
  " Updated: Wed Feb 22 13:25:23 2012 by galileo@galileo
  function! LastMod()
    exe "silent! 1,20s/Updated: .*/" . printf('Updated: %s by %s@%s', strftime("%c"), expand("$LOGNAME"), hostname()) . "/e"
  endfunction
 
  " FUNCTION - LastModNow {{{3
  " An even better version than LastMod()
  function! LastModNow()
    call setline(line('.'), printf('%sUpdated: %s by %s@%s', printf(&commentstring, ' '), strftime("%c"), expand("$LOGNAME"), hostname()))
    "printf('%sUpdated: %s by %s@%s', printf(&commentstring, ' '), strftime("%c"), expand("$LOGNAME"), hostname())|dd|j|dd<cr><esc>
    "printf('Updated: %s by %s %s', strftime("%c"), expand("$LOGNAME@$HOSTNAME")) ."/e"
  endfunction
 
  " FUNCTION - AppendModeline {{{3
  " Append modeline after last line in buffer.  Use substitute() instead of printf() to handle '%%s' modeline
  function! AppendModeline()
    let l:modeline = printf(" vim: set ft=%s ts=%d sw=%d tw=%d foldmethod=%s :", &filetype, &tabstop, &shiftwidth, &textwidth, &foldmethod)
    let l:modeline = substitute(&commentstring, "%s", l:modeline, "")
    call append(line("$"), l:modeline)
  endfunction
 
  " FUNCTION - LastModAAZZZ {{{3
  " AA_UPDATED='01/24/12-00:56:00'
  function! LastModAAZZZ()
    exe "1,50s/AA_UPDATED=.*/AA_UPDATED='" . strftime("%c") . "'"
  endfunction
 
  " FUNCTION - StripTrailingWhitespace {{{3
  " automatically remove trailing whitespace before write
  function! StripTrailingWhitespace()
    normal mZ
    %s/s+$//e
    if line("'Z") != line(".")|echo "Stripped whitespacen"|endif
    normal `Z
  endfunction
 
  " FUNCTION - MyTabL {{{3
  function! MyTabL()
    let s = ''|let t = tabpagenr()|let i = 1
    while i <= tabpagenr('$')
      let bl = tabpagebuflist(i)|let wn = tabpagewinnr(i)
      let s .= '%' . i . 'T'. (i == t ? '%1*' : '%2*') . '%*' . (i == t ? ' %#TabLineSel# ' : '%#TabLine#')
      let file = (i == t ? fnamemodify(bufname(bl[wn - 1]), ':p') : fnamemodify(bufname(bl[wn - 1]), ':t') )|if file == ''|let file = '[No Name]'|endif
      let s .= i.' '. file .(i == t ? ' ' : '')|let i += 1
    endwhile
    let s .= '%T%#TabLineFill#%=' . (tabpagenr('$') > 1 ? '%999XX' : 'X')
    return s
  endfunction
 
  " FUNCTION - DiffWithSaved {{{3
  " Diff with saved version of the file
  function! s:DiffWithSaved()
    let filetype=&ft
    diffthis
    vnew | r # | normal! 1Gdd
    diffthis
    exe "setlocal bt=nofile bh=wipe nobl noswf ro ft=" . filetype
  endfunction
  com! DiffSaved call s:DiffWithSaved()
 
  " FUNCTION - ShowWhitespace() {{{3
  function! ShowWhitespace(flags)
    let bad = ''
    let pat = []
    for c in split(a:flags, 'zs')
      if c == 'e'
        call add(pat, 's+$')
      elseif c == 'i'
        call add(pat, '^t*zs +')
      elseif c == 's'
        call add(pat, ' +zet')
      elseif c == 't'
        call add(pat, '[^t]zst+')
      else
        let bad .= c
      endif
    endfor
 
    if len(pat) > 0
      let s = join(pat, '|')
      exec 'syntax match ExtraWhitespace "'.s.'" containedin=ALL'
    else
      syntax clear ExtraWhitespace
    endif
 
    if len(bad) > 0|echo 'ShowWhitespace ignored: '.bad|endif
  endfunction
 
  " FUNCTION - ToggleShowWhitespace {{{3
  " I use this all the time, it's mapped to , ts
  function! ToggleShowWhitespace()
    if !exists('b:ws_show')|let b:ws_show = 0|endif
    if !exists('b:ws_flags')|let b:ws_flags = 'est'|endif
    let b:ws_show = !b:ws_show
    if b:ws_show|call ShowWhitespace(b:ws_flags)|else|call ShowWhitespace('')|endif
  endfunction
 
endif
 
" DYNAMIC SETTINGS / COLORS / TERMINAL {{{1
" ================================================================================================================================================================
 
" DISABLE MOUSE NO GOOEYS {{{3
if has('mouse')|set mouse=|endif
 
" SET TITLESTRING {{{3
if has('title')|set titlestring=%t%( [%R%M]%)|endif
 
" SET TABLINE {{{3
if exists("*s:MyTabL")|set tabline=%!MyTabL()|endif
 
let g:vimsyn_folding='af'
 
"DISABLE FILETYPE-SPECIFIC MAPS {{{3
let no_plugin_maps=1
 
"}}}1 DYNAMIC SETTINGS / COLORS / TERMINAL
 
" OPTIONS "{{{1
" ===========================================================================================================================================================================
 
" BACKUP, FILE OPTIONS {{{2
" ================================================================================
set backup        " Make a backup before overwriting a file.  Leave it around after the file has been successfully written.
set backupcopy=auto " When writing a file and a backup is made, this option tells how it's done.  This is a comma separated list of words. - value: yes,no,auto - no:rename the file and write a new one
 
set swapfile
set swapsync=fsync
 
"}}}2 BACKUP, FILE OPTIONS
 
" BASIC SETTINGS "{{{2
" ================================================================================
set nocompatible    " vim, not vi.. must be first, because it changes other options as a side effect
set modeline
 
set statusline=%M%h%y %t %F %p%% %l/%L %=[%{&ff},%{&ft}] [a=%03.3b] [h=%02.2B] [%l,%v]
set title titlelen=150 titlestring=%( %M%)%( (%{expand("%:p:h")})%)%( %a%) - %{v:servername}
 
"set tags=tags;/      " search recursively up for tags
 
set ttyfast        " we have a fast terminal
set scrolljump=5    " when scrolling up down, show at least 5 lines
"set ttyscroll=999    " make vim redraw screen instead of scrolling when there are more than 3 lines to be scrolled
 
"set tw=500        " default textwidth is a max of 5
 
set undolevels=10    " 50 undos - saved in memory
set updatecount=250    " switch every 250 chars, save swap
 
set whichwrap+=b,s,<,>,h,l,[,]      " backspaces and cursor keys wrap to
"set wildignore+=*.o,*~,.lo,*.exe,*.bak  " ignore object files
"set wildmenu              " menu has tab completion
"set wildmode=longest:full        " *wild* mode
set nowrap
 
set autoindent smartindent    " auto/smart indent
 
set autoread          " watch for file changes
 
set backspace=indent,eol,start  " backspace over all kinds of things
 
set cmdheight=1          " command line two lines high
set complete=.,w,b,u,U,t,i,d  " do lots of scanning on tab completion
set cursorline          " show the cursor line
"set enc=utf-8 fenc=utf-8    " utf-8
 
set history=3000        " keep 3000 lines of command line history
 
set keywordprg=TERM=mostlike man -s -Pless
 
set laststatus=2
 
"set lazyredraw          " don't redraw when don't have to
set linebreak          " wrap at 'breakat' instead of last char
set magic            " Enable the "magic"
 
set maxmem=25123  " 24 MB -  max mem in Kbyte to use for one buffer.  Max is 2000000
 
set noautowrite          " don't automagically write on :next
 
set noexpandtab          " no expand tabs to spaces"
set noruler          " show the line number on the bar
set nospell
set nohidden          " close the buffer when I close a tab (I use tabs more than buffers)
 
set noerrorbells visualbell t_vb= " Disable ALL bells
 
set number          " line numbers
 
set pastetoggle=<f11>
 
set scrolloff=3        " keep at least 3 lines above/below
set shiftwidth=3      " shift width
 
set showcmd          " Show us the command we're typing
set showfulltag        " show full completion tags
set showmode        " show the mode all the time
 
set sidescroll=2      " if wrap is off, this is fasster for horizontal scrolling
set sidescrolloff=2      "keep at least 5 lines left/right
 
set noguipty
 
set splitright
set splitbelow
 
set restorescreen=on " restore screen contents when vim exits -  disable withset t_ti= t_te=
 
"set sessionoptions=word,blank,buffers,curdir,folds,globals,help,localoptions,resize,sesdir,tabpages,winpos,winsize
set winheight=25
set winminheight=1  " minimal value for window height
"set winheight=30  " set the minimal window height
set equalalways    " all the windows are automatically sized same
set eadirection=both  " only equalalways for horizontally split windows
 
set hlsearch
 
set laststatus=2
 
set tabstop=4
set softtabstop=4
 
set shiftwidth=3
set switchbuf=usetab
 
set commentstring=#%s
 
set tabpagemax=55
set showtabline=2    " 2 always, 1 only if multiple tabs
set smarttab      " tab and backspace are smart
 
set foldmethod=marker
set foldenable
set foldcolumn=6        " the blank left-most bar left of the numbered lines
 
set incsearch          " incremental search
"set ignorecase          " search ignoring case
set sc              " override 'ignorecase' when pattern has upper case characters
set smartcase          " Ignore case when searching lowercase
 
set showmatch          " show matching bracket
set diffopt=filler,iwhite    " ignore all whitespace and sync"
set stal=2
 
"}}}1 OPTIONS
 
" PLUGIN SETTINGS {{{1
" ================================================================================================================================================================
" Settings for :TOhtml "{{{3
let html_number_lines=1
let html_use_css=1
let use_xhtml=1
"}}}1 PLUGIN SETTINGS
 
" COLORSCHEME IF MORE THAN 2 COLORS lol {{{1
" ================================================================================================================================================================
if &t_Co > 2
 
  if &term =~ "256"
 
    set bg=dark t_Co=256 vb
    let &t_vb="<esc>[?5h<esc>[?5l"  " flash screen for visual bell
 
    if filereadable(expand("$VIMRUNTIME/colors/askapachecode.vim"))
      colorscheme askapachecode
    elseif filereadable(expand("$HOME/.vim/colors/askapachecode.vim"))
      colorscheme askapachecode
    else
      colorscheme default
    endif
 
    filetype indent plugin on
    syntax on
 
  else
    " things like cfdisk, crontab -e, visudo, vless, etc.
    set term=linux
    set t_Co=8
    syntax off
    filetype indent plugin off
 
  endif
 
endif
 
"}}}1
 
" AUTOCOMMANDS "{{{1
" ===========================================================================================================================================================================
"if !exists(":DiffOrig") | command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis | endif
 
" auto load extensions for different file types
if has('autocmd')
 
  if !exists("autocommands_loaded")
    let autocommands_loaded = 1
 
    " JUMP TO LAST POS {{{3
    " When editing a file, always jump to the last known cursor position. Don't do it when the position is invalid or when inside an event handler
    " (happens when dropping a file on gvim). Also don't do it when the mark is in the first line, that is the default position when opening a file.
    au BufReadPost * if line("'"") > 1 && line("'"") <= line("$") | exe "normal! g`"" | endif
 
    " CLEARMATCHES ON BUFWINLEAVE {{{3
    au BufWinLeave * call clearmatches()
 
    " STRIP TRAILING WHITESPACE {{{3
    autocmd BufWritePre *.cpp,*.hpp,*.i :call StripTrailingWhitespace()
 
    " AA_ZZZ LAST MOD {{{3
    autocmd BufWritePre,FileWritePre,TabLeave zzz_askapache-bash.sh ks|call LastModAAZZZ()|'s
 
    " SET VIM SETTINGS FOR AA_ZZZ SCRIPTS {{{3
    autocmd BufRead /etc/ZZZ/*.sh,.bash_profile,.bash_login,.bashrc,.bash_login_user,.bash_logout setlocal ts=4 sw=3 ft=sh foldmethod=marker tw=500 foldcolumn=7
 
    " INSERT CURRENT DATE AND TIME IN A *.SH FILE WHEN WRITING IT {{{3
    autocmd BufWritePre,FileWritePre *.*   ks|call LastMod()|'s
 
    " IMPROVE LEGIBILITY {{{3
    autocmd BufRead quickfix setlocal nobuflisted wrap number
 
    " SAVE BACKUPFILE AS BACKUPDIR/FILENAME-06-13-1331 {{{3
    autocmd BufWritePre * let &bex = strftime("-%m-%d-%H%M")
 
    " TMUX FILETYPE {{{3
    autocmd BufRead tmux.conf,.tmux.conf,.tmux*,*/tmux-sessions/* setlocal filetype=tmux foldmethod=marker
 
    " APACHE2 FILETYPE {{{3
    autocmd BufRead /opt/a*/conf/*,/etc/httpd/*.conf setlocal filetype=apache
 
    " SH FILETYPES {{{3
    autocmd BufRead *.sh,*.cron,*.bash setlocal filetype=sh
 
    " SYSLOG-NG FILETYPE {{{3
    autocmd BufRead syslog-ng.conf setlocal filetype=syslog-ng
 
    " COMMENTSTRING FOR VIM "{{{3
    au FileType vim setlocal commentstring="%s
 
    " COMMENTSTRING FOR XDEFAULTS "{{{3
    au FileType xdefaults setlocal foldmethod=marker foldlevel=2 commentstring=!%s
 
    " VIMRC {{{3
    augroup vimrc
      au BufReadPre * setlocal foldmethod=indent
      au BufWinEnter * if &fdm == 'indent' | set foldmethod=manual | endif
      au BufRead *.vim,vimrc,*.vimrc set filetype=vim ts=3 sw=3 tw=500 foldmethod=marker foldcolumn=6
    augroup END
 
    " AUTOMKVIEWS {{{3
    " Warning - this will save your settings for each file you edit and restore those settings when opened again - can fill up quick
    au BufWinLeave *.sh,*.conf,*.vim,*.c,*.txt,.htaccess,*.cgi,*.php,*.html,*.conf,vimrc mkview
    au BufWinEnter *.sh,*.conf,*.vim,*.c,*.txt,.htaccess,*.cgi,*.php,*.html,*.conf,vimrc silent loadview
    " }}}3
 
    " MAN RUNTIME - TODO REPLACE WITH TMUXES CTRL-M BINDING {{{3
    " Lets you type :Man anymanpage and it will load in vim, color-coded and searchable
    "runtime ftplugin/man.vim
 
  endif
 
endif
"}}}1
 
" MAPS "{{{1
" ===========================================================================================================================================================================
 
" FUNCTION MAPS {{{2
" ---------------------------------
" APPEND MODELINE {{{3
map <silent> <localLeader>ml :call AppendModeline()<cr>
 
" SHOW WHITESPACE {{{3
nnoremap <localLeader>ts :call ToggleShowWhitespace()<cr>
 
" SUDO A WRITE {{{3
command! W :execute ':silent w !sudo tee % > /dev/null' | :edit!
"cmap w!! %!sudo tee > /dev/null %
" :w !sudo tee > /dev/null %
 
" SET TABLINE {{{3
" My Personal Fav, inserts last-modified manually on current line when you press <f12> key
" call setline(1, printf('%sUpdated: %s by %s@%s', printf(&commentstring, ' '), strftime("%c"), expand("$LOGNAME"), hostname()))
if exists("*s:LastModNow")
  map <silent> <f12> :call LastModNow()<cr>
endif
 
" RELOAD VIMRC FILES {{{3
map <localLeader>. :mkview<cr>:unlet! AskApacheLoaded autocommands_loaded<cr>:mapclear<cr>:source /etc/vimrc<cr>:echoerr 'VIMRC RELOADED'<cr>
 
" SCROLLING MAPS {{{3
map <pageDown> :set scroll=0<cr>:set scroll^=2<cr>:set scroll-=1<cr><c-D>:set scroll=0<cr>
map <pageUp> :set scroll=0<cr>:set scroll^=2<cr>:set scroll-=1<cr><c-U>:set scroll=0<cr>
nnoremap <silent> <pageUp> <c-U><c-U>
vnoremap <silent> <pageUp> <c-U><c-U>
inoremap <silent> <pageUp> <c-><c-O><c-U><c-><c-O><c-U>
nnoremap <silent> <pageDown> <c-D><c-D>
vnoremap <silent> <pageDown> <c-D><c-D>
inoremap <silent> <pageDown> <c-><c-O><c-D><c-><c-O><c-D>
"}}}3
 
" KEY MAPS {{{2
" physically map keys to produce different key, type CTRL-V in insert mode followed by any key to see how vim sees it
" ----------------------------------------
imap <esc>[8~ <end>
map <esc>[8~ <end>
 
imap <esc>[7~ <home>
map <esc>[7~ <home>
 
" Basic Maps  {{{2
" ----------------------------------------
" TOGGLE PASTE MODE {{{3
map <localLeader>pm :set nonumber! foldcolumn=0<cr>
 
" REINDENT FILE {{{3
map <localLeader>ri G=gg<cr>
 
" CLEAR SPACES AT END OF LINE {{{3
map <localLeader>cs :%s/s+$//e<cr>
 
" Y YANKS FROM CURSOR TO $ {{{3
map Y y$
 
" DON'T USE EX MODE, USE Q FOR FORMATTING {{{3
map Q gq
map! ^H ^?
 
" NEXT SEARCH RESULT {{{3
map <silent> <localLeader>cn :cn<cr>
 
" WRAP? {{{3
map <silent> <localLeader>ww :ww
 
" ERR INSERTION {{{3
"map <silent> <localLeader>e <home>A<c-R>=printf('%s', '_err "$0 $FUNCNAME:$LINENO FAILED WITH ARGS= $*"')<cr><home><esc>
 
" CUSTOM LINES FOR CODING {{{3
map <silent> <localLeader>l1 <home>A<c-R>=printf('%s%s', printf(&commentstring, ' '), repeat('=', 160))<cr><home><esc>
map <silent> <localLeader>l2 <home>A<c-R>=printf('%s%s', printf(&commentstring, ' '), repeat('=', 80))<cr><home><esc>
map <silent> <localLeader>l3 <home>A<c-R>=printf('%s%s', printf(&commentstring, ' '), repeat('-', 40))<cr><home><esc>
map <silent> <localLeader>l4 <home>A<c-R>=printf('%s%s', printf(&commentstring, ' '), repeat('-', 20))<cr><home><esc>
 
" CHANGE DIRECTORY TO THAT OF CURRENT FILE {{{3
nmap <localLeader>cd :cd%:p:h<cr>
 
" CHANGE LOCAL DIRECTORY TO THAT OF CURRENT FILE {{{3
nmap <localLeader>lcd :lcd%:p:h<cr>
 
" TOGGLE WRAPPING {{{3
nmap <localLeader>ww :set wrap!<cr>
nmap <localLeader>wo :set wrap<cr>
 
" TABS "{{{2
" ---------------------------------
 
" CREATE A NEW TAB {{{3
map <localLeader>tc :tabnew %<cr>
 
" LAST TAB {{{3
map <localLeader>t<space> :tablast<cr>
 
" CLOSE A TAB {{{3
map <localLeader>tk :tabclose<cr>
 
" NEXT TAB {{{3
map <localLeader>tn :tabnext<cr>
 
" PREVIOUS TAB {{{3
map <localLeader>tp :tabprev<cr>
 
" FOLDS   "{{{2
" ---------------------------------
" Fold with paren begin/end matching
nmap F zf%
 
" When I use ,sf - return to syntax folding with a big foldcolumn
nmap <localLeader>sf :set foldcolumn=6 foldmethod=syntax<cr>
"}}}2
 
"}}}1
 
" HILITE "{{{1
" ===========================================================================================================================================================================
hi NonText cterm=NONE ctermfg=NONE
hi Search cterm=bold ctermbg=99 ctermfg=17
"}}}
 

Colorscheme

Here is a colorscheme file optimized for 256 colors. It will work if saved in ~/.vim/colors/askapachecode.vim or likewise in your runtimepath. Additionally, you could just paste it in the bottom of the above vimrc. The code really needs to be cleaned up, but it looks awesome.

Download - askapachecode - 256 Colors Vim Colorscheme

~/.vim/colors/askapachecode.vim

" Vim color file -- askapachecode
" Maintainer: AskApache <webmaster@askapache.com>
" Updated: Wed Feb 22 14:10:54 2012 by galileo@galileo
 
set background=dark
hi clear
 
if exists("syntax_on")|syntax reset|endif
 
let g:colors_name="askapachecode"
 
" Vim >= 7.0 specific colors
if version >= 700
 hi CursorLine ctermbg=236
 hi CursorColumn ctermbg=236
 hi MatchParen ctermfg=157 ctermbg=237 cterm=bold
 hi Pmenu ctermfg=255 ctermbg=238
 hi PmenuSel ctermfg=0 ctermbg=148
endif
 
" General colors
hi Cursor ctermbg=241
hi Normal ctermfg=253 ctermbg=232
hi NonText ctermfg=244 ctermbg=235
hi LineNr ctermfg=244 ctermbg=232
hi StatusLine ctermfg=253 ctermbg=238 cterm=italic
hi StatusLineNC ctermfg=246 ctermbg=238
hi VertSplit ctermfg=238 ctermbg=238
hi Folded ctermbg=4 ctermfg=248
hi Title ctermfg=254 cterm=bold
hi Visual ctermfg=254 ctermbg=4
hi SpecialKey ctermfg=244 ctermbg=236
 
hi pythonOperator ctermfg=103
 
hi Search cterm=NONE
 
" basic highlight groups (:help highlight-groups) {{{1
 
" text {{{2
hi Normal ctermfg=white ctermbg=black cterm=NONE
hi Folded ctermfg=lightgray ctermbg=black cterm=underline
hi LineNr ctermfg=darkgray ctermbg=NONE cterm=NONE
hi Directory ctermfg=cyan ctermbg=NONE cterm=NONE
hi NonText ctermfg=yellow ctermbg=NONE cterm=NONE
hi SpecialKey ctermfg=green ctermbg=NONE cterm=NONE
 
hi DiffAdd ctermfg=white ctermbg=darkblue cterm=NONE
hi DiffChange ctermfg=black ctermbg=darkmagenta cterm=NONE
hi DiffDelete ctermfg=black ctermbg=red cterm=bold
hi DiffText ctermfg=white ctermbg=green cterm=bold
 
" borders / separators / menus {{{2
hi FoldColumn ctermfg=lightgray ctermbg=darkgray cterm=NONE
hi SignColumn ctermfg=lightgray ctermbg=darkgray cterm=NONE
hi Pmenu ctermfg=white ctermbg=darkgray cterm=NONE
hi PmenuSel ctermfg=white ctermbg=lightblue cterm=NONE
hi PmenuSbar ctermfg=black ctermbg=black cterm=NONE
hi PmenuThumb ctermfg=gray ctermbg=gray cterm=NONE
 
hi StatusLine ctermfg=black ctermbg=white cterm=bold
hi StatusLineNC ctermfg=darkgray ctermbg=white cterm=NONE
hi WildMenu ctermfg=white ctermbg=darkblue cterm=bold
hi VertSplit ctermfg=white ctermbg=white cterm=NONE
 
if &t_Co == 256|hi TabLine ctermfg=15 ctermbg=242 term=underline|else|hi TabLine ctermfg=grey ctermbg=white term=underline|endif
"hi TabLine ctermfg=white ctermbg=white cterm=NONE
hi TabLineFill ctermfg=grey ctermbg=white cterm=NONE
"hi TabLineSel ctermfg=black ctermbg=green cterm=NONE
hi TabLineSel ctermfg=green ctermbg=black term=bold
"hi TabLineSel term=bold cterm=bold
"hi TabLineFill term=reverse cterm=reverse
"hi TabLine term=underline cterm=underline ctermfg=15 ctermbg=242
 
"hi Menu
"hi Scrollbar
"hi Tooltip
 
" cursor / dynamic / other {{{2
hi Cursor ctermfg=black ctermbg=white cterm=NONE
hi CursorIM ctermfg=black ctermbg=white cterm=reverse
hi CursorLine ctermfg=NONE ctermbg=NONE cterm=NONE
hi CursorColumn ctermfg=NONE ctermbg=NONE cterm=NONE
 
hi Visual ctermfg=white ctermbg=lightblue cterm=NONE
hi IncSearch ctermfg=white ctermbg=yellow cterm=NONE
hi Search ctermfg=white ctermbg=darkgreen cterm=NONE
 
" LISTINGS / MESSAGES {{{2
hi ModeMsg ctermfg=yellow ctermbg=NONE cterm=NONE
hi Title ctermfg=red ctermbg=NONE cterm=bold
hi Question ctermfg=green ctermbg=NONE cterm=NONE
hi MoreMsg ctermfg=green ctermbg=NONE cterm=NONE
hi ErrorMsg ctermfg=white ctermbg=red cterm=bold
hi WarningMsg ctermfg=yellow ctermbg=NONE cterm=bold
 
hi Directory term=bold ctermfg=4 "{{{
hi ErrorMsg term=standout ctermfg=15 ctermbg=1
hi IncSearch term=reverse cterm=reverse
hi Search term=NONE ctermfg=255 ctermbg=135
hi MoreMsg term=bold ctermfg=2
hi ModeMsg term=bold cterm=bold
hi LineNr term=underline ctermfg=244 ctermbg=232
hi Question term=standout ctermfg=2
hi StatusLine term=bold,reverse cterm=italic ctermfg=253 ctermbg=238
hi StatusLineNC term=reverse cterm=reverse ctermfg=246 ctermbg=238
hi VertSplit term=reverse cterm=reverse ctermfg=238 ctermbg=238
hi Title term=bold cterm=bold ctermfg=254
hi Visual term=reverse ctermfg=254 ctermbg=4
hi VisualNOS term=bold,underline cterm=bold,underline
hi WarningMsg term=standout ctermfg=1
hi WildMenu term=standout ctermfg=0 ctermbg=11
hi Folded term=standout cterm=BOLD ctermfg=7 ctermbg=27
hi FoldColumn term=NONE cterm=NONE ctermfg=75 ctermbg=16
hi IncSearch term=bold,underline cterm=bold,underline ctermfg=7 ctermbg=9
hi DiffAdd term=bold ctermbg=12
hi DiffChange term=bold ctermbg=13
hi DiffDelete term=bold ctermfg=12 ctermbg=14
hi DiffText term=reverse cterm=bold ctermbg=9
hi SpellBad term=reverse ctermbg=9
hi SpellCap term=reverse ctermbg=12
hi SpellRare term=reverse ctermbg=13
hi SpellLocal term=underline ctermbg=14
hi Pmenu ctermfg=255 ctermbg=238
hi PmenuSel ctermfg=0 ctermbg=148
hi PmenuSbar ctermbg=7
hi PmenuThumb cterm=reverse
hi TabLine term=underline cterm=underline ctermfg=0 ctermbg=7
hi TabLineSel term=bold cterm=bold
hi TabLineFill term=reverse cterm=reverse
hi CursorLine term=underline cterm=bold ctermbg=234
hi Cursor ctermbg=241
hi MatchParen term=reverse cterm=bold ctermfg=157 ctermbg=237
hi Error term=reverse ctermfg=15 ctermbg=9
 
" :hi TabLineSel|hi TabLineFill|hi TabLine
"hi TabLineSel term=bold cterm=bold
"hi TabLineFill term=reverse cterm=reverse
"hi TabLine term=underline cterm=underline ctermfg=15 ctermbg=242
hi ExtraWhitespace ctermbg=red
hi Comment term=none ctermfg=darkgrey
hi Constant term=underline ctermfg=Magenta
hi Special term=bold ctermfg=DarkMagenta
hi Identifier term=underline cterm=bold ctermfg=Cyan
hi Statement term=bold ctermfg=Yellow
hi PreProc term=underline ctermfg=LightBlue
hi Type term=underline ctermfg=LightGreen
hi Repeat term=underline ctermfg=White
hi Operator ctermfg=Red
hi Ignore ctermfg=black
hi Error term=reverse ctermbg=Red ctermfg=White
hi Todo term=standout ctermbg=Yellow ctermfg=Black
 
" COMMON GROUPS THAT LINK TO DEFAULT HIGHLIGHTING.
 
hi Function ctermfg=85
hi String ctermfg=204
hi Statement term=bold cterm=bold ctermfg=81
hi Function term=bold cterm=bold ctermfg=32
hi Number ctermfg=129
hi Conditional term=bold cterm=bold ctermfg=47
hi Special term=underline ctermfg=191
hi Normal ctermfg=7
hi PreProc ctermfg=141
" Syntax highlighting
hi Comment ctermfg=244
hi Todo ctermfg=245
hi Boolean ctermfg=148
hi String ctermfg=148
hi Identifier ctermfg=148
hi Function ctermfg=124
hi Type ctermfg=103
hi Statement ctermfg=103
hi Keyword ctermfg=81
hi Constant ctermfg=81
hi Number ctermfg=81
hi Special ctermfg=81
hi PreProc ctermfg=230
" Code-specific colors
 
" SYNTAX HIGHLIGHTING GROUPS (:HELP GROUP-NAME) {{{2
hi FoldColumn ctermbg=0 ctermfg=2
hi Folded cterm=none ctermfg=2
hi NonText cterm=NONE ctermfg=NONE
hi StatusLine ctermfg=black ctermbg=White cterm=bold
hi StatusLineNC ctermfg=White ctermbg=green cterm=NONE
hi CursorLine cterm=bold term=bold
 
" FINAL THOUGHTS "{{{2
"syn region myFold start="{" end="}" transparent fold
hi Search term=reverse ctermfg=0 ctermbg=11
hi LineNr term=underline ctermfg=244 ctermbg=232
hi MatchParen ctermfg=15 ctermbg=242
hi String ctermfg=10
hi Constant ctermfg=14
hi Identifier ctermfg=14
hi Operator ctermfg=13
hi NonText cterm=NONE ctermfg=NONE
hi Search cterm=bold ctermbg=99 ctermfg=17

Additional Resources

  1. The perfect .vimrc vim config file

Optimized Vimrc with 256 Colorscheme originally appeared on AskApache.com

HOWTO: Uninstall CPANEL over SSH

$
0
0

AskApache.com

UPDATE 12/04/2012: I am so glad I don't even have to THINK about this stuff.. just received this email from cpanel. One less thing I have to do today as a server admin. Payoff!

Important: cPanel & WHM 11.30 Security Release
 
cPanel has released new builds for all public update tiers. These updates provide targeted changes to address security concerns with the cPanel & WHM product. These builds are currently available to all customers via the standard update system.
 
cPanel has rated this update as having important security impact. Information on security ratings is available at http://go.cpanel.net/securitylevels.
 
If your deployed cPanel & WHM servers are configured to automatically update when new releases are available, then no action is required. Your systems will update automatically. If you have disabled automatic updates, then you are highly encouraged to update your cPanel & WHM installs at your earliest convenience.
 
Releases
 
Version 11.30.7.4 of cPanel & WHM addresses all known vulnerabilities. The latest public releases of cPanel & WHM for all update tiers are published at http://httpupdate.cpanel.net.
 
Security Issue Information
 
The resolved security issues were identified by various members of the development and quality assurance teams at cPanel. There is no reason to believe that these vulnerabilities are known to the public. As such, cPanel will only release limited information regarding the vulnerabilities.
 
Once sufficient time has passed to allow cPanel & WHM systems to automatically update their installed software to the new versions, cPanel will release additional information regarding the nature of the security issue. This Targeted Security Release addresses five vulnerabilities. Additional information is scheduled to be released December 6, 2012, via email.

WARNING! This is for advanced users of the shell, this is NOT a howto or tutorial. The thing is, I googled how to uninstall cpanel and for once in my life I came up empty.. And certainly the cpanel official sites themselves don't provide any instructions other than to say "Dont uninstall it, reinstall your entire operating system without it.".. they sure don't seem confident that they know exactly what their code is doing. Cpanel is great for most people, perfect for many situations, so don't get me wrong.. this is just for fun.

Why Uninstall?

Why? Because I have always built my servers, php installations, perl installs, ruby, iptables, everything from source. I read the INSTALL/README docs, I read the man pages, and I read the info pages as well. I google for configuration advice, I google for tips, and I don't need a web-based perl script messing my stuff up!

The main problems I had with cpanel, which really is a great bit of software for millions of website developers, is that it was incredibly sneaky! I used it for about 6 months and spent that entire time trying to figure out what the heck it was doing. A couple issues that I really disliked, it takes over your bind install, it takes over your apache install, it takes over your php install. And although it does let you configure some things (very few) for custom configurations and the like, I just don't need any of that. By removing the darn thing I am saving GIGS of space on my server, tons of bandwidth, and most importantly to me I am saving CPU and processing time along with RAM and IO speed.

Anything Else

Please.. I could go on for DAYS! Another reason I have wanted to be rid of cpanel is that I like my servers to be as lean and mean as possible. This means I like as few files and processes as possible. There are many benefits to this, like it's much easier for my integrity checking software and rootkit/antivirus software to run and drastically reduces the false positives. And there is that glaring security issue of constantly having cpanel run it's own software to create the WHM/Cpanel web interface, which is accessible online. I haven't researched cpanel security at all, it's possible that it never has security problems that are published, but for me, why take the chance?

Warning - Caution!

The following is just a quick reference of some of the commands I used to uninstall cpanel. This is for advanced users of the shell. If you aren't that advanced and you run a single one of these commands without fully understanding it, you will probably kill your server, probably lose everything on it permanently, probably not have a website or email for weeks.. So backup all your data FIRST. Also, if you aren't 100% sure you won't run into problems, you should contact your hosts technical support - but be prepared for some MAJOR negativity.. cpanel makes things very easy for hosts, and the last thing tech support wants is to fix a server broken by someone who doesn't know what they are doing.

Last Warning!

Unless you understand what theses commands do and the purpose they serve, do not try any of this. These are not the exact commands I used verbatim, they are also not in order. I only put them up here because I was so amazed that google didn't have any uninstall cpanel intructions. Hopefully it's not a conspiracy that will get my site taken down.. ;)

That said and out of the way, it really only took me about 10 minutes to uninstall cpanel completely. But keep in mind I have been closely monitoring and debugging cpanel for 6 months, so I knew what I was doing. And finally, I do apologize for not having better instructions.. but hey, if you don't get this then you have no business trying to figure out how to uninstall cpanel! It's great software and shouldn't be removed unless you are fully capable of managing email/dns/www/ftp and any/all other servers and services on your machine by hand.

Do This First

I have a few drafts I'm working on at the moment with specifics, but for now you will have to figure it out with google. Basically you want to make sure you don't totally knock your machine offline without being able to reconnect. What I do is compile a static version of openssh and a few other security-type shell tools, and configure this binary sshd to run by using inittab, which is the file run by init (pid 1) and makes sure if it dies it is restarted. Here is my /etc/inittab to run the static sshd binary:

hh:12345:respawn:/failover/os/sbin/aassh -D -q -u0 -f /failover/os/etc/aassh

Another trick is to keep a detached screen logged in to root. That way if you mess up your sudoers or securetty or pam or whatever, you can just reattach and fix it.

Finally, you may want to setup your syslog to start earlier than usual, and set up more than normal verbosity. ( I take it to the max ). Then you should setup a 2nd server or machine somewhere to act as a syslog server. Lastly, configure your web server syslog to copy all messages to the remote syslog you set up. I use a reverse ssh tunnel to encrypt the syslog packets, but when I do something serious like reboot after uninstalling cpanel, I prepare for it by adding additional networking routes on my machine to make sure I will get some logs even if sshd cant start or even if my network addresses aren't brought up correctly.

If that sounds easy to you, please continue. If you are saying: Wha??? Continue in read-only mode.

Also, you can't just uninstall cpanel, I have replaced a lot of cpanel already, like building my own bind, apache, php, syslog and making sure they work and aren't being tampered with by cpanel. Basically cpanel runs everything on your server in most cases, so you should prepare by creating your own static software to replace cpanel, and make sure it works.

Find files Accessing /var/cpanel

More than likely these will need to be killed.

lsof +w -Rg -nP +c15 -x f +D /var/cpanel
lsof +w -Rg -nP +c15 -x f +D /usr/local/cpanel

Killing cpanel

Just an example, your machine may have a lot more than these, I have been slowly taking control of my machine back from cpanel for 6 months, so it was easier for me.

for P in tailwatchd queueprocd cpanellogd exim; do pkill -9 $P; done

Commands and Shortcuts

alias NF='nice find $PWD -mount -depth ! -type d'
alias NFF='nice find $PWD -mount -depth ! -type d | xargs -IF87 file F87'
alias NA='nice find $PWD -mount -depth'
alias NAF='nice find $PWD -mount -depth | xargs -IF87 file F87'

Watch out for crontab

An example of the sneakiness (from my POV, from most it's called builtin robustness) that cpanel does is automagically adding crontab entries that make it behave similarly to a self-propagating virus. If you don't disable the cronjobs and kill the right processes within a short period of time, be prepared for a magic resurrection.

Here's my awesome crontab information function, you will need to check every file, it lists the default crons on my box, and every users crontab, but it can't account for other cron software like at and other crons.

function askapache_crontab()
{
  local GG i;
  for i in `getent passwd|cut -d ":" -f1`;
  do
    GG=$(sudo crontab -u $i -l 2>$N6 | tr -s 'n�00' | sed '/^#/d');
    [[ ${#GG} -gt 3 ]] && sleep 1 && echo -e "$i nn${GG}"
  done;
   sleep 4;
   ls -aLls1ch --color=always /etc/cron.{hourly,daily,weekly,monthly,d} | sed '/^total/d; / drwxr-xr-x/d';
}
grep -ir /var/spool cpan
#6 3 * * * /scripts/upcp
#0 1 * * * /scripts/cpbackup
#0 2 * * * /scripts/mailman_chown_archives
#35 * * * * /usr/bin/test -x /usr/local/cpanel/bin/tail-check && /usr/local/cpanel/bin/tail-check
#11,26,41,56 * * * * /usr/local/cpanel/whostmgr/bin/dnsqueue > /dev/null 2>&1
#30 */4 * * * /usr/bin/test -x /scripts/update_db_cache && /scripts/update_db_cache
#45 */8 * * * /usr/bin/test -x /usr/local/cpanel/bin/optimizefs && /usr/local/cpanel/bin/optimizefs
#*/5 * * * * /usr/local/cpanel/bin/dcpumon >/dev/null 2>&1
#25 1 * * * /usr/local/cpanel/whostmgr/docroot/cgi/cpaddons_report.pl --notify

Delete Crontabs

sudo crontab -u mailman -r

Find INIT scripts with cpanel

This is the main startup script: /usr/local/cpanel/etc/init/startup

I had no idea ruby-on-rails was being controlled by cpanel.. sneaky bugger. You can tell by all of these advanced unix commands just how difficult it would be to uninstall cpanel, its totally like the Alien!

(1:3744)# find . ! -type d -print0|xargs -0 -I'F87' grep -Hi "cpan|tailwat|chkser" F87
./fastmail:# Author:       cPanel, Inc. <nick@cpanel.net>
./httpd:        HTTPD=/usr/local/cpanel/bin/chroothttpd
./cpanel:# cpanel8       Start Cpanel Services
./cpanel:# Author:       cPanel, Inc. <nick@cpanel.net>
./cpanel:# description: This is the cpanel webserver and chat.
./cpanel:# processname: cpaneld
./cpanel:# pidfile: /var/run/cpanel.pid
./cpanel:[ -f /usr/local/cpanel/etc/init/startup ] || exit 0
./cpanel:       if [ -f "/var/cpanel/smtpgidonlytweak" ]; then
./cpanel:       echo -n "Starting cPanel services: "
./cpanel:       daemon /usr/local/cpanel/etc/init/startcpsrvd
./cpanel:       echo -n "Starting cPanel brute force detector services: "
./cpanel:       daemon /usr/local/cpanel/etc/init/startcphulkd
./cpanel:    echo -n "Starting cPanel dav services: "
./cpanel:       daemon /usr/local/cpanel/etc/init/startcpdavd
./cpanel:               daemon /usr/local/cpanel/etc/init/startcppop
./cpanel:       echo -n "Starting cPanel Chat services: "
./cpanel:               daemon /usr/local/cpanel/entropychat/entropychat
./cpanel:               daemon /usr/local/cpanel/bin/startmelange
./cpanel:                       /usr/local/cpanel/bin/startinterchange
./cpanel:       echo -n "Starting cPanel ssl services: "
./cpanel:       daemon /usr/local/cpanel/startstunnel
./cpanel:    echo -n "Starting cPanel Queue services: "
./cpanel:       daemon /usr/local/cpanel/etc/init/startqueueprocd
./cpanel:    echo -n "Starting tailwatchd: "
./cpanel:    daemon /usr/local/cpanel/libexec/tailwatchd --start
./cpanel:       echo -n "Starting cPanel Log services: "
./cpanel:       daemon /usr/local/cpanel/cpanellogd
./cpanel:    action "Starting mailman services: " /usr/local/cpanel/etc/init/startmailman
./cpanel:    action "Stopping tailwatchd: " /usr/local/cpanel/libexec/tailwatchd --stop
./cpanel:    action "Stopping cPanel services: " /usr/local/cpanel/etc/init/stopcpsrvd
./cpanel:       action "Stopping cPanel dav services: " /usr/local/cpanel/etc/init/stopcpdavd
./cpanel:       action "Stopping cPanel queue services: " /usr/local/cpanel/etc/init/stopqueueprocd
./cpanel:       action "Stopping cPanel brute force detector services: " /usr/local/cpanel/etc/init/stopcphulkd
./cpanel:               action "Stopping pop3 services: " /usr/local/cpanel/etc/init/stopcppop
./cpanel:       echo -n "Stopping cPanel log services: "
./cpanel:       killproc cpanellogd
./cpanel:       echo -n "Stopping cPanel Chat services: "
./cpanel:       action "Stopping cPanel ssl services: " /usr/local/cpanel/etc/init/stopstunnel
./cpanel:       action "Stopping mailman services: " /usr/local/cpanel/etc/init/stopmailman
./cpanel:       if [ -e "/usr/local/cpanel/3rdparty/mailman/bin/mailmanctl" ]; then
./exim:if [ -e "/etc/chkserv.d" ]; then
./exim:        for file in `ls /etc/chkserv.d`
./exim:            if [ ! -e "/usr/local/cpanel/libexec/tailwatchd" ]; then
./exim:    if [ -x "/usr/local/cpanel/etc/init/startspamd" ]; then
./exim:        /usr/local/cpanel/etc/init/startspamd
./exim:        if [ ! -e "/usr/local/cpanel/libexec/tailwatchd" ]; then
./ror:  /usr/local/cpanel/bin/rormgr --startboot
./ror:  /usr/local/cpanel/bin/rormgr --stopall
./ror:  /usr/local/cpanel/bin/rormgr --stopall
./ror:  /usr/local/cpanel/bin/rormgr --startboot
./ror:  /usr/local/cpanel/bin/rormgr --statusall
./securetmp:# Author:       cPanel, Inc. <copyright@cpanel.net>

Turn off cpanel services

You should remove the below delete command and start by just disabling the inits by turning them off. Then reboot. Then delete. If your machine won't reboot, I told you so, Cpanel told you so, and likely your host told you so.

for S in cpanel ror securetmp fastmail exim; do R=$(command chkconfig --level 123456 $S off ||echo); R=$(command chkconfig --del $S ||echo); done

HTTPD

If you are running chrooted httpd then you'll need to make sure you don't delete your entire webserver on accident. Here's a relevant part from the /etc/init.d/httpd script.

# the path to your httpd binary, including options if necessary
if [ -e "/etc/chroothttpd" ]; then
        HTTPD=/usr/local/cpanel/bin/chroothttpd
else
        HTTPD=/usr/local/apache/bin/httpd
fi

Finding files owned by cpanel

Some super cool bash commands in this post.. let's start with one to find all the files and folders on your machine owned by cpanel. Check your /etc/passwd file for your machines specific usernames and groups. This command saves all the filenames to ~/cpanel-files-backup.txt, which is used by tar next to create a backup of all of them.

{ find / -mount -depth -maxdepth 150 ( -group cpanel -o   -group cpanel-phpmyadmin -o -group cpanel-phppgadmin   -o -group cpanelphpmyadmin   -o -group cpanelphppgadmin   -o -group cpanelhorde   -o -group cpanelroundcube ) -print; find / -mount -depth -maxdepth 150 ( -user cpanel -o   -user cpanel-phpmyadmin -o -user cpanel-phppgadmin   -o -user cpanelphpmyadmin   -o -user cpanelphppgadmin   -o -user cpanelhorde   -o -user cpanelroundcube ) -print; } > ~/cpanel-files-backup.txt

Here's another way to search directories.

 grep --color=always -Hir cpanel /var

Create the Backup

Note that you must have the latest version of tar for this exact command, also you should backup /var/cpanel and /usr/local/cpanel and /etc and heck the whole machine why dontcha!

tar -T ~/cpanel-files-backup.txt -cvz --checkpoint=1000 --checkpoint-action="ttyout=rHit %s checkpoint #%u" -f /cpanel-files-backup.tgz --totals

Remove Files

Once you do this your upstream without a paddle, you better make sure you know what you're doing with this. This removes all those files.

cat ~/cpanel-files-backup.txt | xargs -I'F87' rm -vfr F87

Additionally you will want to remove /usr/local/cpanel and /var/cpanel - What I always do when running as root is alias my rm command to instead simply move the files to a .trash folder. That way if something goes bork you have a better chance at fixing it.

Find Group-Owned Files

find / -mount -depth -maxdepth 150 
(  -group cpanel -o 
  -group cpanel-phpmyadmin 
  -o -group cpanel-phppgadmin 
  -o -group cpanelphpmyadmin 
  -o -group cpanelphppgadmin 
  -o -group mailman 
  -o -group cpanelhorde 
  -o -group cpanelroundcube 
) -fprintf /root/cpanel-group-files.log '%#8k %#5m %11M %#10u:%-10g %-5U:%-5G %p %f %Y %Fn'

Find User-Owned Files

find / -mount -depth -maxdepth 150 (
  -user cpanel 
  -o -user cpanel-phpmyadmin 
  -o -user cpanel-phppgadmin 
  -o -user cpanelphpmyadmin 
  -o -user cpanelphppgadmin 
  -o -user mailman 
  -o -user cpanelhorde 
  -o -user cpanelroundcube
) -fprintf /root/cpanel-users-files.log '%#8k %#5m %11M %#10u:%-10g %-5U:%-5G %p %f %Y %Fn'
       4  0755  drwxr-xr-x     cpanel:cpanel     32002:32004 /var/cpanel/userhomes/cpanel cpanel d reiserfs
       4  0700  drwx------ cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin/tmp tmp d reiserfs
       4  0644  -rw-r--r-- cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin/.cpanel/caches/featurelists/default.cache default.cache f reiserfs
       4  0700  drwx------ cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin/.cpanel/caches/featurelists featurelists d reiserfs
       4  0700  drwx------ cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin/.cpanel/caches caches d reiserfs
       4  0700  drwx------ cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin/.cpanel .cpanel d reiserfs
       4  0750  drwxr-x--- cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin/mail mail d reiserfs
       4  0711  drwx--x--x cpanel-phpmyadmin:cpanel-phpmyadmin 32005:32007 /var/cpanel/userhomes/cpanel-phpmyadmin cpanel-phpmyadmin d reiserfs
       4  0700  drwx------ cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin/sessions sessions d reiserfs
       4  0644  -rw-r--r-- cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin/.cpanel/caches/featurelists/default.cache default.cache f reiserfs
       4  0700  drwx------ cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin/.cpanel/caches/featurelists featurelists d reiserfs
       4  0700  drwx------ cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin/.cpanel/caches caches d reiserfs
       4  0700  drwx------ cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin/.cpanel .cpanel d reiserfs
       4  0750  drwxr-x--- cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin/mail mail d reiserfs
       4  0711  drwx--x--x cpanelphppgadmin:cpanelphppgadmin 32009:32011 /var/cpanel/userhomes/cpanelphppgadmin cpanelphppgadmin d reiserfs
       4  0750  drwxr-x--- cpanelroundcube:cpanelroundcube 514  :514   /var/cpanel/userhomes/cpanelroundcube/mail mail d reiserfs
       4  0700  drwx------ cpanelroundcube:cpanelroundcube 514  :514   /var/cpanel/userhomes/cpanelroundcube/sessions sessions d reiserfs
       4  0711  drwx--x--x cpanelroundcube:cpanelroundcube 514  :514   /var/cpanel/userhomes/cpanelroundcube cpanelroundcube d reiserfs
       4  0644  -rw-r--r--     cpanel:cpanel     32002:32004 /var/cpanel/.cpanel/caches/featurelists/default.cache default.cache f reiserfs
       4  0700  drwx------     cpanel:cpanel     32002:32004 /var/cpanel/.cpanel/caches/featurelists featurelists d reiserfs
       4  0700  drwx------     cpanel:cpanel     32002:32004 /var/cpanel/.cpanel/caches caches d reiserfs
       4  0700  drwx------     cpanel:cpanel     32002:32004 /var/cpanel/.cpanel .cpanel d reiserfs
       4  0700  drwx------ cpanelroundcube:cpanelroundcube 514  :514   /var/cpanel/roundcube/tmp tmp d reiserfs
       4  0700  drwx------ cpanelroundcube:cpanelroundcube 514  :514   /var/cpanel/roundcube/log log d reiserfs

Find Permissions

cat ~/cpanel-group-files.log ~/cpanel-users-files.log |tr -s '�00 t'|cut -d' ' -f3|sort -u

Find files tailwatchd

(1:3732)# $NICE find ${1:-`pwd`} -mount -name '*tailwatch*'
/usr/local/cpanel/libexec/tailwatchd
/usr/local/cpanel/libexec/tailwatch
/usr/local/cpanel/libexec/tailwatch/tailwatchd
/usr/local/cpanel/etc/init/scripts/freebsd/tailwatchd.sh
/usr/local/cpanel/etc/init/scripts/trustix/tailwatchd
/usr/local/cpanel/etc/init/scripts/centos/tailwatchd
/usr/local/cpanel/etc/init/scripts/suse/tailwatchd
/usr/local/cpanel/etc/init/scripts/caos/tailwatchd
/usr/local/cpanel/etc/init/scripts/whitebox/tailwatchd
/usr/local/cpanel/etc/init/scripts/mandrake/tailwatchd
/usr/local/cpanel/etc/init/scripts/debian/tailwatchd
/usr/local/cpanel/etc/init/scripts/redhat/tailwatchd
/usr/local/cpanel/etc/init/scripts/fedora/tailwatchd
/usr/local/cpanel/etc/init/stoptailwatchd
/usr/local/cpanel/etc/init/starttailwatchd
/usr/local/cpanel/bin/tailwatchd
/usr/local/cpanel/logs/tailwatchd_log
/var/log/cpanel/tailwatchd_log
/var/cpanel/log_rotation/cp_tailwatchd_log.cpanellogd
/var/cpanel/tailwatch.positions
/var/run/tailwatchd.pid
/etc/chkserv.d/tailwatchd
/scripts/restartsrv_tailwatchd

Delete cpanel Users/Groups

for U in cpanel-phpmyadmin cpanel-phppgadmin cpanelphpmyadmin cpanelphppgadmin cpanelhorde cpanelroundcube machbuild; do userdel -fr $U; groupdel $U; done

Check for broken symlinks

find / -mount -depth -type l -print0 |xargs -0 -P0 -I'F87' file -s 'F87' | sed -n '/: broken symbolic link to/p'

Especially check /etc

$ find /etc -mount -depth -type l -print0 |xargs -0 -P0 -I'F87' file -s 'F87' | sed -n '/: broken symbolic link to/p'
/etc/ftpd-rsa.pem                   broken symbolic link to `/var/cpanel/ssl/ftp/ftpd-rsa.pem'
/etc/rc.d/rc1.d/K10chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc1.d/K30antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc1.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/rc.d/rc3.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/rc.d/rc3.d/S80chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc3.d/S80antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc6.d/K10chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc6.d/K30antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc6.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/rc.d/rc5.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/rc.d/rc5.d/S80chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc5.d/S80antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc2.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/rc.d/rc2.d/S80chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc2.d/S80antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc4.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/rc.d/rc4.d/S80chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc4.d/S80antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc0.d/K10chkservd         broken symbolic link to `../init.d/chkservd'
/etc/rc.d/rc0.d/K30antirelayd       broken symbolic link to `../init.d/antirelayd'
/etc/rc.d/rc0.d/K80dcc              broken symbolic link to `../init.d/dcc'
/etc/authlib/authProg               broken symbolic link to `/usr/local/cpanel/bin/courier-auth'

And delete if you are sure

find /etc -mount -depth -type l -print0 |xargs -0 -P0 -I'F87' file -s 'F87' | sed -n '/: broken symbolic link to/p' |cut -d' ' -f1|xargs -I'F87' rm -rvf 'F87'

Reinstall CSF

The only thing I actually used that came with cpanel is the CSF/LFD Firewall package, which is a fantastic piece of software. I had to reinstall this, and to get it working without cpanel add the following line to the csf.conf

GENERIC = "1"

Thats It

Now once you've cleaned up everything, you should try everything conceivable to get an error before rebooting. Like you should start and stop every service in /etc/init.d/, you should use telinit to check various runlevels (which keeps your sshd connection still live). Go all out, should take at least a full hour.

Another thing I like to do is rebuild alot of my source-built software again in case anything got messed up. I upgrade perl from cpanels 5.8.8 to 5.10, which is pretty thorough, and you know, reinstall anything else I think I might need. One of the benefits of compiling your own software is all I have to do is cd to the source directory and type make -B && ( { make test || make check || make checks || make tests; } || echo ) && sudo make install and that's it. The tests/checks are optional of course.

If anyone actually ever reads this and does it, please share your advice here.. everybody knows we need it! Good Luck

HOWTO: Uninstall CPANEL over SSH originally appeared on AskApache.com


Adding a PayPal Donate Now to Site

$
0
0

AskApache.com

Adding a PayPal Donate Now to Site
Adding a PayPal "Donate Now" button to your site is really easy. All you need is a paypal account, once logged in you can use the helpful wizard that walks you through the very quick and easy process.

The Wizard

To create your donate now button (it's actually a form), do this to get to the automated wizard.

  1. Login to PayPal.
  2. Goto the Merchant Services Tab
  3. Click the Create payment buttons for your website image
  4. Now follow through the wizard

Choose payment type and button details

Adding a PayPal Donate Now to Site

Customize advanced features

Once you are finished hit the Create Button button to get the HTML code of the button, which you then paste into your site.

Adding a PayPal Donate Now to Site

Get the HTML

Now just grab the HTML for pasting into your site.

Adding a PayPal Donate Now to Site

Finally, Clean up the HTML

For some reason the wizard gives you old HTML instead of XHTML, so you will need to convert it to XHTML by ending with a /> instead of just >, and then wrapping all the elements within the form inside a div.

HTML Before

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="LF9N4MHDAAGCY">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

XHTML After

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<div>
<input type="hidden" name="cmd" value="_s-xclick" />
<input type="hidden" name="hosted_button_id" value="LF9N4MHDAAGCY" />
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" />
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" />
</div>
</form>

More Info

Adding a PayPal Donate Now to Site originally appeared on AskApache.com

AskApache Debug Viewer Plugin for WordPress

$
0
0

AskApache.com

Screen Shots | PHP Debug Functions

AskApache Debug Viewer Plugin for WordPressThe story behind this plugin is sorta wack, but in a good way :). While doing tons of security research on permissions, authorization, access, etc.. for the Password Protection plugin (still being worked on), I needed to have unheard of debugging capabilities while working on the plugin on the various websites, webhosts, and test servers that I use to test in different environments. So I hacked together a bunch of php code that helped me debug, actually I pretty much went overkill and tried to get as much debugging info as programmatically possible, and it ended up being so much code that I took it out of my Password Protection code and made it its own plugin.

I've been using it for several months now while working on a plugin or diagnosing some issue, and decided that I'd share it with everyone. Hopefully it will help other plugin authors and php programmers in general to start writing more robust and error-proof code, which would in turn help me! To help those not using WordPress, I've included most of the debugging functions below, but you'll need the AskApacheDebug class for them to work. Hope you find it useful! I do. Download AskApache Debug Viewer


Screenshots and Debug Output

The plugin outputs the debugging info in the admin footer by hooking into the 'in_admin_footer' action.
AskApache Debug Viewer Plugin for WordPress

AskApache Debug Viewer Plugin for WordPressAskApache Debug Viewer Plugin for WordPress

AskApache Debug Viewer Plugin for WordPressAskApache Debug Viewer Plugin for WordPress

AskApache Debug Viewer Plugin for WordPressAskApache Debug Viewer Plugin for WordPress

AskApache Debug Viewer Plugin for WordPressAskApache Debug Viewer Plugin for WordPress

PHP Debugging Functions

Ok so for those interested more in the php flavor, here are a few of the functions that produce the debugging output. I'll start with my customized _stat function, which took a lot of research to write, but you can read that story at Chmod, Umask, Stat, Fileperms, and File Permissions.

function _stat($fl)
{
  static $ftypes = false;
  if (!$ftypes)
  {
    $this->logg(__FUNCTION__ . ':' . __LINE__);
    $ftypes = array(S_IFSOCK => 'ssocket', S_IFLNK => 'llink', S_IFREG => '-file', S_IFBLK => 'bblock', S_IFDIR => 'ddir', S_IFCHR => 'cchar', S_IFIFO => 'pfifo');
  }
 
  $s = $ss = array();
  if (($ss = stat($fl)) === false) return $this->logg(__FUNCTION__ . ':' . __LINE__ . " Couldnt stat {$fl}", 0);
  $p = $ss['mode'];
  $t = decoct($p & S_IFMT);
  $q = octdec($t);
  $type = (array_key_exists($q, $ftypes)) ? substr($ftypes[$q], 0, 1) : '?';
$s = array(
'filename' => $fl,
 
'human' => ($type .
(($p & S_IRUSR) ? 'r' : '-') . (($p & S_IWUSR) ? 'w' : '-') . (($p & S_ISUID) ? (($p & S_IXUSR) ? 's' : 'S') : (($p & S_IXUSR) ? 'x' : '-')) .
(($p & S_IRGRP) ? 'r' : '-') . (($p & S_IWGRP) ? 'w' : '-') . (($p & S_ISGID) ? (($p & S_IXGRP) ? 's' : 'S') : (($p & S_IXGRP) ? 'x' : '-')) .
(($p & S_IROTH) ? 'r' : '-') . (($p & S_IWOTH) ? 'w' : '-') . (($p & S_ISVTX) ? (($p & S_IXOTH) ? 't' : 'T') : (($p & S_IXOTH) ? 'x' : '-'))),
'octal' => sprintf("%o", ($ss['mode'] & 007777)),
'hex' => sprintf("0x%x", $ss['mode']),
'decimal' => sprintf("%d", $ss['mode']),
'binary' => sprintf("%b", $ss['mode']),
'base_convert' => base_convert($ss['mode'],10,8),
'fileperms' => fileperms($fl),
'mode' => $p,
 
'type_octal' => sprintf("%07o", $q),  'fileuid' => $ss['uid'],
 
'type' => $type,
'filegid' => $ss['gid'],
'owner_name' => $this->get_posix_info('user', $ss['uid'],
'name'),
'group_name' => $this->get_posix_info('group', $ss['gid'],
'name'),
'dirname' => dirname($fl),
'is_file' => is_file($fl) ? 1 : 0,
'is_dir' => is_dir($fl) ? 1 : 0,
'is_link' => is_link($fl) ? 1 : 0,
'is_readable' => is_readable($fl) ? 1 : 0,
'is_writable' =>
is_writable($fl) ? 1 : 0,'device' => $ss['dev'],
'device_number' => $ss['rdev'],
'inode' => $ss['ino'],
'link_count' => $ss['nlink'],
'size' => $ss['size'],
'blocks' => $ss['blocks'],
'block_size' => $ss['blksize'],
'accessed' => date('Y M D H:i:s', $ss['atime']),
'modified' => date('Y M D H:i:s', $ss['mtime']),
'created' => date('Y M D H:i:s', $ss['ctime']),
'mtime' => $ss['mtime'], 'atime' => $ss['atime'],
'ctime' => $ss['ctime'], );
  if (is_link($fl)) $s['link_to'] = readlink($fl);
  if (realpath($fl) != $fl) $s['real_filename'] = realpath($fl);
 
  return $s;
}

get_debug_functions

These are various security and user related information. Nice.

function get_debug_functions($vb=false)
{
  $functions=$oa=array();
  $functions = array(
'PHP script Process ID' => 'getmypid',
'PHP script owners UID' => 'getmyuid',
'php_sapi_name' => 'php_sapi_name',
'PHP Uname' => 'php_uname',
'Zend Version' => 'zend_version',
'PHP INI Loaded' => 'php_ini_loaded_file',
'Current Working Directory' => 'getcwd',
'Last Mod' => 'getlastmod',
'Script Inode' => 'getmyinode',
'Script GID' => 'getmygid',
'Script Owner' => 'get_current_user',
'Get Rusage' => 'getrusage',
'Error Reporting' => 'error_reporting',
'Path name of controlling terminal' => 'posix_ctermid',
'Error number set by the last posix function that failed' => 'posix_get_last_error',
'Pathname of current directory' => 'posix_getcwd',
'posix_getpid' => 'posix_getpid',
'posix_uname' => 'posix_uname',
'posix_times' =>'posix_times',
'posix_errno' => 'posix_errno',
'Effective group ID of the current process' => 'posix_getegid',
'Effective user ID of the current process' => 'posix_geteuid',
'Real group ID of the current process' => 'posix_getgid',
'Group set of the current process' => 'posix_getgroups',
'Login name' => 'posix_getlogin',
'Current process group identifier' => 'posix_getpgrp',
'Current process identifier' => 'posix_getpid',
'Parent process identifier' => 'posix_getppid',
'System Resource limits' => 'posix_getrlimit',
'Return the real user ID of the current process' => 'posix_getuid',
'Magic Quotes GPC' => 'get_magic_quotes_gpc',
'Magic Quotes Runtime' => 'get_magic_quotes_runtime', );
 
  foreach ($functions as $title => $func_name) {
    $val = '';
    if ( ( $this->checkfunction($func_name) && ($val = $func_name()) !== false) ){
      if (empty($val)) $val=$func_name;
      $oa[$title] = $val;
    }
  }
 
  return $oa;
}

get_debug_permissions

This is a function designed to get as much information about file/user/group permissions as possible.

function get_debug_permissions($vb=false)
{
  $oa=array();
 
  $user_info = $this->get_posix_info('user');
  $group_info = $this->get_posix_info('group');
 
$functions = array(
'Real Group ID' => posix_getgid(),
'Effective Group ID' => posix_getegid(),
'Parent Process ID' => posix_getppid(),
'Parent Process Group ID' => posix_getpgid(posix_getppid()),
'Real Process ID' => posix_getpid(),
'Real Process Group ID' => posix_getpgid(posix_getpid()),
'Process Effective User ID' => posix_geteuid(),
'Process Owner Username' => $user_info['name'],
'File Owner Username' => get_current_user(),
'User Info' => print_r($user_info, 1),
'Group Info' => print_r($group_info, 1),
'RealPath'  => realpath(__FILE__),
'SAPI Name' => (function_exists('php_sapi_name')) ? print_r(php_sapi_name(), 1) : '',
'Posix Process Owner' => print_r(posix_getpwuid(posix_geteuid()), 1),
'Scanned Ini' => (function_exists('php_ini_scanned_files')) ? str_replace("n", "", php_ini_scanned_files()) : '',
'PHP.ini Path' => get_cfg_var('cfg_file_path'),
'Sendmail Path' => get_cfg_var('sendmail_path'),
'Info about a group by group id' => posix_getgrgid(posix_getegid()),
'Process group id for Current process' => posix_getpgid(posix_getpid()),
'Process group id for Parent process' => posix_getpgid(posix_getppid()),
'Process group id of the session leader.' => posix_getsid(posix_getpid()),
'Info about a user by username' => posix_getpwnam(get_current_user()),
'Info about a user by user id' => posix_getpwuid(posix_geteuid()),
'Apache Version' => (function_exists('apache_get_version')) ? print_r(apache_get_version(), 1) : '',
'Apache Modules' => (function_exists('apache_get_modules')) ? print_r(apache_get_modules(), 1) : '',
'PHP_LOGO_GUI' => php_logo_guid(),
'ZEND_LOGO_GUI' => zend_logo_guid()
);
 
  foreach ($functions as $title => $v) $oa[$title] = $v;
 
  return $oa;
}

get_debug_defined

This gets all the defined constants, if verbose it gets more and gets the values for each.

function get_debug_defined($vb=false)
{
  $oa=array();
  foreach ((array)@get_defined_constants() as $k => $v){if (!$vb && in_array($k, array('ABSPATH', 'WP_ADMIN'))) $vb = true;  if($vb)$oa[$k]=$v;}
 
  foreach (
  array('WP_TEMP_DIR', 'WP_SITEURL', 'WP_HOME', 'ABSPATH', 'WP_CONTENT_URL',
  'WP_CONTENT_DIR', 'WP_PLUGIN_DIR', 'WP_PLUGIN_URL', 'WP_LANG_DIR', 'TEMPLATEPATH',
  'STYLESHEETPATH', 'WPINC', 'COOKIEPATH', 'SITECOOKIEPATH', 'ADMIN_COOKIE_PATH',
  'PLUGINS_COOKIE_PATH', 'PHP_SAPI', 'PHP_OS', 'PHP_VERSION'
  ) as $def) if (defined($def) && $val = constant($def) && !empty($val)) $oa[$def] = $val;
 
  return $oa;
}

get_debug_inis

This function gets the values of your php ini, if verbose it gets them all and shows the currently used value instead of both the global and local.

function get_debug_inis($vb=false)
{
  $oa=array();
 
  foreach (array('Error Log' => 'error_log',
'Session Data Path' => 'session.save_path',
'Upload Tmp Dir' => 'upload_tm_p_dir',
'Include Path' => 'include_path',
'Memory Limit' => 'memory_limit',
'Max Execution Time' => 'max_execution_time',
'Display Errors' => 'display_errors',
'Allow url fopen' => 'allow_url_fopen',
'Disabled Functions' => 'disable_functions',
'Safe Mode' => 'safe_mode',
'Open Basedir' => 'open_basedir',
'File Uploads' => 'file_uploads',
'Max Upload Filesize' => 'upload_max_filesize',
'Max POST Size' => 'post_max_size',
'Open Basedir' => 'open_basedir') as $title => $ini_name) if (($val = '' && $val = strval(ini_get($ini_name))) !== false && !empty($val)) $oa[$title] = $val;
 
  if($vb!==false){
    foreach ((array)@ini_get_all() as $k => $v) $oa[$k] = (($v['global_value'] == $v['local_value']) ? $v['global_value'] : $v);
  }
  return $oa;
}

get_debug_phpinfo

I'm particularly proud of this function because the preg_replace was tough and the result is a perfect array of values returned by the phpinfo command.

function get_debug_phpinfo()
{
  $oa=array();
  ob_start();
  phpinfo(-1);
  $oa = preg_replace(array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms', '#<h1>Configuration</h1>#', "#r?n#", "#</(h1|h2|h3|tr)>#", '# +<#', "#[ t]+#", '# #', '#  +#', '# class=".*?"#', '%'%', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>' . '<h1>PHP Version (.*?)</h1>(?:n+?)</td></tr>#',
    '#<h1><a href="(?:.*?)?=(.*?)">PHP Credits</a></h1>#', '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#', "#  +#", '#<tr>#', '#</tr>#'), array('$1', '', '', '', '</$1>' . "n", '<', ' ', ' ', ' ', '', ' ', '<h2>PHP Configuration</h2>' . "n" . '<tr><td>PHP Version</td><td>$2</td></tr>' . "n" . '<tr><td>PHP Egg</td><td>$1</td></tr>',
    '<tr><td>PHP Credits Egg</td><td>$1</td></tr>', '<tr><td>Zend Engine</td><td>$2</td></tr>' . "n" . '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'), ob_get_clean());
  $sections = explode('<h2>', strip_tags($oa, '<h2><th><td>'));
  unset($sections[0]);
  $oa = array();
  foreach ($sections as $section)
  {
    $n = substr($section, 0, strpos($section, '</h2>'));
    preg_match_all('#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#', $section, $askapache, PREG_SET_ORDER);
    foreach ($askapache as $m) $oa[$n][$m[1]] = (!isset($m[3]) || $m[2] == $m[3]) ? $m[2] : array_slice($m, 2);
  }
  return $oa;
}

get_debug_included

Gets a list of all the files included by php, if verbose it also super-stats them.

function get_debug_included($vb=false)
{
  $oa=array();
  foreach((array)@get_included_files() as $k=>$v) $oa[$v]=($vb===false) ? '' : $this->_stat($v);
  return $oa;
}

get_debug_classes

Gets a list of predefined classes declared in your php instance, if verbose it gets EVERY class and also gets the methods for each.

function get_debug_classes($vb=false)
{
  $classes=$oa=array();
  $classes= ($vb!==false) ? (array)@get_declared_classes() : array('WP','WP_Error','Walker','WP_Ajax_Response','wpdb','WP_Object_Cache','WP_Query','WP_Rewrite','WP_Locale');
  foreach ($classes as $k)  $oa[$k] = @get_class_methods($k);
 
  return $oa;
}

get_debug_globals

This function tries to get the values of every known (past and present) global variable in php.

function get_debug_globals($vb=false)
{
  $oa=array();
 
  $globs =
  array(
  'GET'     => isset( $_GET )?$_GET:'',
  'POST'    => isset( $_POST )?$_POST:'',
  'COOKIE'  => isset( $_COOKIE )?$_COOKIE:'',
  'SESSION'   => isset( $_SESSION )?$_SESSION:'',
  'ENV'     => isset( $_ENV )?$_ENV:'',
  'FILES'     => isset( $_FILES )?$_FILES:'',
  'SERVER'  => isset( $_SERVER )?$_SERVER:'',
  'SERVER'  => isset( $_SERVER )?$_SERVER:'',
  'UPLOAD'  => function_exists('wp_upload_dir') ? wp_upload_dir():'',
  'REQUEST'   => isset( $_REQUEST )?$_REQUEST:'',
  'HTTP_POST_FILES'   => isset( $HTTP_POST_FILES )?$HTTP_POST_FILES:'',
  'HTTP_POST_VARS'    => isset( $HTTP_POST_VARS )?$HTTP_POST_VARS:'',
  'HTTP_SERVER_VARS'  =>  isset( $HTTP_SERVER_VARS )?$HTTP_SERVER_VARS:'',
  'HTTP_RAW_POST_DATA' => isset( $HTTP_RAW_POST_DATA )?$HTTP_RAW_POST_DATA:'',
  'HTTP_GET_VARS'     => isset( $HTTP_GET_VARS )?$HTTP_GET_VARS:'',
  'HTTP_COOKIE_VARS'  =>  isset( $HTTP_COOKIE_VARS )?$HTTP_COOKIE_VARS:'',
  'HTTP_ENV_VARS'     => isset( $HTTP_ENV_VARS )?$HTTP_ENV_VARS:'',
  );
  foreach ($globs as $k => $v) if (isset($v) && sizeof($v) > 0) $oa[$k] = $v;
 
  foreach (array_keys($_SERVER) as $k) if ($val = strval($_SERVER[$k]) && !empty($val)) $oa[(substr($k, 0, 5) == 'HTTP_' ? 'HTTP' : 'SERVER')][$k] = $_SERVER[$k];
 
  return $oa;
}

get_debug_loaded_extensions

Returns a list of all the loaded extensions in php. If verbose it also returns their functions!

function get_debug_loaded_extensions($vb=false)
{
  $oa=array();
  foreach((array)@get_loaded_extensions() as $k=>$v) $oa[$v]= ($vb===false) ? '' : (array)@get_extension_funcs($v);
  return $oa;
}

AskApache Debug Viewer Plugin for WordPress originally appeared on AskApache.com

Install multiple OS Without Cds

$
0
0

AskApache.com


Orig published 2006. If you are looking for a current solution I would recommend: Pendrivelinux.com, Ultra Boot CD, Linux Live USB Creator, or my personal favorite UNetbootin
unetbootin screenshot

I had a CD-RW drive but being a computer security researcher I had no desire to spend money for blank cd-recordables. What follows is how I managed to install various operating systems on my computer (1 hard drive) without having to burn to a CD the ISO and then boot from that.

The original reason I wrote this article was just to expand my knowledge of network/computer security on unix/BSD/linux operating systems. The plan was to create a multi-OS pc that I could boot into 1 of several OS's, then from another PC I would attempt to hack into the computer.. mostly just scanning to get baselines and get a feel for the differences. I figured the best way to do that would be to have a multi-boot system. Unfortunately for me I didn't have any blank CDs to record ISO's on, and I also didn't have a floppy 3.5 disk. So that is how my journey into this subject-matter started.

Summary

  1. Download the iso file
  2. Mount the iso file as a loop back device on a temporary directory /mnt/cdrom
  3. Save the content of /mnt/cdrom, which has the distro expanded in a recognisible form, into a temporary directory. (using dd to "burn" the iso to HD instead of CD)
  4. Reboot and use Grub, sourced from any other Linux, to boot up the kernal and initrd files of this temporary directory, thereby activate its installer if it has one or to conduct the installation from the fire-up GUI.

NOTE: Please keep in mind that there are many different ways to achieve this same result using various loop and ramdisk methods... this is ongoing for me so any help would be appreciated!

Download the iso file

I have been into the computer security scene since 1990, but I realized that I had very little experience with the various LInux, Unix, and alternative Operating systems out there. I first partitioned my 120GB harddrive into 10 partitions, the 2nd partition is a small swap and the last partition is extra large because it holds all the ISO images.. I then wrote a small shell script to automatically download (I love wget, but curl most!) the following.

  • OpenBSD
  • IpCOP
  • Libranet
  • Arch-Linux
  • Fire
  • Local Area Security
  • Packet Master
  • Devil-Linux
  • FreeBSD
  • Knoppix
  • Helix
  • Gentoo
  • Yoper-Linux
  • NetBSD
  • RedHat
  • Slackware

The script also downloaded Installation manuals and md5 checksums.. (let me know if I should post... its pretty unsophisticated ;)

I installed Slackware (personal favorite) on hda1 using my last blank CD-R, note that I do not have a separate boot partion. (Should I?). I also installed grub on the MBR. I love grub, if you read through the man pages and all info you can find about grub, you can learn a whole lot. Grub has much more features and capability than lilo, even though lilo comes installed by default with slack.

I organize my kernel situation as follows... In my /boot directory, I mkdir KERNEL, CONFIG, MAP, INITRD and that is a good way for me to keep my kernels and everything organized.. Another good way is a separate dir for each new kernel.

Since Arch-Linux is a solid distro, my personal favorite, I'll use that as a first example.

Here is the Arch-Linux section of my shell script

goge Arch-Linux
$w http://puzzle.dl.sourceforge.net/sourceforge/archlinux/arch-0.6.iso
$w http://unc.dl.sourceforge.net/sourceforge/archlinux/arch-0.6.md5sum
$w http://www.archlinux.org/docs/en/guide/install/arch-install-guide.html
md55
cat arch-0.6.md5sum
md5sum arch-0.6.iso
md55

Mount the iso file

The first thing to do is to mount the downloaded ISO image so we can use it as if it were an actual CD.

mount -t iso9660 -o ro,loop=/dev/loop0 cdimage /mnt/cdrom

Where cdimage= the ISO image. EX: /usr/local/src/ISO/Linux/Arch-Linux/arch-0.6.iso

This mounts the iso as /mnt/cdrom.

Next you need to copy /mnt/cdrom to a separate partition for the booting process. So mkfs.ext2 /dev/hda9. ( I prefer reiserfs or even XFS to ext but if you use something other than ext2 you could run into some problems because some of the installation kernels and initrds don't include support for reiserfs and so can't recognize the files. Although you could use mkinitrd to create a new initrd with reiserfs support, that might be pushin it IMO... ;) I use the 9th partition consistently for this. I know there is a "right" way to copy the /mnt/cdrom files so everything stays the way it is supposed too, using tar or cpio, but I'm lazy so I just do cp -rp.

(What is the tar or cpio commands to copy with correct permissions etc??)

So you mount the 9th partition as whatever, say /mnt/hd and then copy the files. Now what?

Reboot and use Grub

Now edit your /boot/grub/menu.lst file to include the specific options to boot arch-linux installation.

A good idea is to find the isolinux.cfg file somewhere on the distro cd, this will tell you what to include in the menu.lst. Here is the section in my menu.lst

title Arch Install
  root (hd0,8)
  kernel /isolinux/vmlinuz load_ramdisk=1 prompt_ramdisk=0 root=/dev/rd/0
  initrd=/isolinux/initrd.img

This should be self-explanatory. The root (hd0,8) is pointing to partition 9. So the rest of the commands start from partition 9.

When you experience problems, remember you can always edit the grub boot options by typing 'e' and then edit the section. Also, a good idea is to include several variations in your menu.lst so you can easily try other ways to boot efficiently. And, remember to read up on all the installation guides that come with your distro, specifically, hard-disk installs.

There are special cases, Gentoo, has a semi-new compressed filesystem called squashfs. BTW, this is AWESOME, so check it out. It has to be compiled into the kernel, so some work is in order, but use this recompile to optimize your kernel. You can get the squashfs patch for almost any kernel. I use the latest stable 2.6 kernel. Squashfs is incredible and although I don't think you need it to install from ISO, you do need it to expand the livecd.squashfs filesystem that comes with the cd. Heres a sample Gentoo section from my menu.lst

title Gentoo Install
  root (hd0,8)
  kernel /isolinux/gentoo root=/dev/ram0
  initrd=/isolinux/gentoo.igz init=/linuxrc acpi=off looptype=squashfs loop=/livecd.squashfs cdroot vga=791 splash=silent

A nother' tip is the shell that is provided if you experience problems, typically busybox or ash. The key tools to get you going from here is mount and chroot. Sometimes you will need to manually create a simulated file system and then chroot into it. For instance, you might have to create boot, etc, bin, directories on the target partition.

I generally install each OS onto the next partition (careful of the logical partition) and add it to my menu.lst after install. A good idea is after installation, copy the kernel and initrd(if there is one) to the slackware(or whatever) boot partition on hda1. I copy kernels to /boot/KERNEL/ and initrd's to /boot/INITRD, then menu.lst is more organized...

You then need to add an updated section to your menu.lst (just comment out the install section for later) Here is the finished arch-linux section from menu.lst

title Arch Linux 6
  root (hd0,2)
  kernel /boot/vmlinuz26 ro root=/dev/hdc3

This doesn't use my convenient boot/KERNEL/vmlinuz26 as you can tell by setting the root to partition 3. ***NOTE: Make a backup of MBR using dd and save to floppy, also backup the partition table to floppy, using cfdisk or parted. And boot disks (I use 1 with grub, and 1 with slack, and tomsbootdisk) will invariably come in handy. Tomsbootdisk is recommended, and make the grub boot disk when you install grub. install to floppy.

The final result after some fun experimenting, is when I boot, I have a cool grub boot screen come up with the option to boot into whatever OS I want, this is handy for multiple reasons. One good thing to do after this is to port scan and vuln scan each OS, after you update of course. Write this stuff down and you will know the weaknesses/strengths of the various OS's.

I can boot a custom Firewall, snort, or multiple honeypots using this procedure, as well as a graphical kde environment with a kernel optimized for graphics and my processor/architecture, or an environment devoted to forensics or even an environment suitable for programming.

P.S. Some of the cooler alternative operating systems are BeOS 5, EOS, ER_OS, V2_OS, and my personal favorite Menuet. Menuet is 100% assembly graphical operating system that fits on a floppy. Its money!

This should be a good enough example to get you started, this kind of thing should be learned and not just copied... Knowing how to do this stuff could prove to be exceptionally useful... ;)

I'm currently doing research into the following areas.

  • MBR code, especially passing off control to different addresses.
  • The difference (in code) of the various bootloaders out there... I have around 20 so far.
  • How to use grub with the stage1_5 iso9660 to be able to read iso filesystems.. this leads to the possibility of moving the iso file to a specific area on the hard drive and load the iso file as if it were a device..
  • How to pass control from the boot-loader, to the boot-manager, to the boot-loader on the iso filesystem. This is my #1 goal. Make it look to the iso filesystem that besides the fact that its a file and not a cd, that a previous boot-loader didn't chain-load to it. IOW, that it is a fresh boot that received its control directly from the BIOS. stupid f'in BIOS! How easy it is to boot from a CD-server serving iso files as cd's, on a nearby pc.
  • How to use the ability of boot-loaders to register and load code into memory much like loop devices, to load and register the code for an iso filesystem, in a looping fashion.
  • How to use vmware to install an iso using the "use actual harddisk" method, how to use this on a partition, safely, and how to transfer entire partition images byte by byte.

I am doing a lot of code hacking and if I don't find an easy (for all linux skill levels) solution soon with one of the boot-loaders, I am looking at having to write one myself.. something I REALLY STRONGLY do not want to do. Any suggestions are welcome.

Also, looking at how the pre-root root, that grub loads and then mounts the kernel from it, how can I add the loop option to tthe mount command used. This happens all transparently for th euser, so I know I have to hack it out.. But is it possible to use a looped fs? without a mounted HD? with a mounted HD that the original looped iso is mounted on?

Also looking at using the ramdisk initrd to load some type of custom program that allows me to mount a looped fs on the pre-root, (or root).

Looking at GRUB2 code has helped a lot. I also like the Ranish Partition Manager..

ONCE AND FOR ALL, lilo just can't compare AT ALL to grub or Ranish Partition Manager. I bet people only use it because of the "first love" syndrome. eh?

At any rate, I'm learning a lot, and many of the results I will find I will post here eventually, because they are HUGE lee important for the security community.

A couple months ago, I stumbled across two incredible programs that I have used over and over again in awe. After getting over my greediness of wanting to keep them to myself.. here you go.. enjoy!

The home page for these tools EasyBoot and UltraISO.

Some Uses Ive Explored:

  • Copying all my system CD's and install CD's to my HD.
  • Modifying my XP Restore CD's to be current and streamlined with XP SP2 and include my favorite windows programs.
  • Creating a custom grub boot CD with extra and unique capabilities.
  • Viewing the construction of all major Operating System's Boot Loader Code and related code.

Suggestions for use:

  1. Read the product documentation thoroughl
  2. Get a good hexeditor/viewer
  3. Read a bunch of threads in the forum
  4. Begin use

Phrack #63

Hey the last issue of phrack (#63) has a really relevant article to this topic..

You can check it out at www.phrack.org or download it here and read it at your leisure :)

Phrack Issue About grub hacking

==Phrack Inc.==
 
              Volume 0x0b, Issue 0x3f, Phile #0x0a of 0x14
 
|=-----------------=[ Hacking Grub for fun and profit ]=-----------------=|
|=-----------------------------------------------------------------------=|
|=---------------=[ CoolQ <qufuping@ercist.iscas.ac.cn> ]=---------------=|
|=-----------------------------------------------------------------------=|
 
--[ Contents
 
    0.0 - Trojan/backdoor/rootkit review
 
    1.0 - Boot process with Grub
        1.1 how does Grub work ?
        1.2 stage1
        1.3 stage1.5 & stage2
        1.4 Grub util
 
    2.0 - Possibility to load specified file
 
    3.0 - Hacking techniques
        3.1 how to load file_fake
        3.2 how to locate ext2fs_dir
        3.3 how to hack grub
        3.4 how to make things sneaky
 
    4.0 - Usage
 
    5.0 - Detection
 
    6.0 - At the end
 
    7.0 - Ref
 
    8.0 - hack_grub.tar.gz

If you need to hack the physical security of a computer.. there isnt really a much better way of doing it than what is referenced in the phrack article and in the posts above. There is also the possiblity of breaking the physical security at 1 computer and booting up your custom files.. and then use your custom loaded OS to configure devices network-wide.. using BOOTP/DHCP/tftp/etc. protocols.. A lot of networked printers and devices would rapidly fall to this method... configure the newly captured printers/devices to open a backdoor back into the local network remotely for you automatically, even after your custom OS is unloaded.. with the increase use of wireless devices and PnP devices like USB, protecting the physical security will become much more important in the future.

Ive also noticed that booting a pc could be as easy as a usb key, or using a usb upstream/downstream hub to self-boot, just think of all the memory cards and other proprietary type access points there are..

If I can boot your machine, your security is about none. Scarry.

Sounds like fun

Install multiple OS Without Cds originally appeared on AskApache.com

The Right to Read

$
0
0

AskApache.com

Free Knowledge

Act on ACTA: Tell the New Congress to Open the Secret IP Pact

Revelations about the secretive Anti-Counterfeiting Trade Agreement (ACTA) have emerged, and the news is not good for technology users or digital rights. Instead of concentrating on physical fakes and fraud, recently leaked draft language suggests ACTA will provide expansive powers to customs authorities worldwide to search and seize digital technology at the border on suspicion of IP infringements and to widen the criminalization of previously civil IP law way beyond profit-seeking pirates. An entire section of the trade agreement would create new regulations over the Internet and DRM -- but those details remain secret. Write to your representatives now to demand that Congress bring transparency to this clandestine pact.

by Richard Stallman This article appeared in the February 1997 issue of Communications of the ACM (Volume 40, Number 2). (from "The Road To Tycho", a collection of articles about the antecedents of the Lunarian Revolution, published in Luna City in 2096)
For Dan Halbert, the road to Tycho began in college—when Lissa Lenz asked to borrow his computer. Hers had broken down, and unless she could borrow another, she would fail her midterm project. There was no one she dared ask, except Dan.
This put Dan in a dilemma. He had to help her—but if he lent her his computer, she might read his books. Aside from the fact that you could go to prison for many years for letting someone else read your books, the very idea shocked him at first. Like everyone, he had been taught since elementary school that sharing books was nasty and wrong—something that only pirates would do. And there wasn't much chance that the SPA—the Software Protection Authority—would fail to catch him. In his software class, Dan had learned that each book had a copyright monitor that reported when and where it was read, and by whom, to Central Licensing. (They used this information to catch reading pirates, but also to sell personal interest profiles to retailers.) The next time his computer was networked, Central Licensing would find out. He, as computer owner, would receive the harshest punishment—for not taking pains to prevent the crime. Of course, Lissa did not necessarily intend to read his books. She might want the computer only to write her midterm. But Dan knew she came from a middle-class family and could hardly afford the tuition, let alone her reading fees. Reading his books might be the only way she could graduate. He understood this situation; he himself had had to borrow to pay for all the research papers he read. (10% of those fees went to the researchers who wrote the papers; since Dan aimed for an academic career, he could hope that his own research papers, if frequently referenced, would bring in enough to repay this loan.) Later on, Dan would learn there was a time when anyone could go to the library and read journal articles, and even books, without having to pay. There were independent scholars who read thousands of pages without government library grants. But in the 1990s, both commercial and nonprofit journal publishers had begun charging fees for access. By 2047, libraries offering free public access to scholarly literature were a dim memory.

Debugging code is Illegal

GNU Free SoftwareThere were ways, of course, to get around the SPA and Central Licensing. They were themselves illegal. Dan had had a classmate in software, Frank Martucci, who had obtained an illicit debugging tool, and used it to skip over the copyright monitor code when reading books. But he had told too many friends about it, and one of them turned him in to the SPA for a reward (students deep in debt were easily tempted into betrayal). In 2047, Frank was in prison, not for pirate reading, but for possessing a debugger.
Dan would later learn that there was a time when anyone could have debugging tools. There were even free debugging tools available on CD or downloadable over the net. But ordinary users started using them to bypass copyright monitors, and eventually a judge ruled that this had become their principal use in actual practice. This meant they were illegal; the debuggers' developers were sent to prison. Programmers still needed debugging tools, of course, but debugger vendors in 2047 distributed numbered copies only, and only to officially licensed and bonded programmers. The debugger Dan used in software class was kept behind a special firewall so that it could be used only for class exercises. It was also possible to bypass the copyright monitors by installing a modified system kernel. Dan would eventually find out about the free kernels, even entire free operating systems, that had existed around the turn of the century. But not only were they illegal, like debuggers—you could not install one if you had one, without knowing your computer's root password. And neither the FBI nor Microsoft Support would tell you that. Dan concluded that he couldn't simply lend Lissa his computer. But he couldn't refuse to help her, because he loved her. Every chance to speak with her filled him with delight. And that she chose him to ask for help, that could mean she loved him too. Dan resolved the dilemma by doing something even more unthinkable—he lent her the computer, and told her his password. This way, if Lissa read his books, Central Licensing would think he was reading them. It was still a crime, but the SPA would not automatically find out about it. They would only find out if Lissa reported him. Of course, if the school ever found out that he had given Lissa his own password, it would be curtains for both of them as students, regardless of what she had used it for. School policy was that any interference with their means of monitoring students' computer use was grounds for disciplinary action. It didn't matter whether you did anything harmful—the offense was making it hard for the administrators to check on you. They assumed this meant you were doing something else forbidden, and they did not need to know what it was.

Banned from School Computer Systems

Students were not usually expelled for this—not directly. Instead they were banned from the school computer systems, and would inevitably fail all their classes. Later, Dan would learn that this kind of university policy started only in the 1980s, when university students in large numbers began using computers. Previously, universities maintained a different approach to student discipline; they punished activities that were harmful, not those that merely raised suspicion. Lissa did not report Dan to the SPA. His decision to help her led to their marriage, and also led them to question what they had been taught about piracy as children. The couple began reading about the history of copyright, about the Soviet Union and its restrictions on copying, and even the original United States Constitution. They moved to Luna, where they found others who had likewise gravitated away from the long arm of the SPA. When the Tycho Uprising began in 2062, the universal right to read soon became one of its central aims.

Author's Note

The Right to ReadThis note was updated in 2007. The right to read is a battle being fought today. Although it may take 50 years for our present way of life to fade into obscurity, most of the specific laws and practices described above have already been proposed; many have been enacted into law in the US and elsewhere. In the US, the 1998 Digital Millenium Copyright Act established the legal basis to restrict the reading and lending of computerized books (and other works as well). The European Union imposed similar restrictions in a 2001 copyright directive. In France, under the DADVSI law adopted in 2006, mere possession of a copy of DeCSS, the free program to decrypt video on a DVD, is a crime. In 2001, Disney-funded Senator Hollings proposed a bill called the SSSCA that would require every new computer to have mandatory copy-restriction facilities that the user cannot bypass. Following the Clipper chip and similar US government key-escrow proposals, this shows a long-term trend: computer systems are increasingly set up to give absentees with clout control over the people actually using the computer system. The SSSCA was later renamed to the unpronounceable CBDTPA, which was glossed as the "Consume But Don't Try Programming Act".
The Republicans took control of the US senate shortly thereafter. They are less tied to Hollywood than the Democrats, so they did not press these proposals. Now that the Democrats are back in control, the danger is once again higher.
In 2001 the US began attempting to use the proposed Free Trade Area of the Americas treaty to impose the same rules on all the countries in the Western Hemisphere. The FTAA is one of the so-called "free trade" treaties, which are actually designed to give business increased power over democratic governments; imposing laws like the DMCA is typical of this spirit. The FTAA was effectively killed by Lula, President of Brazil, who rejected the DMCA requirement and others. Since then, the US has imposed similar requirements on countries such as Australia and Mexico through bilateral "free trade" agreements, and on countries such as Costa Rica through CAFTA. Ecuador's President Correa refused to sign the "free trade" agreement, but Ecuador had adopted something like the DMCA in 2003. Ecuador's new constitution may provide an opportunity to get rid of it. One of the ideas in the story was not proposed in reality until 2002. This is the idea that the FBI and Microsoft will keep the root passwords for your personal computers, and not let you have them. The proponents of this scheme have given it names such as "trusted computing" and "palladium". We call it "treacherous computing", because the effect is to make your computer obey companies instead of you. This was implemented in 2007 as part of Windows Vista; we expect Apple to do something similar. In this scheme, it is the manufacturer that keeps the secret code, but the FBI would have little trouble getting it. What Microsoft keeps is not exactly a password in the traditional sense; no person ever types it on a terminal. Rather, it is a signature and encryption key that corresponds to a second key stored in your computer. This enables Microsoft, and potentially any web sites that cooperate with Microsoft, the ultimate control over what the user can do on his own computer.

Vista also gives Microsoft additional powers; for instance, Microsoft can forcibly install upgrades, and it can order all machines running Vista to refuse to run a certain device driver. The main purpose of Vista's many restrictions is to make DRM that users can't overcome.

The SPA, which actually stands for Software Publisher's Association, has been replaced in this police-like role by the BSA or Business Software Alliance. It is not, today, an official police force; unofficially, it acts like one. Using methods reminiscent of the erstwhile Soviet Union, it invites people to inform on their coworkers and friends. A BSA terror campaign in Argentina in 2001 made slightly-veiled threats that people sharing software would be raped. When this story was first written, the SPA was threatening small Internet service providers, demanding they permit the SPA to monitor all users. Most ISPs surrendered when threatened, because they cannot afford to fight back in court. (Atlanta Journal-Constitution, 1 Oct 96, D3.) At least one ISP, Community ConneXion in Oakland CA, refused the demand and was actually sued. The SPA later dropped the suit, but obtained the DMCA which gave them the power they sought. The university security policies described above are not imaginary. For example, a computer at one Chicago-area university prints this message when you log in (quotation marks are in the original):
This system is for the use of authorized users only. Individuals using this computer system without authority or in the excess of their authority are subject to having all their activities on this system monitored and recorded by system personnel. In the course of monitoring individuals improperly using this system or in the course of system maintenance, the activities of authorized user may also be monitored. Anyone using this system expressly consents to such monitoring and is advised that if such monitoring reveals possible evidence of illegal activity or violation of University regulations system personnel may provide the evidence of such monitoring to University authorities and/or law enforcement officials.
This is an interesting approach to the Fourth Amendment: pressure most everyone to agree, in advance, to waive their rights under it.
The Right to Read This essay is published in Free Software, Free Society: The Selected Essays of Richard M. Stallman.

Other Texts to Read

Copyright © 1996 Richard Stallman Verbatim copying and distribution of this entire article is permitted in any medium without royalty provided this notice is preserved.

The Right to Read originally appeared on AskApache.com

Questions I Ask Web Hosting Companies, Before Buying

$
0
0

AskApache.com

I'm always on the lookout for cheap hosting and great hosting companies, and being that I have done this for many years, on many platforms, and with many hosts, my only requirement is that the host uses a UNIX/BSD/LINUX operating system. I'm just not one of those people who likes to do things the hard way, constantly, if its even possible on a non-nix, or one of those people who enjoys getting hacked or my sites defaced by a cracker. So *nix is definitely a requirement. This is just a current look at the basic idea I use when looking for a web host. If you were smart you would do a whole lot more than this.

Research the People

Ok, in a web hosting company there are 5 distinct groups of people, at least generally, that you will want to get in contact with or at least do some background research on (like the owners/founders). Depending on which of these groups you talk to will determine the amount and quality of information you get, the difference is night and day. Because of my past experience with really bad hosts (DreamHost), and really great hosts (WiredTree), I am very cautious and purposeful in making this decision, so I go to great lengths to contact at least one person from each of these groups. Most good advice says to also get in touch with customers.. I don't usually need/want to do that though because most customers don't know jack. But of course I know a few of the customers because I research the hosts network block and test the speed and servers that run on their IP block.

Who / Why

Being a curious and inquisitive person by nature, I always do background research on who started the company, how they started it, and what skills they have. Knowing who the owners are and if they are real unix/network experts or just snake oil salesmen really makes a difference in this world of smoke and mirrors.

Here's my recommendation of which group to contact, in order of best to worst:

  1. Owners/Founders - The Founders have been involved since the start of the company. Always contact.
  2. System Admins - Programmers and System Operators who keep things running, fix problems tech support cant. Always contact.
  3. Sales/Marketing - Both types have different motivations for what they say, and how they say it. Always contact both.
  4. Tech Support - They make the web go round, will always know a lot about problems and issues their customers frequently experience. Always contact.
  5. Management - These people are in charge of the day-to-day operations, overseers. Contact optional.

Questions to Ask

The following is a transcript of a chat I had with a company called tektonic, and at that time I was looking for a cheap linux host to use for some redundancy/failover operations. I generally contact a new hosting company like this every few months.. I like to have options available in case of some kind of failure or network attack, so it's always a good idea to have a few ace linux servers in your back pocket.

If you've read any other articles on AskApache, you can see a certain obsession towards optimization, speed, and security -- so that is the purpose of the following questions.

General Info
Chat start time Apr 7, 2010 7:18:07 AM EST
Chat end time Apr 7, 2010 8:38:52 AM EST
Duration (actual chatting time) 01:20:44
Operator Vish

Chat Transcript

info: Please wait for a site operator to respond. You are 1 out of 1 in the queue. The average wait time is 0 minutes and 30 seconds.

info: You are now chatting with 'Vish'

Vish: Hello

AskApache: Hi vish, i was looking to purchase a planwith you guys but had some questions.. is this the right place to ask?

Vish: yeah sure

Vish: Let me know how may I assist you with ?

AskApache: what is your cheapest plan that includes ssh?

Vish: http://tektonic.net/vps.php

Vish: Linux-360

AskApache: im there..

Vish: It is cheapest plan you can have

AskApache: what does full root access mean for you guys?

AskApache: do you have swap? jailshell?

Vish: you have full access of you server .

AskApache: including network interface device access? ie.. is it possible to setup virtual nics?

Vish: Sorry we do not provide it.

Vish: hold on

Vish: Let me check

AskApache: how can i find out more about the limits of the machine for the Linux-360?

AskApache: like how many processes, fd descriptors..

Vish: You can mail us at sales department.

Vish: They will get back to you with in few hrs with your answers

Vish: You can just drop mail at sales@tektonic.net

AskApache: no thanks.

AskApache: jw if you had that info offhand.

AskApache: do you know if cpanel is optinoal?

AskApache: could it be uninstalled?

Vish: yeah

Vish: you can install or uninstall as you wish

AskApache: Thanks vish you are being very helpful... a few more..

Vish: sure

AskApache: what operating system?

Vish: Hold on ..

Vish: allow me a moment.

AskApache: please take your time

Vish: We do provide Ubantu , Centos and Debian

Vish: You can reinstall your server any time with one click

AskApache: what devices are supported in /dev ?

AskApache: do you support loop devices, ramdisk/tmpfs/swap?

Vish: One moment please..

AskApache: no rush at all, thanks

Vish: We do provide tmpfs but ramdisk and swap is not available .

Vish: All basic device are available with us optional devices like TUN is also enabled for you automatically.

AskApache: sweet

AskApache: is ipv6 supported?

Vish: It is there but we do support currently .

Vish: We are thinking to provide it in near future for our clients ;)

AskApache: good idea, people will start using it in 5years or so.. maybe

AskApache: how is the internal network segmented? vlans?

AskApache: for security..

Vish: Yeah, We do have Vlans

AskApache: security is very crucial.

Vish: You can check more info in network here network

AskApache: ok thanks brb

AskApache: do you allow kernel modules? or reloading the kernel like kexec?

Vish: a moment please.

Vish: What type kernel module you are looking for exactly ?

Vish: kexex is for fast reboot .

Vish: Is there any specific requirement ?

Vish: As we do not allow kernel modules on VPS they are not supported by virtuzzo.

AskApache: ok.. so far so good. let me think a minute.

AskApache: what kind of failovers do you have?

AskApache: like if a machine fails to reboot or goes offline

Vish: we do not provide failover services for vpses at this time. You will have power panel in hand using it you can reboot or reinstall your machine in one click. You can reach us 24*7 for live support.

AskApache: one problem that I've seen on other vps's is sometimes a vps upon reboot fails to recognize the network interface/fails to connect to the web.. When that happens we are unable to ssh into the box to fix the problem and rely on support.. is this something that would be easy/normal for your support (to have to manually login to the vps locally)

Vish: There are the possiblities for the issue so we need to check in server but you can reach us anytime for live chat and ticket system.

Vish: as you are on live chat right now ;)

AskApache: so your support does have access to the vps locally?

AskApache: in case the network is down due to vps errors

Vish: Yes, We have the access

AskApache: do you run any packet filtering on the network or is this controlled solely with the vps?

AskApache: like iptables stuff.. switch/router filtering beyond defaults..

Vish: No , we dont have packet filtering the port we block is IRC only.

AskApache: great

Vish: I'm sorry for the delay. I'll be right with you.

Vish: Is there anything else I may assist you with ?

AskApache: no problem, you've answered all my questions so far.. trying to think of anything else I'd like to know before buying..

Vish: Sure

Vish: Is there anything else I can help you with ?

AskApache: Does the Linux-360 support filesystems? what storage devices are included (usually just 1 ext2/3/4 fs for vps).. Is it possible to repartition the drive?

AskApache: Oh and the other kernel module I would love to have on a vps is fuse so that I can mount remote filesystems (such as sshfs or nbd)

Vish: We do not provide kernel modules on VPS.

AskApache: do you allow kernel compilation? (that way i can build the module statically into the kernel)

Vish: A moment please.

Vish: We do not allow kernel compilation on VPS.

AskApache: ok, thats smart security

AskApache: what about the linux-360 partitioning question?

Vish: Thanks. :)

Vish: it is tmpfs on VPS

Vish: and we dot allow repartition.

AskApache: which is ultimately mounted on.. filesystems? like could I modify an ext3 / to ext4 or reiserfs?

AskApache: expected.. ok

Vish: No, it is vzfs

AskApache: even better.

AskApache: thats what i mostly use.

Vish: great

AskApache: What vps os install images do you use? like where do you get the CentOS/Ubuntu/Debian vps images? And are they modified/customized by you guys in any way?

AskApache: Or just all defaults?

Vish: they include basic services such as httpd, sendmail

AskApache: sorry for all the q's ... I wasn't thinking that I'd actually find a good host to purchase, but so far tek is looking really good.. might go ahead within the hour.

Vish: otherwise default

Vish: We get it from parallels

Vish: Okay great.

Vish: Is there anything else I can help you with ?

AskApache: like: http://download.openvz.org/template/precreated/

AskApache: do you use templates like that..

Vish: We get it from parallels

AskApache: how many employees do you have? how many customers?

Vish: Sorry, We do not disclose this information

AskApache: thats fine..

Vish: For more you can contact sales department.

Vish: You are on technical department live chat.

AskApache: can you give me more info on what type of parallels products you utilize?

AskApache: I wouldn't last long on any other chat.. ;)

AskApache: I'm curious so if it's a template/container I haven't used before I can test it out on my own machine.

Vish: We provide power panel from parallels

AskApache: i mean like the templates/container versions you use.. I want to check that you use updated/new versions and are valid licensed.

Vish: you mean OS version ?

AskApache: basically, do you know if you use the latest available os images from parallels..

AskApache: and I will let you go with that..

info: Your chat transcript will be sent to your email at the end of your chat.

Vish: Yes , We do provide latest OS version as per requirement.

AskApache: thank you vish, you've been most helpful. I am going to do a little more digging online about you guys and will probably be back with a couple questions.. cya around, have an awesome day

Hosts used by AskApache.com

WiredTree is the main hosting company that I mainly use for this site and my business. It took me 10+ years of trial and error before I found them, you can believe I will be posting alot more about them on this site, stay tuned. I also use HostGator, and several other dependable nix hosts that are dirt cheap.

Finding A Host

I used to spend days and weeks googling for a host that wouldn't end up burning me later, oh that really sucked. Now I use a site developed by a colleague of mine, Web Hosting Search as it lets me fairly quickly find a linux host with my bare requirements. From THERE is when I start my own research. This includes email and followups on the phone, visiting wiki's, googling owners, sneaking around in customer areas, etc..

Who do you Use?

I'd love to hear about anyone's experiences with specific hosts, recommendations especially!

Questions I Ask Web Hosting Companies, Before Buying originally appeared on AskApache.com

Viewing all 58 articles
Browse latest View live