As a developer, efficiently managing source code with Git is an essential skill. Connecting to hosted Git repositories via SSH offers convenient authentication and data transfer compared to HTTPS. However, organizations may restrict the standard SSH port 22. Thankfully, specifying an alternate SSH port when adding a Git remote is straightforward.

In this comprehensive 3200+ word guide, you‘ll learn:

  • SSH key generation best practices
  • Comparing default port 22 vs other ports
  • Detailed process to add Git remotes with custom ports
  • Troubleshooting connectivity issues
  • Next steps for using SSH Git remotes in production

Whether you need to comply with obscure IT policies or work around quirky hosting constraints, this guide has you covered. Follow along as we dive deep on SSH-powered Git remote access through non-standard ports from a professional developer‘s perspective.

Developer-Focused SSH Key Generation

First, we need to ensure SSH keys are configured properly to avoid headaches down the road.

SSH keys authorize Git connections to remote servers without using passwords, making authentication much smoother. However, best practices around SSH key generation are often glossed over.

As a developer, it‘s important to understand and properly manage your SSH keys for passwordless access to Git hosting providers and internal development infrastructure.

Here are key areas developers should focus on for robust SSH key handling:

1. Separate Personal and Work SSH Keys

Many developers start by creating a single default SSH keypair on their machine tied to their personal email address. This allows connecting to public Git hosting providers like GitHub or GitLab via SSH right away with minimal hassle.

However, for enterprise and contract work, associating keys with your personal identity is poor practice and rightfully frowned upon by IT security teams.

Instead, dedicate separate SSH key pairs for business/client work associated with official corporate email addresses. This allows code access to be properly scoped and ideally enables better lifecycle management through centralized IT systems.

Switching between personal and work keys is easy enough through SSH‘s IdentitiesOnly directive or leveraging SSH agent forwarding, a built-in mechanism for securely utilizing keys over network connections.

2. Automate Key Installation

Development teams today need the ability to seamlessly spin up and tear down infrastructure on demand through scripting and configuration management tools like Ansible, Puppet, and Chef.

This automation potential is hindered when developers must manually log into new systems to copy over SSH keys and enable access.

Thankfully, SSH public keys can be installed remotely, allowing complete automation of key deployment. Solutions like Ansible provide modules purpose-built for securely adding keys only to appropriate target accounts.

Invest time as a team to refine this capability early, as it pays dividends down the road allowing development and provisioning pipelines to seamlessly incorporate the SSH key distribution needed for code synchronization.

3. Use SSH Certificate Authority

Managing lots of user accounts across myriad environments is challenging enough without also juggling piles of authorized_keys files. Missed key updates lead to frustrating access failures.

Improve this process by implementing an SSH Certificate Authority (CA) which centrally signs key-based access permissions. Popular options include Hashicorp Vault, Keylime, and Venafi.

With an SSH CA in place, granting or revoking access involves only signing updated certificates rather than pushing public keys to target servers. Keys automatically expire on set schedules based on polynomials.

Modern SSH CAs integrate with identity providers through protocols like OIDC for smoother and more secure management at scale. If working across many distinct environments, the consistency and automation capabilities of SSH CAs are game changing.

4. Enable SSH Agent Forwarding

One downside of using SSH for Git auth is getting prompted for passphrases to unlock keys, which are required to enhance encryption strength. This gets annoying fast, undermining productivity.

Thankfully, SSH agent forwarding allows a sign-in handshake to securely transmit unlocked keys to remote servers as needed through encrypted channels.

Combined with a capable SSH CA to enable single sign on across your entire development infrastructure, passphrase prompts can be eliminated. Push or pull code from any environment without disruption.

If building complex internal development systems, ensure SSH agent forwarding compatibility early on for maximum convenience.

5. Restrict Key Permissions

Developers love firing up new cloud servers to conveniently test things out. Unfortunately convenience often overrides security best practices.

One common mistake is using overly permissive SSH keys granting wider infrastructure access than each developer strictly needs for their tasks. This violates the principle of least privilege and enables lateral movement in the unfortunate case of account compromise.

Combat this by configuring restrictive SSH keys and access controls, limiting each developer solely to the resources and environments essential for their role through tools like Kubernetes‘ RBAC.

Make adherence to key permission scoping and regular rotation part of your team security culture.

Default SSH Port vs Other Ports – An Honest Comparison

Beyond proper handling of SSH keys, understanding tradeoffs between standard and non-standard SSH ports enables better decision making.

Here is an objective comparison of strengths and weaknesses, from the lens of hands-on software developers managing daily coding tasks:

Consideration Default SSH Port 22 Non-Standard SSH Ports
Convenience Simplest remote URLs Require port specifics in Git URLs/config
Compatibility Universally supported May not work on restrictive networks
Security Often restricted via firewall rules Obscurity provides slight extra protection
Transparency Easier to monitor and audit Difficult to identify non-standard ports at scale
Change Effort No modifications needed Alter SSH ports in URL, hosts, config files

In summary:

  • Port 22 SSH access remains the gold standard for frictionless Git remote usage
  • But alternative ports can facilitate access where 22 is intentionally blocked
  • There are some security and audit tradeoffs to consider
  • Use non-standard ports judiciously based on technical constraints

Understanding these technical nuances will help guide your decisioning.

Now let‘s dive into the actual process of configuring alternate SSH ports.

Step-by-Step Guide: Add Git Remote with Other SSH Port

Whether for mandated compliance, quirky hosting restrictions, or unusual infrastructure configurations, here is how to customize your Git SSH port when adding remotes.

