megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Resolve permission error while SSH-ing to AWS EC2 instance from a Linux machine

If you are someone who's trying to access a AWS EC2 instance via SSH using a private key from a linux machine, you might have or will come across this error:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'your-aws-private-key.pem' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: your-aws-private-key.pem
Permission denied (publickey).

Why am I getting this?

From what I have read, EC2 instances will simply not accept a private key that are publicly visible to others especially if it's somewhere stored in your Desktop or Downloads folder.

So basically, your private key should be accessible to others.

Oh, how can I fix it?

It's pretty straightforward, you just have to make sure that the private key is read-only like this:

chmod 400 your-aws-private-key.pem

After that, try connecting again and it should work fine!

Hope you found this tip useful!

Install PFX certificate on a Linux server

I would consider this as an extended post to my previous post that I had written six months ago.

A PFX Certificate usually contains the following in PKCS#12 format:

  • The actual certificate.
  • The private key to the certificate.
  • The Intermediate authority certificate that ensures the trustworthiness of the certificate.

To extract all those files, here are the steps that I have documented:

Note

If the .PFX file prompts you for a passphrase, please check with your project manager or client regarding this information.

Extract the Encrypted Private Key

openssl pkcs12 -in <filename.pfx> -nocerts -out encrypted.key

Extract RSA Private Key

openssl rsa -in encrypted.key -out private.key

Extract Certificate

openssl pkcs12 -in <filename.pfx> -clcerts -nokeys -out certificate.crt

Extract Combined Chain Certificate (Optional)

openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > combined_chain_certificate.crt

Once you are done extracting all the required files, you can add the certificates like this:

Apache configuration:

SSLCertificateFile /path/to/certificate.crt
SSLCertificateKeyFile /path/to/private.key

# Optional, if you have it, else skip.
SSLCertificateChainFile /path/to/combined_chain_certificate.crt

Test if it works:

apachectl configtest
systemctl restart httpd

Nginx configuration:

# If you don't have a combined chain certificate:
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;

# If you have a combined chain certificate:
ssl_certificate /path/to/combined_chain_certificate.crt
ssl_certificate_key /path/to/private.key;

Test if it works:

nginx -t
systemctl restart nginx

Hope you found this tip useful.

Install Microsoft SQL Server Driver for PHP on Amazon Linux 2

Recently, I tried to install Microsoft SQL Server driver for PHP on Amazon Linux and searching on how-to do was really annoying.

I read a few articles on StackOverflow and found some samples on GitHub Gists and thought of sharing on how I installed it.

Prerequisites

  1. Amazon Linux 2 installed.
  2. Ensure the ports 80 and 443 are open on your instance.
  3. PHP >= v5.6 and the following extensions: php-devel, php-pear, php-pdo, and php-xml.
  4. Know-how on using the terminal.

Installation steps

These are the commands used to install the SQL Server driver:

sudo su
sudo yum-config-manager --add-repo https://packages.microsoft.com/config/rhel/7/prod.repo
sudo yum update
sudo ACCEPT_EULA=Y yum install -y msodbcsql mssql-tools unixODBC-devel re2c gcc-c++ gcc
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv

Modify php.ini

You can either to go to your php.ini file and add the extension=sqlsrv extension or add it like this:

echo "extension=sqlsrv" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
echo "extension=pdo_sqlsrv" >> /etc/php.d/30-pdo_sqlsrv.ini

Restart the service

Ensure that the server can connect and restart the service:

sudo setsebool -P httpd_can_network_connect_db 1
sudo systemctl restart httpd && sudo apachectl restart

Next, run the following the command to see that both pdo_sqlsrv and sqlsrv are installed:

