Sie sind auf Seite 1von 11

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

L2DC Linux Server Guide - Public Release


Author: Cyberfox - cyberfox@l2-adrenaline.com - L2DC Tech Admin http://www.l2dcproject.com/ - IRC Channel #l2dc at freenode.net IMPORTANT: This document was created for L2DC community, in order to help our admins to create good Production Servers in order to run our software based on good security and performance policies. Since L2DC and L2J shares lots of common code and the same basis, I think some admins might have a good use of it. I tested on a Virtual Machine every command and setting proposed here, so this might to be safe enough to be used on production environment, anyways, be carefull applying this settings on a stable running Server.[BR] This is a working in progress. I will add and correct data on this document and release new revisions. Software evolves, documentation should follow same pace. If you plan use this info somewhere, please keep authorship and contact information references. To release this document to public, in order to benefit all our community, I had to remove some project-related information, like our SVN location and details of our settings on optimizing InnoDB and MyISAM storage engines. Im sorry for that. I really hope this document helps you to make/adjust your Server to maximum security and performance. Good luck! Revision 1.3 - Public Release All we know Linux based servers are faster, more stable and secure tham Windows based Servers, but several of our admins choose Windows server for having problems setting up a Linux Server. A badly configured Linux Server can be in all aspects, worst tham a Windows one. I have some experience on Linux and L2J-based servers, so, I decided wrote this reference guide to help you friends to setup correctly and securely a good Linux Production Server. Production Server: Running a Server on live, public on Internet is a quite dangerous thing. I receive an average 40 attacks per day, with all varities of techniques we can imagine, going from portscans to DDoS. An efficient way of frustrating those attackers is understand a basic idea: Production Server. A Production Server is an enviroment highly specialized in some type of Service, like a Game Server or a Web Server. Such Server need to start they setup from a minimium as possible installation and focus greatly on resource and security tweaks on its configuration, as needed services are installed. Basics understood, lets start working on our Server. We have two approaches now: Admin will set up his own Server or will make specifics recommendations to Datacenter on Server rental. This is what you may have in mind ordering a Server. 2 processors or more. This is required for -server Java setting on server startup line. Enough RAM. DDR3 is better. Crowded Servers running a basic MySQL setup runs fine with 8GB. Hard drivers faster as possible. 15k RPM SCSI on RAID are best option so far. Solid state drivers are still too expensive for production use, but in a near future, will be my next pickup. A spare HD just for MySQL is a good call. Enough bandwitdh. At least 100mb/s. This will reduce ingame lag and will stop some silly DDoS attacks from most script kiddies. Dont forget: Ask for a minimal system setup.

Ubuntu Server 64 bits


This is my personal choice. After years of experiments, this is the most reliable Server System I have found so far. Ubuntu Server is a Debian based distro, so, you can assume all contents on this guide may be applied to any Debian setup or Debian variable on net. So, why not use a Debian? Simple: Debian is a very stable and secure system, which makes it ideal for long runs, but our software constantly requires latest technologies, like latest Sun Java or newer MySQL versions to run fine. Debian takes years to relase a new version, and in this mid time, you might have problems running L2J/L2DC updates. Ubuntu Servers release a new version each 6 months, so, all you can do is run a simple script to update it fully to the newer version, with latest technology, well tested. An advice: When a new Ubuntu Server release comes, wait 30 days, at least before updating to newer. I had problems updating in the zero-day and a update script flaw put my MySQL Server ou of Service for some hours, until I found a solution for it. Always prefer 64 bit architecture. This will help a lot with memory limits, MySQL and Java memory management.

References and defaults


Each section may build on information and recommendations discussed in prior sections. Each section should be read and understood completely; instructions should never be blindly applied. Relevant discussion will occur after instructions for an action. On this guide, I will assume you know how to connect to your system using SSH. This is primarily a Linux - Linux based guide. For admins using Windows locally, I will provide some links on relevant sections for additional information. In our example, we will use user to login and manage system. You should not use root on a Production Server for login and common use. I prefer aptitude over apt-get. Both do same work, but I prefer advanced packet handling provided by aptitude. All our commands, during system setup will assume you are root. Later, on basic usage, its better use sudo to manage system. My Server is called l2dcserver on this guide. My home machine is called firefox on this guide My username is called cyberfox on this guide This is a Server root shell: root@l2dcserver:~# This is a Server user shell: user@l2dcserver:~$ This is a Local user shell: cyberfox@firefox:~$ Pay attention to this details. This is an important reference on this guide.

BASIC SETUP
Update Installed System Automatic Update Routine Server Timezone Linux Kernel Optional - Setup DynDNS

Logging in first time


Your Datacenter will mail you your first access password. This password must be changed to a personal one right in first moments with Server. Check http://www.passwordmeter.com/ to get a good one. user@l2dcserver:~$ passwd If you Datacenter mailed you a USER account, run a sudo su - and enter your own password to gain root access. If a root account was provided, log in and lets work on System.

Updating System
When loggin in, update your system: root@l2dcserver:~# aptitude update root@l2dcserver:~# aptitude safe-upgrade -y

Keep System Updated


Keep your system updated is a crucial step to avoid exploits on known vulnerable services/packages on System. To automate that process, lets install unattended-upgrades package and configure it using nano, a simple text editor. root@l2dcserver:~# aptitude install unattended-upgrades nano root@l2dcserver:~# nano /etc/apt/apt.conf.d/50unattended-upgrades Uncoment (removes //) from those lines "Ubuntu karmic-security"; "Ubuntu karmic-updates"; Uncoment and set your email here: Unattended-Upgrade::Mail "root@localhost"; Save and exit nano: CTRL + X

Setting TimeZone?
As international admins, you may live in Brazil and set up a Server in Germany. Its very important to setup your timezone correctly to avoid misunderstandings and among your users. When you decide what timezone you will use, set it up now: root@l2dcserver:~# dpkg-reconfigure tzdata And follow screen instructions.

Setting Linux Kernel


Yes, Linux kernel can, and must be configured to take maximum advantage from its features. We will do this changing and adding commands to /etc/sysctl.conf file. This file is readed on every system startup, so, once correctly configured, you never have to do it again. Edit the file /etc/sysctl.conf and add or correct the following lines:

1 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

# Process protections kernel.exec-shield = 1 kernel.randomize_va_space = 1 # Routing settings net.ipv4.ip_forward = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 # IPv4 settings net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.all.secure_redirects = 0 net.ipv4.conf.all.log_martians = 1 net.ipv4.conf.default.accept_source_route = 0 net.ipv4.conf.default.accept_redirects = 0 net.ipv4.conf.default.secure_redirects = 0 net.ipv4.icmp_echo_ignore_broadcasts = 1 net.ipv4.icmp_ignore_bogus_error_messages = 1 net.ipv4.tcp_syncookies = 1 net.ipv4.conf.all.rp_filter = 1 net.ipv4.conf.default.rp_filter = 1 # Performance setting vm.swappiness = 0 # IPv6 setting - Disable. net.ipv6.conf.all.accept_ra = 0 ExecShield? comprises a number of kernel features to provide protection against buffer overflows. These features include random placement of the stack and other memory regions, prevention of execution in memory that should only hold data, and special handling of text buffers These options improve Linuxs ability to defend against certain types of IPv4 protocol attacks. The accept source route, accept redirects, and secure redirects options are turned off to disable IPv4 protocol features which are considered to have few legitimate uses and to be easy to abuse. The net.ipv4.conf.all.log martians option logs several types of suspicious packets, such as spoofed packets, source-routed packets, and redirects. The icmp echo ignore broadcasts icmp ignore bogus error messages options protect against ICMP attacks. The tcp syncookies option uses a cryptographic feature called SYN cookies to allow machines to continue to accept legitimate connections when faced with a SYN flood attack. The rp filter option enables RFC-recommended source validation. VM Swappiness average value is 50, this is the rate between use of system memory and enter on system swap. On a high performance Server, I prefer set this to 0, where system will avoid using swap at all costs, until its absolutely necessary. I have no problem with this feature in years. Finally, last setting will disable IPv6 partially on our System. Its a relatively new protocol and still have some potential flaws. Its very difficult to handle with actual software and hardware and a possible security problem, so, we will turn it off. L2 client or server never use this protocol. To ensure IPv6 module NEVER load, execute following command: root@l2dcserver:~# echo "blacklist ipv6" > /etc/modprobe.d/blacklist-ipv6

OPTIONAL Features on Basic Setup


Optional - DynDNS
You have an option to setup a free hostmane to your server IP address. This will make connceting to your Server more easily, even from other machines, since you dont have to know your exact IP address number. Create a free dynamic DNS here: http://www.dyndns.com/ Take note of your DynDNS login and password, as other settings you might set on DynDNS webpage. Them install and configure ddclient with given options root@l2dcserver:~# aptitude install ddclient Do NOT set ddclient as a daemon. That will keep program resident on memory, consuming resources. This can be a potential security problem, so lets update system on a more secure and resource cheaper way. Edit /etc/default/ddclient and set run_daemon="false" to be sure. Them, create ddclient.weekly file: #!/bin/bash # Script to automate ddclinet usabe without daemon mode. # Put this on /etc/cron.weekly /usr/sbin/ddclient Set it as executable and move it to /etc/cron.weekly/ directory. root@l2dcserver:~# chmod +x ddclient.weekly root@l2dcserver:~# mv ddclient.weekly /etc/cron.weekly/ That way, this will run automatically every week, updating your DynDNS data and avoiding expiration. Important: Now its time to a Server Restart to ensure all settings will take place. root@l2dcserver:~# shutdown -r now

ESSENTIAL SERVICES SETUP


SSH Server - Key based auth. Firewall Optional - SSH Tunnels Optional - OSSEC-HIDS Optional - PSAD

SSH Server
OpenSSH is a FREE version of the SSH connectivity tools that technical users of the Internet rely on. Users of telnet, rlogin, and ftp may not realize that their password is transmitted across the Internet unencrypted, but it is. OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks. Additionally, OpenSSH provides secure tunneling capabilities and several authentication methods, and supports all SSH protocol versions. An well configured SSH Server will make your Server almost unhackeable. This is why you should give special attention to this topic. Lets start installing SSH Server. root@l2dcserver:~# aptitude install openssh-server To correctly configure SSH Server, add of modify this lines on /etc/ssh/sshd_config: Protocol 2 PermitRootLogin no IgnoreRhosts yes HostbasedAuthentication no PermitEmptyPasswords no # Subsystem sftp /usr/lib/openssh/sftp-server AllowUsers user SSH1 protocol have some known issues, this is why we set protocol 2 only here. We will not allow root login via SSH or empty passwords anymore. This is a huge security problem. Host-based auth and rhosts will not be considered by SSH Server anymore. Following "Production Server" idea, i will disable sftp not required service. Now, lets test SSH login with username user on l2dcserver: cyberfox@firefox:~$ ssh 192.168.0.70 -l user The authenticity of host '192.168.0.70 (192.168.0.70)' can't be established. RSA key fingerprint is 3e:06:b0:63:b3:ae:f3:d4:53:03:81:d3:ec:af:1c:ed. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.0.70' (RSA) to the list of known hosts. user@192.168.0.70's password: Linux l2dcserver 2.6.31-19-server #56-Ubuntu SMP Thu Jan 28 03:40:48 UTC 2010 x86_64 Last login: Mon Mar 1 07:41:06 2010 user@l2dcserver:~$ sudo su [sudo] password for user: root@l2dcserver:~# SSH Server is now set up and ready for use.

Optional - Key-based Authentication - HIGHLY RECOMMENDED


This is the best way to avoid the most common attack on whole Internet: Brute-force SSH. How it works: We will create a keypair, public and private, install your public key on your user on Server and login using only that key. This way, SSH will ignore user system password and only checks for private key password, stored locally. Only you, with your private key AND your password are allowed to login on Server. This is a dream for most admins. Even knowing root password, no one can even login on your Server, so lets do it! All those steps will be done on your local machine. For Windows users, please follow this guide: http://www.ualberta.ca/CNS/RESEARCH/LinuxClusters/pka-putty.html cyberfox@firefox:~$ sudo aptitude install openssh-client When installed, lets create keypair.

2 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository


NOTE: At this point, you can create a key without a password, just leave Enter passphrase (empty for no passphrase): field blank. Personally, I dont like this approach, anyone who can copy your private key will be able to login without password on your Server. Be careful about that. cyberfox@firefox:~$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/cyberfox/.ssh/id_rsa): Created directory '/home/cyberfox/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/cyberfox/.ssh/id_rsa. Your public key has been saved in /home/cyberfox/.ssh/id_rsa.pub. The key fingerprint is: ee:3e:d7:cb:4c:2b:40:58:29:c0:17:ab:41:3b:6e:f9 cyberfox@firefox The key's randomart image is: +--[ RSA 2048]----+ | .o... . | | ...o.o | | +..+ | | . =. . | | = .S | | . . .. | | E .. .. | | .. o+.. | | .oo .=. | +-----------------+ Now, lets install our public key on Server cyberfox@firefox:~$ ssh-copy-id -i /home/cyberfox/.ssh/id_rsa.pub user@192.168.0.70 user@192.168.0.70's password: Now try logging into the machine, with "ssh 'user@192.168.0.70'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. Local setup is done, lets login on Server using key auth and finish settings. When you try login to your Server, SSH will ask for your KEY password. Enter it and log in normally. cyberfox@firefox:~$ ssh 192.168.0.70 -l user Now everything is working fine, we need to disable password authentication on Server. Add or change following lines on /etc/ssh/sshd_config: PasswordAuthentication no UsePAM no Now, restart SSH Server to ensure all settings take place: root@l2dcserver:~# service ssh restart NOTE: Your public and private key are kept in hidden /home/youruser/.ssh/ directory. Save it on a secret, safe place. Without your private key, you will not be able to login on your Server. Recommended reading: https://help.ubuntu.com/9.10/serverguide/C/openssh-server.html