Follow these steps:

  1. Check existing SSH keys
  2. Obtain SSH remote URL with custom port
  3. Add remote with git remote add
  4. Update SSH config for persistent simplification (optional)
  5. Confirm remote connectivity

Let‘s examine each step in detail from a developer‘s point of view.

Step 1: Verify SSH Keys

First we‘ll validate proper SSH keys exist so authentication can happen seamlessly.

On your local machine, check for existing SSH keys:

ls -al ~/.ssh

You should see SSH key files present:

> id_rsa id_rsa.pub

If this your first time setting up SSH-based access, generate new keys:

ssh-keygen -t ed25519 -C "your_email@domain.com"

Use your official work email and follow the prompts to create identity keys for this purpose only.

With SSH keys ready, we can focus on remote specifics.

Step 2: Obtain Remote URL with SSH Port

Next, identify the full remote SSH URL with custom port number that you need to connect to.

For example, to access repository myrepo on server git.company.com through port 22222 instead of standard SSH, the URL would be:

ssh://git@git.company.com:22222/myrepo

How you get this exact URL format will vary across Git hosting providers:

  • GitHub – When adding remotes, there is a convenient port field presented in the SSH URL template to customize as needed.

  • DigitalOcean App Platform – Includes SSH port customization when selecting deployment Git remotes within App Spec settings

  • Bare metal & VMs – Manually construct based on server IP and port details

  • Other hosts – Follow provider docs to build SSH remote URLs

At the end, you need the fully formed, specialty SSH URL with proper port to proceed.

Step 3: Add Remote with git remote add

Here we take the crucial step that associates our local repo instance with the remote server location through a friendly alias.

From a terminal session inside your Git repository directory:

git remote add origin ssh://git@git.company.com:22222/myrepo

Here origin becomes the local alias used to reference that remote server location. The full SSH URL includes our port specification.

Double check it was added properly:

git remote -v

You should see your new SSH remote mapped to origin, with port visible:

origin    ssh://git@git.company.com:22222/myrepo (fetch)
origin    ssh://git@git.company.com:22222/myrepo (push)

Success! Your Git repository now recognizes a remote server location accessible through our non-standard SSH port.

Step 4: Simplify Access in SSH Config

Having to reference long, complex SSH URLs is tedious. For convenience, we can optionally store the details in the SSH client configuration file instead for cleaner usage.

Open (or create) your SSH config file:

vi ~/.ssh/config

Add a new host entry:

Host myrepo 
    HostName git.company.com
    User git
    Port 22222
    IdentityFile ~/.ssh/work_id_ed25519

Here we assign the convenient alias myrepo. SSH knows to connect to our alternate port and use our dedicated work SSH key when accessing this host.

Now instead of the full remote SSH URL, we can use just our alias:

git push myrepo main

Much simpler and cleaner! This SSH host alias gets added to your ~/.known_hosts automatically on first connection too.

Step 5: Validate Connectivity

With configuration complete, test connectivity using our simplified alias:

git fetch myrepo
git push myrepo main

The Git commands should interact with our remote repository without issues. The custom SSH port will be utilized behind the scenes!

If having trouble connecting, double check:

  • Correct SSH keys are registered
  • Port number is accurate in all locations
  • Network firewall allows the non-standard port

And that‘s it! SSH-powered access to your Git remote through a custom port is now complete.

Troubleshooting SSH Connection Issues

However, you may still run into connectivity struggles that require troubleshooting.

Here are tips for resolving common SSH problems when utilizing non-standard ports:

1. Verify key permissions – Ensure your public SSH key was added to remote account successfully

2. Check network rules – Some networks block wide ranges of non-essential ports

3. Test basic connectivity – Use ssh command locally to diagnose base SSH port issues

4. Change SSH key algorithm – Switch to ed25519 which has fewer restrictions

5. Trace traffic flow – Use tools like Wireshark to analyze firewall decisioning

6. Try comparing to HTTPS – Determine if problem lies with SSH specifically

If facing numbing IT bureaucracy, demonstrate SSH alternate port mission-criticality for development velocity. Offer to assist defining narrow-scoped security rules.

With systematic analysis, most obscure SSH connectivity problems can eventually be uncovered through tenacious but respectful appeal to network guardians.

Extending to Production: Next Steps

While this guide focused specifically on adding Git remotes with custom SSH ports, properly hardening and governing SSH access for business-critical systems involves quite a few additional considerations:

  • Implement SSH bastion hosts and VPNs rather than directly exposing developmental environments
  • Utilize identity & access management integration for auditing and access revocation
  • Store private keys in hardware modules to enable cryptographic erase
  • Frequently scan SSH server ciphers, keys, and configuration for vulnerabilities
  • Monitor subnets for suspicious SSH activity including brute force attacks
  • Develop automated remediation procedures for decommissioning compromised developer accounts

The responsibility and privilege of SSH gateway access to production resources should be carefully safeguarded through both technology controls and security-centric cultural habits.

But those involved topics will need to wait for a future post!

Recap: Key Takeaways

Let‘s recap the core concepts and best practices around adding Git remotes with alternate SSH ports:

  • Separate personal, work SSH keys appropriately
  • Automate and centralize SSH key deployment where possible
  • Specify non-standard ports directly in Git remote URLs
  • Configure SSH aliases for convenience
  • Troubleshoot methodically through divide & conquer testing

While default port 22 remains the uncomplicated option for SSH Git access, this guide clarified the process for employing alternate ports when needed for business cases.

The ability to reliably utilize Git over SSH – whether on standard or non-standard ports – remains an indispensable skill for productive developers. I hope these tips help you version control code even in restrictive network environments.

Now go show the world what amazing things you build!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *