# Setting up SSH keys

--8<-- "ssh-ca.md"

[SSH keys](https://www.ssh.com/academy/ssh-keys) provide more convenient and
secure authentication. SSH keys are required to be able to connect to CSC
supercomputers using an SSH client. Connecting to Roihu requires also that you
sign your public key in order to obtain a time-based SSH certificate.

1. [Generate SSH keys on your local workstation](#generating-ssh-keys).
    - SSH keys are always generated in pairs consisting of one _public key_ and
      one _private key_. Generate these keys on the device you intend to use to
      connect to CSC supercomputers. **Never share the private key with
      anyone!**
2. [Copy the public key from your workstation to MyCSC](#copying-public-key-to-supercomputer).
    - For authenticating an SSH connection using a key pair, you need to copy
      the _public key_ to MyCSC. **Do not copy the private key.** Note that
      copying the public key directly to CSC supercomputers using tools such as
      `ssh-copy-id` will not work.
3. [Sign the public key in MyCSC and download SSH certificate](#signing-public-key) (**required for Roihu only**).
    - To connect to Roihu, sign your public key in MyCSC to generate a
      time-based SSH certificate that is used for authentication. SSH
      certificates have a finite lifetime of 24 hours, which significantly
      improves the security of the system. After the SSH certificate expires, a
      new one must be generated by signing the public key in MyCSC again.

For more information about SSH keys, see:

- [Tutorial: Setting up SSH keys at CSC](https://csc-training.github.io/csc-env-eff/hands-on/connecting/ssh-keys.html)
- [FAQ: Troubleshooting issues with SSH keys](../../support/faq/ssh-keys-not-working.md).

## Generating SSH keys

To find out how to generate SSH keys on your local workstation, see the
system-specific instructions for:

1. [Unix-based systems](ssh-unix.md) (macOS and Linux)
2. [Windows systems](ssh-windows.md)

!!! warning
    The private key should **never** be shared with anyone, not even with CSC
    staff! It should only be stored on the local workstation.

    Also, never leave the passphrase empty when generating an SSH key pair!
    Please choose a secure passphrase. It should be at least 8 characters long
    and contain numbers, letters and special characters.

## Copying public key to supercomputer

The only way to copy a public key to a supercomputer is through the MyCSC
customer portal.
[Read the instructions below](ssh-keys.md#adding-public-key-in-mycsc).

### Adding public key in MyCSC

You can add your public key through the
[MyCSC customer portal](https://my.csc.fi) by following these steps:

1. Log in to MyCSC with your CSC or Haka/Virtu credentials.
2. Select _Profile_ from the left-hand navigation or the dropdown menu in the
   top-right corner.
3. Locate _SSH PUBLIC KEYS_ section and select _+ Add key_. As a security
   measure, you are asked to log in again if it has been a few minutes since
   you last logged into the portal.

    ![Add key](https://a3s.fi/docs-files/ssh-no-keys.png 'Add key')

4. Add your public key by either
    1. uploading the public key file in the _Upload file_ tab, or
    2. manually pasting its contents into the _Key_ field in the _Manual input_
       tab. In this case, also add a _Title_ for the key, e.g. "my-ssh-key".

        === "Upload file"
            ![Upload file](https://a3s.fi/docs-files/ssh-upload-file.png 'Upload file')

        === "Manual input"
            ![Manual input](https://a3s.fi/docs-files/ssh-manual-input.png 'Manual input')

5. Select _Upload_ or _Add_.
6. You should now see your new key listed under _SSH PUBLIC KEYS_. Note that
   it might take up to one hour for your new key to become active. If it takes
   longer than that, please
   [contact the CSC Service Desk](../../support/contact.md).

    ![New key added](https://a3s.fi/docs-files/ssh-key-added.png 'New key added')

!!! info "Supported key types and formatting"
    Supported key types are Ed25519 and RSA 4096 through 16384. **We strongly
    recommend Ed25519**.

    Your public key should consist of the SSH key type, the key sequence and an
    optional comment, all separated by single spaces. Make sure to add the
    whole SSH key on the same line and do not add other whitespace than normal
    space characters. If your key is improperly formatted, an error message is
    displayed. A key in the correct format looks like this:
    ```
    ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDlapOdeoxNvz/1AZFRjGAPnPj8pzzz3skI+a+yJS5b7 optional-comment
    ```

Users can check their public keys on Puhti or Mahti using the commands:

```bash
# Check timestamp of file (time of previous sync)
ls -l /var/lib/acco/sshkeys/${USER}/${USER}.pub

# Check its contents (public keys)
cat /var/lib/acco/sshkeys/${USER}/${USER}.pub
```

If you have added multiple keys to MyCSC, they should all be visible in the
same `${USER}.pub` file.

## Signing public key

!!! warning "The following is a requirement for connecting to Roihu only"

To connect to Roihu using SSH or SFTP (WinSCP, FileZilla), you must sign your public key to get a so called
**SSH certificate**. SSH certificates significantly improve the security of the
system by introducing an additional authentication factor for SSH logins.

**SSH certificates are valid for 24 hours at a time**. Once your certificate
expires, a new one must be signed following either of the processes below.

---

### Option 1: Download from MyCSC 

We recommend trying the MyCSC workflow first, since it should work out-of-the-box on all systems.


1. Log in to MyCSC with your CSC or Haka/Virtu credentials.
1. Select _Profile_ from the left-hand navigation or the dropdown menu in the
   top-right corner.
1. Locate _SSH PUBLIC KEYS_ section and click the three vertical dots next to
   the public key you want to sign.
1. Click _Sign and download SSH certificate_. As a security measure, you may be
   asked to log in again.

    ![Sign and download SSH certificate](https://a3s.fi/docs-files/sign-download-ssh-cert.png 'Sign and download SSH certificate')

    !!! info "Where to store the SSH certificate?"
        We **strongly** advise saving the certificate in the default folder for
        SSH-related files (e.g. `~/.ssh` or `C:\Users\<username>/.ssh`).
        Specifically, storing the certificate in the same directory as your
        SSH private key **and** naming it as `<key>-cert.pub` will simplify
        connecting, working with SSH agent, etc.

        For example, if you've stored your SSH private key in
        `~/.ssh/id_ed25519`, please save your SSH certificate as
        `~/.ssh/id_ed25519-cert.pub`.

1. **Connect to Roihu following these instructions**:

=== "Linux & macOS"

	1. Optional, add certificate to [SSH authentication agent](ssh-unix.md#authentication-agent). Mandatory for SSH agent forwarding.
	1. [Connect from Terminal](ssh-unix.md#basic-usage)


=== "Windows"

	1. Optional, add certificate to [SSH authentication agent](ssh-windows.md#authentication-agents-with-roihu). Mandatory for SSH agent forwarding or for using FileZilla and WinSCP.
	1. Connect to Roihu [with SSH clients](ssh-windows.md#basic-usage) or [graphical file transfer tools](../../data/moving/graphical_transfer.md).

---

### Option 2: Certificate helper tool

To make the process smoother and easier, you can use the helper tool.

The certificate helper is a Python tool developed by CSC to simplify the
process of signing and downloading an SSH certificate, and adding it to your
SSH authentication agent. A detailed documentation of the tool is available in
[the source repository](https://github.com/CSCfi/certificate-helper-tool). The
following instructions illustrate only basic usage.

1. Ensure that you have Python installed on your computer.
    - Instructions are available in the
      [Official Python downloads page](https://www.python.org/downloads/).
      Contact your local IT-support if you need assistance.
    - If Python for some reason cannot be installed on your computer, fall
      back to [Option 1](#option-1-download-from-mycsc) instead.
2. [Download the latest release of the certificate helper tool here](https://github.com/CSCfi/certificate-helper-tool/releases)
   (_Right click zip_ :material-arrow-right: _Save Link As_ :material-arrow-right: _Unpack zip_), or clone the Git
   repository:

    ```bash
    git clone https://github.com/CSCfi/certificate-helper-tool.git
    ```

3. Run the `csc_cert.py` tool that is in the new `certificate-helper-tool` folder:

    === "Linux & macOS"

        1. Optional, but **strongly recommended:** Ensure that
           [`ssh-agent`](ssh-unix.md#authentication-agent) is running to
           automatically add SSH key and certificate to SSH agent.
        2. Open terminal and execute:

            ```bash
            # Replace <username> with your CSC user name and
            # <path-to-public-key> with the path to your SSH public key

            python3 csc_cert.py -u <username> <path-to-public-key>
            ```

            * The command above assumes that the path to `csc_cert.py` is in
              your `$PATH` environment variable, or that you are in the same
              directory as the script. If not, make sure to provide the full
              path to `csc_cert.py`.

        3. **If you have an earlier certificate which is still valid, the tool 
           prints the expiration time and exits.**
        4. If signing is needed, a login URL is displayed. Follow the link and
           authenticate.
        5. Copy the 6-digit code displayed into your terminal and enter your
           SSH key passphrase.
            - The signed certificate is automatically downloaded and added to
              your SSH agent.
            - The signed certificate is saved as
              `<key>-cert.pub` (e.g., `~/.ssh/id_ed25519-cert.pub`).
        6. You now have everything ready to **[connect to Roihu following these instructions](ssh-unix.md#basic-usage)**.

    === "Windows"


		6. [Depending on the tool you plan to use](ssh-windows.md), select the OpenSSH or Putty Private Keys (PPK) as input for the script. With OpenSSH keys you can generate certificates for both OpenSSH client and all Windows SSH applications using Putty keys, if you are only using graphical Windows applications you can also use Putty keys as input.  
        7. If you are using Putty keys, install [WinSCP](https://winscp.net/eng/docs/installation). This tool is used to generate Putty Private Keys (PPK) from the certificate from MyCSC.
               * If you install WinSCP without admin rights, you must add 
               `WinSCP.exe` to your Path environment variable. Search for the
               _Edit environment variables for your account_ settings menu.
        8. Optional, but **strongly recommended** start one of the [SSH agents](ssh-windows.md#authentication-agent) to
           automatically add SSH key and certificate to the SSH agent:
               * Pageant for Putty keys. 
               * Windows `ssh-agent` for OpenSSH keys.

        9. Open PowerShell and run the script. Depending on what tools you plan to use, provide the helper script the right type of key.

            ```bash
            # Replace:
            # <username> with your CSC user name and
            # <path-to-public-or-ppk-key> with the path to your OpenSSH public key
            # (.pub) or PuTTY key (.ppk)

            python csc_cert.py -u <username> <path-to-public-or-ppk-key>
            ```
            
            * The command above assumes that the path to `csc_cert.py` is in your
              Path environment variable, or that you are in the same directory as
              the script. If not, make sure to provide the full path to
              `csc_cert.py`.

            !!! info "Note"
                PowerShell is just needed to run the certificate
                helper script. You can still connect to Roihu using your
                [favorite SSH client](ssh-windows.md#basic-usage).

                If you intend to use PowerShell to connect to Roihu, make sure
                to provide `csc_cert.py` your OpenSSH public key (`.pub`).
                Providing a PuTTY `.ppk` key will create a certificate file
                that is only compatible with PuTTY or MobaXterm. Providing a
                `.pub` file will create both an OpenSSH-compatible `-cert.pub`
                file, as well as a `-cert.ppk` file (if WinSCP is available).

        10.  If you have an earlier certificate which is still valid, the tool 
           prints the expiration time and exits.
        11. If signing is needed, a login URL is displayed. Follow the link and
           authenticate.
        12. Copy the displayed 6-digit code into PowerShell and enter your SSH
           key passphrase.
            - The signed certificate is automatically downloaded and added to
              your SSH authentication agent if you have it running.
            - The signed certificate is saved to the same folder as the input key
               as `<key>-cert.pub` for OpenSSH keys and/or
              `<key>-cert.ppk` for Putty keys.
        13. Connect to Roihu [with SSH clients](ssh-windows.md#basic-usage) or [graphical file transfer tools](../../data/moving/graphical_transfer.md).
---

### Check when your SSH certificate will expire

Each SSH certificate is valid for 24 hours.

If you have an active certificate, the expiration time is printed when running the
[`csc_cert.py` tool](#option-2-certificate-helper-tool).

The expiration time can also be checked as follows:

=== "Terminal (Linux, macOS, PowerShell, MobaXterm)"

	1. Open a terminal client.
	1. Run command:

		```bash
		# Replace <path-to-certificate> with the path to your OpenSSH
		# certificate file (.pub)

		ssh-keygen -L -f <path-to-certificate> | grep "Valid"
		```

=== "GUI (PuTTY, MobaXterm)"

	2. Open PuTTYgen / MobaKeyGen.
	3. Load your `.ppk` private key:
		* _File_ :material-arrow-right: _Load private key_
	4. Add a certificate (`.pub`) to the key (unless already included
	   in the `.ppk` file):
		* _Key_  :material-arrow-right: _Add certificate to key_
	5. Select _Certificate info_ to see the validity period among other
	   info.

---

## More information

- [Tutorial on setting up SSH keys at CSC](https://csc-training.github.io/csc-env-eff/hands-on/connecting/ssh-keys.html)
- [Troubleshooting issues with SSH keys](../../support/faq/ssh-keys-not-working.md)
- [Connecting to CSC supercomputers with SSH on Linux and macOS](ssh-unix.md)
- [Connecting to CSC supercomputers with SSH on Windows](ssh-windows.md)