Firewall - Initial Setup


Now, and only now, with SSH Server correctly configured, its time to set up your firewall. We will handle a very basic firewall system with only one initial rule: Close all ports and start to open only required ones when services are being activated on Server. Lets install it: root@l2dcserver:~# aptitude install ufw All we have so far is SSH, so, lets enable it thru firewall: root@l2dcserver:~# ufw app list Available applications: OpenSSH root@l2dcserver:~# ufw allow OpenSSH Now, enable firewall: root@l2dcserver:~# ufw enable Command may disrupt existing ssh connections. Proceed with operation (y|n)? y Firewall is active and enabled on system startup All done. Your Server is now ready for setting up all services needed for L2DC. Recommended reading: https://help.ubuntu.com/9.10/serverguide/C/firewall.html

OPTIONAL Features on Essential Setup


Optional - SSH Tunnels
A Secure Shell (SSH) tunnel consists of an encrypted tunnel created through an SSH protocol connection. Users may set up SSH tunnels to tunnel unencrypted traffic over a network through an encrypted channel. For example, Windows machines can share files using the Server Message Block (SMB) protocol, a non-encrypted protocol. If one were to mount a Microsoft Windows file-system remotely through the Internet, someone snooping on the connection could see transferred files. To mount the Windows file-system securely, one can establish an SSH tunnel that routes all SMB traffic to the remote fileserver through an encrypted channel. Even though the SMB protocol itself contains no encryption, the encrypted SSH channel through which it travels offers security. The best way to explain how it works is by an common example: I used to access my phpMyAdmin installation without leaving port 80 opened on my Server. This have two benefits: 1. Unexploitable, 2. Encripted traffic. This will be better explained later. Now, lets create an SSH tunnel: cyberfox@firefox:~$ ssh -f -N -L8080:192.168.0.70:80 -l cyberfox 192.168.0.70 This will create an SSH Tunnel from localhost to 192.168.0.70, forwarding local port 8080 to remote port 80 using username cyberfox to authenticate on Server. The -f parameter tell command to run on background and the -N parameter tell SSH to just create a port forward, without opening a terminal on remote Server. And yes, you need to specify remote server twice :) This can be useful for several uses, like encrypting VNC traffic, tunneling your email, navigate using your Server as a proxy (make a tunnel with Server using a certain port and setup your browser to use localhost:port as proxy) and even bypassing firewalls. With phpMyAdmin correctly configured (details below), use it thru tunnel. Open you browser and do: http://localhost:8080/secretdbaccess/ Have fun.

Optional - OSSEC-HIDS
I like and use this one. Developed by a brazillian guy, OSSEC is a scalable, multi-platform, open source Host-based Intrusion Detection System (HIDS). It has a powerful correlation and analysis engine, integrating log analysis, file integrity checking, centralized policy enforcement, rootkit detection, real-time alerting and active response. This toll will make attackers life a lot harder and will protect your system against almost all known problems. This worth a try. OSSEC can be found here: http://www.ossec.net/main/downloads/ Download it using wget: root@l2dcserver:~# wget http://www.ossec.net/files/ossec-hids-2.3.tar.gz Unpack it and enter on created directory: root@l2dcserver:~# tar -xzf ossec-hids-2.3.tar.gz root@l2dcserver:~# cd ossec-hids-2.3 Now, you will need compile tools in order to build ossec via given script. To install those tools, run: root@l2dcserver:~/ossec-hids-2.3# aptitude install build-essential When done, install it using: root@l2dcserver:~/ossec-hids-2.3# ./install.sh Choose your preferred language, local setup, set your email adress and leave all default until the end of installation. Its not adviced leave compilers installed on a Production Server: root@l2dcserver:~/ossec-hids-2.3# aptitude remove build-essential Crowded servers are being overrunned by OSSEC emails, you can raise email alerts threshold from 7 to 11, for example. This will disable a lot of false-positives. Personally, I keep 7 for paranoid purposes. Edit /var/ossec/etc/ossec.conf and change this value from 7 to 11 to reduce ossec email alerts.

3 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

<alerts> <log_alert_level>1</log_alert_level> <email_alert_level>7</email_alert_level> </alerts> To completely disable it, change yes to no here. - Not Recommended <email_notification>yes</email_notification> Believe me, you will not leave this enabled for now. When Active Response is enable and OSSEC is running, it will block any hack attempt IP for 20 minutes. Have this in mind! This means if you try to change your accesslevel on MySQL using PHPMyAdmin, for example, OSSEC will detect a successful hack attempt and you lock your access for 20 minutes. There is nothing you can do, except wait, login again and temporarily disable it. In the end, OSSEC helps me more tham annoy me. I like this tool. root@l2dcserver:~/ossec-hids-2.3# service ossec stop

Optional - PSAD
This tool was designed to block DDoS attacks with a Server-side approach. It wrks in a similar way from OSSEC, blacklisting temporarily highly traffic strange packets. On my Server, default config options is ok so far and it consume very few resources. Its a good call. Install it using: root@l2dcserver:~# aptitude install psad mailutils And now you are protected. Recommended reading: http://www.nsa.gov/ia/guidance/security_configuration_guides/operating_systems.shtml

L2DC REQUIREMENTS SETUP


Sun Java Development Toolkit MySQL Server Optional - Java Optimization Optional - MySQL Optimization Optional - phpMyAdmin Optional - Apache 2 Web Server Optional - Apache ModSecurity? Optional - FTP Server Optional - eBox - Not Recommended

Sun Java Development Toolkit


Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is general-purpose, concurrent, class-based, and object-oriented, and is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere". Java is considered by many as one of the most influential programming languages of the 20th century, and widely used from application software to web application. To build and run L2DC software, we need Java 1.6 Development Toolkit. On the new version, Ubuntu 10.04 Lucid Lynx will not have Sun Java on main repositories anymore. They moved it to partner repositories. If you are using Lucid Lynx or newer release, uncomment this two lines on /etc/apt/sources.list deb http://archive.canonical.com/ubuntu lucid partner deb-src http://archive.canonical.com/ubuntu lucid partner NOTE: lucid here is the adjetive part of actual Ubuntu release. Older ones was Karmic Koala and Intrepid Ibex, just to name some examples. Always use the latest adjetive part of Ubuntu relase name here to enable correct repositories. Finally, to install Sun Java and all its dependencies, run: root@l2dcserver:~# aptitude install sun-java6-jdk When its done, make sure you have Sun Java: root@l2dcserver:~# java -version java version "1.6.0_15" Java(TM) SE Runtime Environment (build 1.6.0_15-b03) Java HotSpot(TM) 64-Bit Server VM (build 14.1-b02, mixed mode) Easy with Ubuntu Server, dont you think?