php -m | grep "sqlsrv"`

Test if the driver works

Create a test.php file in your root directory and copy-paste this snippet to test if it works:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$serverName = "YOUR_DB_HOST";
$connectionOptions = array(
    "Database" => "YOUR_DB_NAME",
    "Uid" => "YOUR_DB_USER",
    "PWD" => "YOUR_DB_PASSWORD"
);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if($conn === false ) {
    print "Connected successfully."; 
} else {
    print "Error while connecting to server.";
}
?>

Hope you found this tip useful!

My thoughts on using Visual Studio Code

My experiences on what made me like using Visual Studio Code.

Ever since my university days, I've always used Sublime Text for any sort of text editing and programming tasks, in general.

Despite the annoying "Subscription" dialog box, I like it because it's lightweight, simple and had nice keybindings that made it much more productive.

This week, I thought of taking Visual Studio Code for a drive, not because many developers are using it but personally, I wanted to know if it can be better than Sublime Text.

The answer is yes, it is and here's what I have experienced so far.

Portability

What I like at first is that, it's cross-platform and has support for different operating systems in various architectures. At work, I use Windows 10 and at home, I use Fedora 35 Workstation and it runs fine on both operating systems.

Intellisense, Intellisense, Intellisense...

Intellisense is a term used by Microsoft that includes various features like: code completion, code hinting, method parameter information and more. By default, the editor supports Intellisense for JavaScript, TypeScript, HTML and CSS. But if you install different programming language extensions like Python, PHP, Golang and so on, you'll be able to configure your editor to have a much more richer experience.

At work, I write PHP code and use Laravel framework to develop web applications, I installed the following extensions to make my coding experience much more productive:

  1. PHP Intelephense (bmewburn.vscode-intelephense-client)
  2. phpfmt (kokororin.vscode-phpfmt)
  3. Laravel Snippets (onecentlin.laravel-blade)

Sublime Text and Vim Keybindings

If you've never used Vim, please go ahead and try. I believe that every programmer should try using VIM instead of fearing the keybindings (like :q) as they were developed for a reason.

But unlike Vim, Sublime Text keybindings are quite fun especially when you want to duplicate a line of code, indent lines of code, matching multiple instances of the same keyword and modifying them with multiple cursors at the same time.

Try installing these extensions and see if you like them:

  1. Vim Emulation for Visual Studio Code (vscodevim.vim)
  2. Sublime Text Keymap and Settings Importer (ms-vscode.sublime-keybindings)

Integrated Terminal

You can use different type of shells like Windows Powershell, Command Prompt, Git Bash and much more. Besides IMO, I found that using the integrated terminal was quite productive as I didn't have to switch windows in between.

Looks minimal

When it comes to UI/UX, the word minimalism is often subjective but I guess Microsoft embraced the principles of minimalism for this editor.

Lots of extensions and great support

Thanks to the open source community, there are hundreds and thousands of extensions out there. By installing various extensions, you can make it your own editor and that part fascinates me.

Besides, it's developed by Microsoft, so it definitely has a strong support and community out there.

Conclusion

I guess the simplicity and flexibility of this editor is what made it more powerful amongst the developer community.

Now, I'm not going to say that it's a flawless editor, just like every other pieces of software, it does have it's cons. However, I decided to try out Visual Studio Code for a while and see how it goes for me.

If it doesn't then maybe I might write a post about why I didn't like using it, in the future.

Hope you liked reading this article.

Logging client IP addresses on Apache server

If you want to log the actual client IP address, you need to extract the X-Forward-For header from the request and in order to do that, you need to make a tiny edit in your httpd.conf file.

  1. Go to /etc/apache2/conf or /etc/httpd/conf and open httpd.conf file.
  2. Search for the string that starts with: LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined.
  3. Modify the %h to %{X-Forwarded-For}i. Now, it should look like this: LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined.
  4. Test the config to ensure that there are no typos by typing: apachectl configtest.
  5. Save and restart the service by typing: systemctl restart httpd or systemctl restart apache2.
  6. In your terminal, type tail -f /var/log/httpd/access.log and you'll be seeing the client IP being logged in your logs.

Hope you found this tip useful!

Using IIFE in JavaScript

IIFE a.k.a Immediately-Invoked Function Expression — is a way to execute functions as soon as the function is created.

Using IIFE, you can easily isolate declared variables away from the global scope.

This is how the syntax would look like:

// ES5 Standard
let foo = (function(){
    let message = "Hello world"
    console.log(message);
})();

They can be defined with arrow functions as well:

// ES6 Standard
let foo = (() => {
    let message = "Hello world"
    console.log(message);
})();

According to MDN Docs, it's a design pattern a.k.a Self-Executing Anonymous Function. There are two parts to this:

  1. The function that's enclosed within the Grouping Operator (), which would prevent it from polluting the global space and access to the variables within it's scope.

  2. The (); will create the Immediately Invoked Function Expression on-the-fly.

When to use it?

There are many interesting cases such as if you are following the Module Pattern especially if you want to avoid polluting the global namespace or just that you don't want your code to interfere with other code thus ensures code safety.

Readings

9th August 2022 — Blogmarks

7th August 2022 — Blogmarks

  • ImHex — A Hex Editor for Reverse Engineers, Programmers and people who value their retinas when working at 3 AM.
  • Bisqwit — Found this cool programmer on YouTube who writes game emulators and 3D renderers from scratch. Inspiring guy!
  • Web Browser Engineering — I came across this site recently and it was quite intriguing. I really wanted to get my hands-on this tutorial and learn more about Web Browsers. Thank you Pavel Panchekha for this!