MySQL Server
MySQL is the world's most popular open source database software, with over 100 million copies of its software downloaded or distributed throughout it's history. With its superior speed, reliability, and ease of use, MySQL has become the preferred choice for Web, Web 2.0, SaaS, ISV, Telecom companies and forward-thinking corporate IT Managers because it eliminates the major problems associated with downtime, maintenance and administration for modern, online applications. So far, this is the choice for all L2DC Based Servers admins. At this point, we will not aim for any specific configurations, like tweaking memory usage, setting a separate HD for database, response time and changing sql engine. This will be a basic and secure setup for start. Install it by running: root@l2dcserver:~# aptitude install mysql-server You need increase max_connections on /etc/mysql/my.cnf to avoid MySQL locks for multiple connections. max_connections = 300 Now run MySQL security script: root@l2dcserver:~# mysql_secure_installation This will remove test table and user, reset privileges and put your MySQL in production state. Once installed, MySQL will be automatically installed using default settings. And you will be able to login on its console and creating a database l2dc and grant all privileges on l2dc user to that database. NOTE: As a basic setup, this fits well. On advanced installs, we can use separated databases for loginserver, gameservers and communityservers. Log in on MySQL console and enter this settings: root@l2dcserver:~# mysql -u root -p mysql> CREATE USER 'l2dc'@'localhost' IDENTIFIED BY 'YOURPASSWORD'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT USAGE ON * . * TO 'l2dc'@'localhost' IDENTIFIED BY 'YOURPASSWORD' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ; Query OK, 0 rows affected (0.00 sec) mysql> CREATE DATABASE IF NOT EXISTS `l2dc` ; Query OK, 1 row affected (0.00 sec) mysql> GRANT ALL PRIVILEGES ON `l2dc` . * TO 'l2dc'@'localhost'; Query OK, 0 rows affected (0.00 sec) mysql> quit; Bye NOTE: Pay attention on YOURPASSWORD on lines 1 and 2. That will the chosen password for l2dc user. Restart MySQL: root@l2dcserver:~# service mysql restart Recommended reading: https://help.ubuntu.com/9.10/serverguide/C/mysql.html

OPTIONAL Features on L2DC Requirements Setup


Optional - Java Optimization
Java settings are quite personal. Your Server can do best with your particular settings, no settings at all or just one or two starup line optimizations. Here, I will show you what ones I actually use and a official explanation about each one. Important: I run a dedicated Production Server with two Intel i7 Quad core CPU (8 cores total) and 12 GB RAM DDR3. Keep that in mind when applying those settings to your own System. Read each setting explanation carefully. GameServer?_loop.sh java -server -Djava.util.logging.manager=com.l2dc.util.L2LogManager -Xms2048m -Xmx5000m -Xmn512m -Xss128k -XX:ParallelGCThreads=6 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=8 -XX -server Pretty obvious... This enables build-in optimization to run on Server-class machines. -Xmn512g Configures a large heap for the young generation (which can be collected in parallel), again taking advantage of the large memory system. It helps prevent short lived objects from being prematurely promoted to the old generation, where garbage collection is more expensive. -Xss128k

4 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository


Reduces the default maximum thread stack size, which allows more of the process' virtual memory address space to be used by the Java heap. -XX:ParallelGCThreads=6 Reduces the number of garbage collection threads. The default would be equal to the processor count, which would probably be unnecessarily high on a 32 thread capable system. I set this to 6 cause I dont want to use all my 8 cores for GC. -XX:+UseConcMarkSweepGC -XX:+UseParNewGC Selects the Concurrent Mark Sweep collector. This collector may deliver better response time properties for the application (i.e., low application pause time). It is a parallel and mostly-concurrent collector and and can be a good match for the threading ability of an large multi-processor systems. -XX:SurvivorRatio=8 Sets survivor space ratio to 1:8, resulting in larger survivor spaces (the smaller the ratio, the larger the space). Larger survivor spaces allow short lived objects a longer time period to die in the young generation. -XX:TargetSurvivorRatio=90 Allows 90% of the survivor spaces to be occupied instead of the default 50%, allowing better utilization of the survivor space memory. -XX:MaxTenuringThreshold=31 Allows short lived objects a longer time period to die in the young generation (and hence, avoid promotion). A consequence of this setting is that minor GC times can increase due to additional objects to copy. This value and survivor space sizes may need to be adjusted so as to balance overheads of copying between survivor spaces versus tenuring objects that are going to live for a long time. The default settings for CMS are SurvivorRatio?=1024 and MaxTenuringThreshold?=0 which cause all survivors of a scavenge to be promoted. This can place a lot of pressure on the single concurrent thread collecting the tenured generation. -XX:+AggressiveOpts? Turns on point performance optimizations that are expected to be on by default in upcoming releases. The changes grouped by this flag are minor changes to JVM runtime compiled code and not distinct performance features (such as BiasedLocking? and ParallelOldGC). This is a good flag to try the JVM engineering team's latest performance tweaks for upcoming releases. Note: this option is experimental! The specific optimizations enabled by this option can change from release to release and even build to build. You should reevaluate the effects of this option with prior to deploying a new release of Java. Recommended reading: http://java.sun.com/performance/reference/whitepapers/tuning.html

Optional - MySQL Optimization


MySQL optimization is an art. We have several tools available to help us doing that, or you can even buy MySQL official support. Here, we will NOT define anything final about Server configuration preferences about Database Engines. Some experienced admins prefer MyISAM and some prefer InnoDB. Personally, I use InnoDB cause I have lots of RAM to spare and I think the final result is faster responses. A friend of mine can hold 3.5k players on an L2DC Server with a quite simple and memory-saving MyISAM settings. I will give an official explanation about each engines (from Wikipedia) and our recommended ways to initially optimizes it. Run mysqltuner script each two days to have sure everything is doing fine, and make necessary adjustments.

MyISAM
MyISAM is the default storage engine for the MySQL relational database management system. It is based on the older ISAM code but has many useful extensions. The major deficiency of MyISAM is the absence of transactions support. Therefore in recent MySQL versions, the InnoDB engine has widely started to replace MyISAM to allow additional referential integrity constraints, and higher concurrency. Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. MySQL uses a .frm file to store the definition of the table, but this file is not a part of the MyISAM engine, but instead is a part of the server. The data file has a .MYD (MYData) extension. The index file has a .MYI (MYIndex) extension. Lets start by getting pre configured files and editing them. root@l2dcserver:~# cp -a /usr/share/doc/mysql-server-5.1/examples/my-large.cnf.gz /etc/mysql/ root@l2dcserver:~# gzip -d /etc/mysql/my-large.cnf.gz Now, edit the file /etc/mysql/my-large.cnf and add or correct the following lines on [mysqld] section: Important: This section was removed in order to preserve some L2DC Servers MySQL Setup by Admins request in a Public Version of this guide. Im sorry for this. If you set a spare disk for MySQL installation now its time to configure it. Assuming your spare disk was mounted as /database (you can ask for this on Server initial setup), enter proper datadir setting on your [mysqld] section: datadir = /database/mysql When everything is correctly done, backup your original my.cnf and let our settings take place: root@l2dcserver:~# mv /etc/mysql/my.cnf /etc/mysql/my.cnf.backup root@l2dcserver:~# mv /etc/mysql/my-large.cnf /etc/mysql/my.cnf A MySQL Server restart will take care of new settings: root@l2dcserver:~# service mysql restart Remember fine tunning your MySQL Server running mysqltuner script every two days.

InnoDB
InnoDB is a storage engine for MySQL, included as standard in all current binaries distributed by MySQL AB. Its main enhancement over other storage engines available for use with MySQL is ACID-compliant transaction support [ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee that database transactions are processed reliably. The concept of ACID is to evaluate databases and application architecture. In the context of databases, a single logical operation on the data is called a transaction. For example, a transfer of funds from one bank account to another, even though that might involve multiple changes (such as debiting one account and crediting another)], similar to PostgreSQL, along with foreign key support (Declarative Referential Integrity). InnoDB became a product of Oracle Corporation after their acquisition of Innobase Oy in October 2005. The software is dual licensed; it is distributed under the GNU General Public License, but can also be licensed to parties wishing to combine InnoDB in proprietary software. Please note InnoDB consumes a lot more RAMtham MyISAM. This setup is based on a dedicated 4GB for MySQL. Lets start by getting pre configured files and editing them. root@l2dcserver:~# cp -a /usr/share/doc/mysql-server-5.1/examples/my-innodb-heavy-4G.cnf.gz /etc/mysql/ root@l2dcserver:~# gzip -d /etc/mysql/my-innodb-heavy-4G.cnf.gz Now, edit the file /etc/mysql/my-innodb-heavy-4G.cnf and add or correct the following lines: Important: This section was removed in order to preserve some L2DC Servers MySQL Setup by Admins request in a Public Version of this guide. Im sorry for this. If you set a spare disk for MySQL installation now its time to configure it. Assuming your spare disk was mounted as /database (you can ask for this on Server initial setup), enter proper datadir setting on your [mysqld] section: datadir = /database/mysql When everything is correctly done, backup your original my.cnf and let our settings take place: root@l2dcserver:~# mv /etc/mysql/my.cnf /etc/mysql/my.cnf.backup root@l2dcserver:~# mv /etc/mysql/my-innodb-heavy-4G.cnf /etc/mysql/my.cnf A MySQL Server restart will take care of new settings: root@l2dcserver:~# service mysql restart

InnoDB is not the default database engine from L2DC SQL files. To make our life easier, I will share a script which automate the process of changing default database engine on project SQL files. Create the file dbchange.sh, set it as executable and paste this script on it. #!/bin/bash # Changing database engine from L2DC default MyISAM to InnoDB. find /home/l2dc/Server/sql -maxdepth 1 -name '*.sql' | xargs perl -i.bkp -p -e 's/MyISAM/InnoDB/ig;' rm -rf /home/l2dc/Server/sql/*.bkp echo Done Run it before install/update your database with database_installer.sh

Optional - MySQLTuner
MySQLTuner is a script written in Perl that will assist you with your MySQL configuration and make recommendations for increased performance and stability. Within seconds, it will display statistics about your MySQL installation and the areas where it can be improved. Its a good idea run it every two days on fresh installations to keep tweaking MySQL settings on Server restart/updates. Download it using: wget mysqltuner.pl Set script as executable: chmod u+x mysqltuner.pl Run it: ./mysqltuner.pl Enjoy. Recommended reading: http://blog.mysqltuner.com/

Optional - phpMyAdmin + Apache2 WebServer?


phpMyAdmin is a free software tool written in PHP intended to handle the administration of MySQL over the World Wide Web. phpMyAdmin supports a wide range of operations with MySQL. The most frequently used operations are supported by the user interface (managing databases, tables, fields, relations, indexes, users, permissions, etc), while you still have the ability to directly execute any SQL statement. Its good have such tool installed if you dont have other way to handle your database. Setting Admin access for example can be a pain if you dont know the correct MySQL command. This tool will make this far easier, and painless. NOTE: Do not forget to temporarily stop OSSEC service when dealing with tool. As said before, OSSEC may misunderstand you and lock you out of your system for 20 minutes. phpMyAdmin depends on Apache Web Server to run. Install it by running:

5 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

root@l2dcserver:~# aptitude install phpmyadmin apache2 Answer install questions carefully and dont forget to set Apache as default http engine. You will need MySQL root password. IMPORTANT: Many web scanners seek for hostname/phpmyadmin on web trying to guess vulnerable phpMyAdmin installations or passwords. To avoid that, you will edit phpmyadmin alias on your system and keep that information secret. Edit /etc/phpmyadmin/apache.conf and configure this line: Change Alias /phpmyadmin /usr/share/phpmyadmin For something like Alias /secretdbaccess /usr/share/phpmyadmin Them restart Apache: root@l2dcserver:~# service apache2 restart When installed, lets open the port for it. root@l2dcserver:~# ufw app list Available applications: Apache Apache Full Apache Secure OpenSSH root@l2dcserver:~# ufw allow apache Rule added root@l2dcserver:~# ufw enable Command may disrupt existing ssh connections. Proceed with operation (y|n)? y Firewall is active and enabled on system startup For now on, you will login using http://yourserver/secretdbaccess Try avoid login with your MySQL root account. l2dc user is sufficient. NOTE: We strongly suggest use a SSH tunnel to connect and use your phpMyAdmin installation. Check SSH section for details. NOTE: If you want to use default web installation for you own webpage, just start adding your files to /var/www/ folder. WE do NOT encourage this kind of behavior. Its far easier, cheaper and secure rent a webhost to handle your Server Webpage. For those who want to run a local WebServer? on a Production environment, lets try harden Apache 2 WebServer? tro deliver less information for a possible attacker as possible. Edit /etc/apache2/conf.d/security and change following lines: ServerTokens Prod ServerSignature Off If you dont want to run an web server, or use phpMyAdmin very often, turn Apache off and close its port: root@l2dcserver:~# service apache2 stop root@l2dcserver:~# ufw deny apache Recommended reading: https://help.ubuntu.com/9.10/serverguide/C/httpd.html

Optional - Apache ModSecurity?


ModSecurity? is a web application firewall that can work either embedded or as a reverse proxy. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real-time analysis. It is also an open source project that aims to make the web application firewall technology available to everyone. NOTE: ModSecurity? can lead to several errors on accessing your WebServer?. Have this in mind when hardening security using this tool. When correctly installed, check his logs at /var/log/apache2/modsec_audit.log to ensure everything is fine and modsec arent blocking legitimate traffic. I recommend you rent a separate WebServer? for you Server. Its cheaper and more secure. Let them worry about Apache Security Install it by using: root@l2dcserver:~# aptitude install libapache2-mod-security2 Now, get an config file and rules example from package and install it. root@l2dcserver:~# cp -a /usr/share/doc/mod-security-common/examples/modsecurity.conf-minimal /etc/apache2/conf.d/modsecurity.conf root@l2dcserver:~# cp -a /usr/share/doc/mod-security-common/examples/rules/* /etc/apache2/conf.d/modsecurity/ Now, edit config files and enable rules parsing. Uncomment optional_rules option if you want use them. /etc/apache2/conf.d/modsecurity.conf <Ifmodule mod_security2.c> Include conf.d/modsecurity/*.conf #Include conf.d/modsecurity/optional_rules/*.conf </Ifmodule> Delete redundant files wich will lead to a parse error. root@l2dcserver:~# rm /etc/apache2/conf.d/modsecurity/LICENSE root@l2dcserver:~# rm /etc/apache2/conf.d/modsecurity/CHANGELOG root@l2dcserver:~# rm /etc/apache2/conf.d/modsecurity/README Prepare logs folder. root@l2dcserver:~# ln -s /var/log/apache2/ /etc/apache2/logs Now, here is an important setting. Lets mask your Apache as an MS IIS Server. root@l2dcserver:~# nano /etc/apache2/conf.d/modsecurity/modsecurity_crs_10_config.conf Change this line... SecServerSignature "Apache/2.2.0 (Fedora)" For this one. SecServerSignature "Microsoft IIS 5.0" Script kiddies will lose hours trying to exploit an IIS Server. :D Now, try nmap -v -A localhost and check /var/log/apache2/modsec_audit.log to see modsec detecting and blocking nmap scan. Recommended reading: http://www.modsecurity.org/documentation/modsecurity-apache/2.5.12/html-multipage/

Optional - FTP Server


Probably the most secure and fastest FTP server for UNIX-like systems. You might like this if you want to host a patcher/loader for your server or the entire client. Serving big files (2GB+) overloads and lead to DoS on Apache when multiple people try download that kind of files. This is not a problem for vsFTPd Server. Install vsFTPd by running: root@l2dcserver:~# aptitude install vsftpd By default, vsFTPd is installed in anonymous mode. The default location for FTP served files if /home/ftp. If you want just share your files, just put them there. If you need do some adjustments on /etc/vsftpd.conf file, remember to read carefully vsFTPd documentation to avoid too permissive configurations which will make your FTP Server a warez deposit. Be warned. With all files moved to /home/ftp/ directory, now set root ownership and allow files as world readble: root@l2dcserver:~# chown root:root /home/ftp/ -R root@l2dcserver:~# chmod 555 /home/ftp/ -Rf Now, open FTP port on your firewall. root@l2dcserver:~# ufw allow 21

Recommended reading: https://help.ubuntu.com/9.10/serverguide/C/ftp-server.html

Optional - eBox - HIGHLY *NOT* RECOMMENDED


I really do NOT like this software on a Production Server, and I dont recommend it. But eBox can be a relief for unexperienced admins who are trying Linux and are still addicted for graphical interfaces. This really helps a bit. eBox Platform can act as a Gateway, Infrastructure Manager, Unified Threat Manager, Office Server, Unified Communication Server or a combination of them. One single, easy-to-use platform to manage all your network services. Check for eBox modules and install needed ones by running: root@l2dcserver:~# apt-cache rdepends ebox | uniq root@l2dcserver:~# aptitude install ebox ebox-network ebox-firewall NOTE: eBox will install an alternative Apache server, perl-based, and a PostgreSQL Server (!?) as dependencies. During the installation you will be asked to supply a password for the ebox user. Choose a really good one. An important thing to remember when using eBox is that when configuring most modules there is a Change button that implements the new configuration. After clicking the Change button most, but not all, modules will then need to be Saved. To save the new configuration click on the Save changes link in the top right hand corner.

6 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository


Open https port by doing: root@l2dcserver:~# ufw allow 443 After installing eBox the web interface can be accessed from: https://yourserver/ebox Recommended reading: https://help.ubuntu.com/9.10/serverguide/C/ebox.html

L2DC HOME SETUP


l2dc user l2dc home directory Subversion Apache Ant Compiling and Installing Server Alternative: Uploading your files to Server using rsync approach.

Creating L2DC User and Required Directories


Production Servers are advised to always run processes with low level users. This is very useful to avoid more complex security issues. On our example, lets create an user l2dc to run GameServer?. root@l2dcserver:~# adduser l2dc Lets enable l2dc login on our Server. Edit /etc/ssh/sshd_config and modify this line: AllowUsers user l2dc Now, install your public key on l2dc user to be able to login as this user. Run this command locally. cyberfox@firefox:~$ ssh-copy-id -i /home/cyberfox/.ssh/id_rsa.pub l2dc@192.168.0.70 Now, we will take control of l2dc user to manage his home directory: root@l2dcserver:~# su - l2dc NOTE: You can also open a terminal and SSH to server as l2dc user, if desired. cyberfox@firefox:~$ ssh 192.168.0.70 -l l2dc Once logged in, lets start creating directories. l2dc@l2dcserver:~$ mkdir Sources Sources/L2DC Server Backup Scripts Basic home setup done.

Subversion
In software development, Subversion (SVN) is a version-control system initiated in 2000 by CollabNet? Inc. Developers use Subversion to maintain current and historical versions of files such as source code, web pages, and documentation. Its goal is to be a mostly-compatible successor to the widely used Concurrent Versions System (CVS). To access our SVN, we need install SVN first. root@l2dcserver:~# aptitude install subversion When done, change to l2dc user, navigate thru /home/l2dc/Sources/L2DC directory and checkout project: Important: Edited to remove our SVN Repo. I used L2J one instead. Adapt it to your needs. l2dc@l2dcserver:~/Sources/L2DC$ svn checkout http://www.l2jserver.com/svn/trunk/L2_GameServer l2dc@l2dcserver:~/Sources/L2DC$ svn checkout http://www.l2jdp.com/svn/trunk/datapack_development

Apache Ant - Java commandline compiler


Apache Ant is a software tool for automating software build processes. It is similar to Make but is implemented using the Java language, requires the Java platform, and is best suited to building Java projects. The most immediately noticeable difference between Ant and Make is that Ant uses XML to describe the build process and its dependencies, whereas Make has its Makefile format. By default the XML file is named build.xml. As we already have Sun Java JDK installed, lets just install Ant: root@l2dcserver:~# aptitude install ant Yeah, lots of dependecies... Now, with ant installed, we are able to compile and unzip compiled sources on our Server directory. Change to l2dc user and do the following: Important: This directories are based on L2DC project repository. Adjust it accordingly to reach L2J ones. l2dc@l2dcserver:~$ ant -buildfile Sources/L2DC/dragonclaw/trunk/core/build.xml l2dc@l2dcserver:~$ ant -buildfile Sources/L2DC/dragonclaw/trunk/datapack/build.xml l2dc@l2dcserver:~$ ant -buildfile Sources/L2DC/dragonclaw/trunk/L2DC_CommunityServer/build.xml With all packages compiled, unzip them on Server directory: Important: This directories are based on L2DC project repository. Adjust it accordingly to reach L2J ones. unzip -qo /home/l2dc/Sources/L2DC/dragonclaw/core/build/l2dc-server.zip -d /home/l2dc/Server/ unzip -qo /home/l2dc/Sources/L2DC/dragonclaw/datapack/build/L2DC_DataPack.zip -d /home/l2dc/Server/ unzip -qo /home/l2dc/Sources/L2DC/dragonclaw/trunk/L2DC_CommunityServer/build/l2dc-community.zip -d /home/l2dc/Server/ I really make your life easier, dont I? Now run database installer.sh l2dc@l2dcserver:~$ cd Server/tools/ Make database_installer.sh executable l2dc@l2dcserver:~/Server/tools$ chmod +x database_installer.sh Run it l2dc@l2dcserver:~/Server/tools$ ./database_installer.sh Enter needed information and your server might be correctly installed. Now, opening its ports and starting server. Login Server root@l2dcserver:~# ufw allow 2106 Rule added Game Server root@l2dcserver:~# ufw allow 7777 Rule added root@l2dcserver:~# ufw status Status: active To -OpenSSH 2106 7777 Action -----ALLOW ALLOW ALLOW From ---Anywhere Anywhere Anywhere

You are and L2DC Admin, edit your config files now and prepare everything to Server startup. Now Server is fully installed. To start login server, game server and community server, set them as executables and run it. l2dc@l2dcserver:~$ chmod +x Server/gameserver/GameServer_loop.sh Server/login/LoginServer_loop.sh Server/community/CommunityServer_loop.sh Run Servers and have fun!

Alternative: Update Server - RSync Approach


Personally, I prefer build Server locally and send it to GameServer?. A very good way to do this is create a similar directory tree locally and rsync them to Server. Personally, I use L2DCServer directory and create Server and Sources directories inside it. When Server is compiled and correctly setup, I send it to Server. Take a look at this example: Install RSync, if needed. root@firefox:~# aptitude install rsync Them

7 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

cyberfox@firefox:~$ rsync -av --rsh="ssh -l l2dc" /home/cyberfox/L2DCServer/Server l2dc@192.168.0.70:/home/l2dc/Server This will automatically uses your SSH key to create an encrypted tunnel thru Server and transfer only modified/new files. A must :) Setting up your Server correctly is very important, but is just the first step. On next sections, i will try make your life easier as an L2DC Admin.

MANAGING YOUR SERVER


Setting your char as GM Automatic MySQL routines Announces on console Login and Gameserver Startup scripts.

Setting your char as GM


Easier and faster them phpMyAdmin approach: l2dc@l2dcserver:~$ mysql -u l2dc -p mysql> USE l2dc; mysql> UPDATE characters SET accesslevel=127 WHERE char_name="YOURCHARNAME"; mysql> bye;

Automatic MySQL Server sanity check and backup


Create a sqlbackup.weekly file, give it execution permission and put it in /etc/cron.weekly to automate its process. This will weekly check for MySQL database errors on all tables and try fix them. When done, the script will store a SQL dump on /home/l2dc/Backup properly dated. sqlbackup.sh #!/bin/bash # Server backup. This script will check MySQL data integrity and create a backup from it. # Cyberfox - cyberfox@l2-adrenaline.com # SQL check - mysqlcheck --help for full details / tweaks mysqlcheck -A -a -c -e -r -o -s -u root -pYOURROOTSQLPASSWD --auto-repair # Backup mysqldump --databases l2dc --user=YOURBDUSER --password=YOURDBPASSWD > /home/l2dc/Backup/l2dc.weekly.backup_`date '+%d%b%y_%H%M'`.sql Set it as executable and move it to /etc/cron.weekly/ directory. root@l2dcserver:~# chmod +x sqlbackup.weekly root@l2dcserver:~# mv sqlbackup.weekly /etc/cron.weekly/

Announcing Server Restarts via commandline


This is useful when you are working on Server console (terminal) and want warn your users about a imminent Server restart. Create a announce.sh file on your root folder. Set it as executable. Install required expect package: root@l2dcserver:~# aptitude install expect /root/announce.sh #!/bin/bash # Announce script to L2DC Servers. # Cyberfox - cyberfox@l2-adrenaline.com expect -c " spawn telnet localhost YOURTELNETPORT expect \"Password:\" send \"YOURTELNETPASSWD\r\" expect \"\[L2J\]\" send \"announce Attention: The Server will restart automatically in 2 minutes. Go to a safe place and logout. You can login again in 5 minutes. Thank you.\r\" sleep 1 send \"quit\r\" " > /dev/null

Sending Logfiles via Email Section


This can be useful for some admins who might have problems accessing their Servers for some time. Anyways, the logic can be applied to any log on system, so I think you might use it. Lets assume you want to receive Server stdout.log and chat.log on a daily basis. serverlogs.daily #!/bin/bash # Stdout.log files. cat /home/l2dc/Server/gameserver/log/*out.log > /tmp/email1std.txt mail YOUR@EMAIL.HERE -s 'SERVERNAME Stdout Log' < /tmp/email1std.txt rm -f /tmp/email1std.txt # Sending Chat.log (if needed, same logic) cat /home/l2dc/Server/gameserver/log/chat.log > /tmp/email2std.txt mail YOUR@EMAIL.HERE -s 'SERVERNAME Stdout Log' < /tmp/email2std.txt rm -f /tmp/email2std.txt Set it as executable and move it to /etc/cron.daily/ directory. root@l2dcserver:~# chmod +x serverlogs.daily root@l2dcserver:~# mv serverlogs.daily /etc/cron.daily/

Login and Gameserver Management Scripts


Create /etc/init.d/gameserver and set it as executable '/etc/init.d/gameserver

8 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

#!/bin/bash # # gameserver Starts L2DC Server # # chkconfig: - 66 34 # description: L2DC Server # processname: gameserver set -e DESC="GameServer" L2DIR="/home/l2dc/Server" # Directory with L2DC L2USER="l2dc" # User under which L2DC is running GADDR="127.0.0.1" # IP address of Game server GPORT="YOURGAMESERVERPORT" # Port of game server GCPORT="YOURTELNETPORT" # Telnet port of game server GPASS="YOURTELNETPASS" # Password for telnet to game server DOWNTIME="" test $# -gt 1 && DOWNTIME=$(echo $2 | sed -e 's/[^0-9]*//g') test "$DOWNTIME" || DOWNTIME=10 # Default shutdown/restart time ############################# g_start() { echo -n " gameserver: " if nc -z $GADDR $GPORT ; then echo "already running" else cd "$L2DIR/gameserver" || exit 1 sudo -u $L2USER ./GameServer_loop.sh & echo "started" fi }

g_stop() { ACTION=$1 echo -n " gameserver: " if ! nc -z $GADDR $GPORT ; then echo "not running" else expect -c " spawn telnet $GADDR $GCPORT expect \"Password:\" send \"$GPASS\r\" expect \"\[L2J\]\" send \"announce Server will $ACTION in $DOWNTIME seconds\r\" sleep 1 send \"$ACTION $DOWNTIME\r\" sleep 1 send \"quit\r\" " > /dev/null for ((i=$DOWNTIME ; i>0 ; i--)) ; do echo -ne "\r gameserver: $i \r" sleep 1 done echo -n " gameserver: " test "$ACTION" = "restart" && echo "restarted" || echo "stopped" fi } g_shutabort() { echo -n " gameserver: " if ! nc -z $GADDR $GPORT ; then echo "not running" else expect -c " spawn telnet $GADDR $GCPORT expect \"Password:\" send \"$GPASS\r\" expect \"\[L2J\]\" sleep 1 send \"abort\r\" sleep 1 send \"quit\r\" " > /dev/null echo "shutdown or restart aborted" fi }

g_status() { echo -n " gameserver: " nc -z $GADDR $GPORT && echo "running" || echo "not running" }

###################### cd "$L2DIR" || exit 1 case "$1" in start) echo "Starting $DESC: " g_start ;; stop) echo "Stopping $DESC:" g_stop shutdown ;; restart|force-reload) echo "Restarting $DESC: " g_stop restart ;; status) echo "Status of $DESC:" g_status ;; abort) echo "Aborting shutdown or restart of $DESC:" g_shutabort ;; *) echo "Usage: $0 {start|stop|restart|force-reload|status|abort}" >&2 exit 1 ;; esac exit 0 Now create /etc/init.d/l2dclogin and set it as executable: /etc/init.d/l2dclogin

9 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository

#!/bin/bash # # l2dclogin Starts L2DC LoginServer # # chkconfig: - 65 35 # description: L2DC Login # processname: l2dclogin set -e DESC="L2DCLogin" L2DIR="/home/l2dc/Server" # Directory with L2DC L2USER="l2dc" # User under which L2DC is running LADDR="127.0.0.1" # IP address of Login server LPORT="YOURLSPORT" # Port of login server LCPORT="YOURTELNETLSPORT" # Telnet port of login server LPASS="YOUTELNETLSPASSWD" # his password DOWNTIME="" test $# -gt 1 && DOWNTIME=$(echo $2 | sed -e 's/[^0-9]*//g') test "$DOWNTIME" || DOWNTIME=10 # Default shutdown/restart time ############################# l_start() { echo -n " loginserver: " if nc -z $LADDR $LPORT ; then echo "already running" else cd "$L2DIR/login" || exit 1 sudo -u $L2USER ./LoginServer_loop.sh & echo "started" fi }

l_stop() { echo -n " loginserver: " if ! nc -z $LADDR $LPORT ; then echo "not running" else expect -c " spawn telnet $LADDR $LCPORT expect \"Password:\" send \"$LPASS\r\" expect \"\[L2J\]\" send \"shutdown 1\r\" sleep 1 send \"quit\r\" " > /dev/null echo "stopped" fi }

l_status() { echo -n " loginserver: " nc -z $LADDR $LPORT && echo "running" || echo "not running" }

###################### cd "$L2DIR" || exit 1 case "$1" in start) echo "Starting $DESC: " l_start ;; stop) echo "Stopping $DESC:" l_stop ;; status) echo "Status of $DESC:" l_status ;; *) echo "Usage: $0 {start|stop|status}" >&2 exit 1 ;; esac exit 0 Well done. For now on, you will be able to start and stop login and gameserver by doing: root@firefox:~# service gameserver start root@firefox:~# service gameserver stop root@firefox:~# service l2dclogin start root@firefox:~# service l2dclogin stop

Realtime Logs
We can open one or two local terminals locally, SSH to our Server and start to watch over Server output logs realtime. This is quite easy to do. Using tail -f command. We can watch over any logs this way. The most needed ones are chat.log and stdout.log. You might take a look on GMAudit logs too, just point tail to desired log. Here is an good example: chat.log l2dc@l2dcserver:~$ tail -f -n 200 /home/l2dc/Server/gameserver/log/chat.log stdout.log l2dc@l2dcserver:~$ tail -f -n 200 /home/l2dc/Server/gameserver/log/stdout.log You can close tail with a ctrl + c or use screen command to run multiple logs on same terminal (l2dc@l2dcserver:~$ man screen for details). Personally I open both chat and stdout on two separated terminals. You can watch any system or game logs with that command.

Final Considerations
I think its it. I really hope can help you have a bit more structured and secure Production Servers. I put some of my experience in this guide, but Im not a coder or Linux Guru. I did a LOT of research to provide most complete, secure and good data available, but this guide may have flaws. If you know better ways/fixes to do anything, let me know. Feedback and fixes on this original work are welcome. Thanks for all feedback so far. If you find this guide useful, please consider sending a donation via PayPal? to donations@l2-adrenaline.com. You will be informed of guide updates. Thank you.

Revision History
Revision 1.0 07/03/2010 Initial release. Revision 1.1 08/03/2010 Added Realtime Logs Section. Revision 1.2 11/03/2010 Added Java Optimization Section Added MySQL Optimization Section Added Sending Logfiles via Email Section Revised DynDNS Section Revised Automatic MySQL Server sanity check and backup Section Configurable OSSEC Mail Alerts.

10 de 11

28-03-2010 21:19

L2DCLinuxServerGuidePulicRelease L2 Dragonclaw Repository


Added Repositories configuration from apt to enable partner repo to install Java on newer Ubuntu releases. Added SSH Tunnels section. Revision 1.3 28/03/2010 Added Optional - Apache ModSecurity? General Formatting and cleanup 1st Public Release Version. Thanks to all L2DC Team Members.

11 de 11

28-03-2010 21:19

Das könnte Ihnen auch gefallen