[
  {
    "path": ".gitignore",
    "content": "/t/*\n/*/t/*\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# kubectl-plugin-ssh-jump\n\n[![kubectl plugin](https://img.shields.io/badge/kubectl-plugin-blue.svg)](https://github.com/topics/kubectl-plugin)\n\nA kubectl plugin to access Kubernetes nodes or remote services using a SSH jump Pod\n\nA `jump host` Pod is an intermediary Pod or an SSH gateway to Kubernetes node machines, through which a connection can be made to the node machines or remote services.\n\nHere is an scenario where you want to connect to Kubernetes nodes or remote services, but you have to go through a jump host Pod, because of firewalling, access privileges. etc. There is a number of valid reasons why the jump hosts are needed...\n\n**CASE 1: SSH into Kubernetes nodes via SSH jump Pod**\n![](assets/ssh-jump-node-ssh-login.png)\n\n**CASE 2: Connect to remote serivces via SSH local port forwarding**. SSH local port forwarding allows to forward the traffic form local machine to SSH jump then SSH jump will forward the traffic to remote services (host:port)s. \n![](assets/ssh-jump-ssh-tunnel.png)\n\n> [NOTE]\n> - Kubectl versions >= `1.12.0` (Preferred)\n>   - As of Kubernetes 1.12, kubectl now allows adding external executables as subcommands. For more detail, see [Extend kubectl with plugins](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/)\n>   - You can run the plugin with `kubectl ssh-jump ...`\n> - Kubectl versions < `1.12.0`\n>   - You still can run the plugin directly with `kubectl-ssh-jump ...`\n\n\n**Table of Content**\n<!-- TOC -->\n\n- [kubectl-plugin-ssh-jump](#kubectl-plugin-ssh-jump)\n\t- [Pre-requistes](#pre-requistes)\n\t- [Installation](#installation)\n\t\t- [Install through krew](#install-through-krew)\n\t\t- [Manual Installation](#manual-installation)\n\t- [How to use](#how-to-use)\n\t\t- [Usage](#usage)\n\t\t\t- [Option parameters Cache](#option-parameters-cache)\n\t\t\t- [SSH Agent ssh-agent](#ssh-agent-ssh-agent)\n\t\t- [Customize SSH jump pod](#customize-ssh-jump-pod)\n\t\t- [Examples](#examples)\n\t\t\t- [CASE 1: SSH into Kubernetes nodes via SSH jump Pod](#case-1-ssh-into-kubernetes-nodes-via-ssh-jump-pod)\n\t\t\t\t- [-1 - You have private & public SSH key on your side](#-1---you-have-private--public-ssh-key-on-your-side)\n\t\t\t\t- [-2 - You have .pem file but you don't have public key on your side](#-2---you-have-pem-file-but-you-dont-have-public-key-on-your-side)\n\t\t\t- [CASE 2: Access remote serivces via SSH local port forwarding](#case-2-access-remote-serivces-via-ssh-local-port-forwarding)\n\t\t\t\t- [-1 - Configuring SSH local port forwarding with --args or -a option](#-1---configuring-ssh-local-port-forwarding-with---args-or--a-option)\n\t- [Useful Links](#useful-links)\n\t- [Contributing](#contributing)\n\n<!-- /TOC -->\n\n\n## Pre-requistes\nThis plugin needs the following programs:\n* ssh(1)\t\n* ssh-agent(1)\n* ssh-keygen(1)\n\n## Installation\n\n### Install through krew\nThis is a way to install kubectl-ssh-jump through [krew](https://krew.sigs.k8s.io/). After installing krew by following [this](https://krew.sigs.k8s.io/docs/user-guide/setup/install/), you can install kubectl-ssh-jump like this:\n\n```sh\n$ kubectl krew install ssh-jump\n```\n\nExpected output would be like this:\n```\nUpdated the local copy of plugin index.\nInstalling plugin: ssh-jump\nCAVEATS:\n\\\n |  This plugin needs the following programs:\n |  * ssh(1)\n |  * ssh-agent(1)\n |\n |  Please follow the documentation: https://github.com/yokawasa/kubectl-plugin-ssh-jump\n/\nInstalled plugin: ssh-jump\n```\n\nOnce it's installed, run:\n```sh\n$ kubectl plugin list\n\nThe following kubectl-compatible plugins are available:\n\n/Users/yoichi.kawasaki/.krew/bin/kubectl-krew\n/Users/yoichi.kawasaki/.krew/bin/kubectl-ssh_jump\n\n$ kubectl ssh-jump\n```\n\n### Manual Installation\n\nInstall the plugin by copying the script in the $PATH of your shell.\n\n```sh\n# Get source\n$ git clone https://github.com/yokawasa/kubectl-plugin-ssh-jump.git\n$ cd kubectl-plugin-ssh-jump\n$ chmod +x kubectl-ssh-jump\n# Add kubeclt-ssh-jump to the install path.\n$ sudo cp -p kubectl-ssh-jump /usr/local/bin\n```\n\nOnce in the $PATH, run:\n```sh\n$ kubectl plugin list\n\nThe following kubectl-compatible plugins are available:\n/usr/local/bin/kubectl-ssh-jump\n\n$ kubectl ssh-jump\n```\n\n## How to use\n\n### Usage\n\n```TXT\nUsage: \n  kubectl ssh-jump <dest_node> [options]\n\nOptions:\n  <dest_node>                     Destination node name or IP address\n                                  dest_node must start from the following letters:\n                                  ASCII letters 'a' through 'z' or 'A' through 'Z',\n                                  the digits '0' through '9', or hyphen ('-').\n                                  NOTE: Setting dest_node as 'jumphost' allows to\n                                  ssh into SSH jump Pod as 'root' user\n  -u, --user <sshuser>            SSH User name\n  -i, --identity <identity_file>  Identity key file, or PEM(Privacy Enhanced Mail)\n  -p, --pubkey <pub_key_file>     Public key file\n  -P, --port <port>               SSH port for target node SSH server\n                                  Defaults to 22\n  -a, --args <args>               Args to exec in ssh session\n  -n, --namespace <ns>            Namespace for jump pod\n  --context <context>             Kubernetes context\n  --pod-template <file>           Path to custom sshjump pod definition\n  -l, --labels <key>=<val>[,...]  Find a pre-existing sshjump pod using labels\n  --skip-agent                    Skip automatically starting SSH agent and adding\n                                  SSH Identity key into the agent before SSH login\n                                  (=> You need to manage SSH agent by yourself)\n  --cleanup-agent                 Clearning up SSH agent at the end\n                                  The agent is NOT cleaned up in case that\n                                  --skip-agent option is given\n  --cleanup-jump                  Clearning up sshjump pod at the end\n                                  Defaults to skip cleaning up sshjump pod\n  -v, --verbose                   Run ssh in verbose mode (=ssh -vvv)\n  -h, --help                      Show this message\n\nExample:\n  Scenario1 - You have private & public SSH key on your side\n  $ kubectl ssh-jump -u myuser -i ~/.ssh/id_rsa -p ~/.ssh/id_rsa.pub hostname\n\n  Scenario2 - You have .pem file but you don't have public key on your side\n  $ kubectl ssh-jump -u ec2-user -i ~/.ssh/mykey.pem hostname\n```\n\n#### Option parameters Cache\n\n`username`, `identity`, `pubkey`, `port` options are cached, therefore you can omit these options afterward. The options are stored in a file named `$HOME/.kube/kubectlssh/options`\n\n```sh\n$ cat $HOME/.kube/kubectlssh/options\nsshuser=myuser\nidentity=/Users/yoichi.kawasaki/.ssh/id_rsa_k8s\npubkey=/Users/yoichi.kawasaki/.ssh/id_rsa_k8s.pub\nport=22\n```\n\n#### SSH Agent (ssh-agent)\n\nThe plugin automatically check if there are any `ssh-agents` started running by the plugin, and starts `ssh-agent`if it doesn't find any `ssh-agent` running and adds SSH Identity key into the agent before SSH login. If the command find that ssh-agent is already running, it doesn't start a new agent, and re-use the agent.\nAdd `--cleanup-agent` option if you want to kill the created agent at the end of command.\n\nIn addtion, add `--skip-agent` option if you want to skip automatic starting `ssh-agent`. This is actually a case where you already have ssh-agent managed or you want to manually start the agent.\n\n### Customize SSH jump pod\n\nYou can customize the sshjump pod created by `kubectl ssh-jump` by setting the `--pod-template` flag to the path to a pod template on disk.\nHowever, customized sshjump pods must be named `sshjump` and run in the current namespace or `kubectl ssh-jump` won't be able to find them without the required flags.\nIf you change the pod name, you must give the pod a unique set of labels and provide them on the command line by setting the `--labels` flag.\n\nYou can also specify the namespace and context used by `kubectl ssh-jump` by setting the `--namespace` and `--context` flags respectively.\n\n### Examples\n\nShow all node list. Simply executing `kubectl ssh-jump` gives you the list of destination nodes as well as command usage\n\n```sh\n$ kubectl ssh-jump\n\nUsage: \n  kubectl ssh-jump <dest_node> [options]\n\n...snip...\n\nList of destination node...\nHostname                    Internal-IP\naks-nodepool1-18558189-0    10.240.0.4\n...snip...\n```\n\n\n#### CASE 1: SSH into Kubernetes nodes via SSH jump Pod\n\n##### 1-1 - You have private & public SSH key on your side\n\nSuppose you have private & public SSH key on your side and you want to SSH to a node named `aks-nodepool1-18558189-0`, execute the plugin with options like this:\n\n- usernaem: `azureuser`\n- identity:`~/.ssh/id_rsa_k8s`\n- pubkey:`~/.ssh/id_rsa_k8s.pub`)\n\n```sh\n$ kubectl ssh-jump aks-nodepool1-18558189-0 \\\n  -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub\n```\n\n> [NOTE] you can try SSH into a node using node IP address (`Internal-IP`) instead of `Hostname`\n\nAs explained in usage secion, `username`, `identity`, `pubkey` options will be cached, therefore you can omit these options afterward.\n\n```sh\n$ kubectl ssh-jump aks-nodepool1-18558189-0\n```\n\nYou can pass the commands to run in the destination node like this (Suppose that `username`, `identity`, `pubkey` options are cached):\n```sh\necho \"uname -a\" | kubectl ssh-jump aks-nodepool1-18558189-0\n\n(Output)\nLinux aks-nodepool1-18558189-0 4.15.0-1035-azure #36~16.04.1-Ubuntu SMP Fri Nov 30 15:25:49 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux\n```\n\nYou can pass commands with `--args` or `-a` option\n``` sh\nkubectl ssh-jump aks-nodepool1-18558189-0 --args \"uname -a\"\n\n(Output)\nLinux aks-nodepool1-18558189-0 4.15.0-1035-azure #36~16.04.1-Ubuntu SMP Fri Nov 30 15:25:49 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux\n```\n\nYou can clean up sshjump pod at the end of the command with `--cleanup-jump` option, otherwise, the sshjump pod stay running by default.\n\n```sh\n$ kubectl ssh-jump aks-nodepool1-18558189-0 \\\n  -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \\\n  --cleanup-jump\n```\n\nYou can clean up ssh-agent at the end of the command with `--cleanup-agent` option, otherwise, the ssh-agent process stay running once it's started.\n\n```sh\n$ kubectl ssh-jump aks-nodepool1-18558189-0 \\\n  -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \\\n  --cleanup-agent\n```\n\nYou can skip starting `ssh-agent` by giving `--skip-agent`. This is actually a case where you already have ssh-agent managed. Or you can start new ssh-agent and add an identity key to the ssh-agent like this:\n\n```sh\n# Start ssh-agent manually\n$ eval `ssh-agent`\n# Add an arbitrary private key, give the path of the key file as an argument to ssh-add\n$ ssh-add ~/.ssh/id_rsa_k8s\n# Then, run the plugin with --skip-agent\n$ kubectl ssh-jump aks-nodepool1-18558189-0 \\\n  -u azureuser -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \\\n  --skip-agent\n\n# At the end, run this if you want to kill the current agent\n$ ssh-agent -k\n```\n\n##### 1-2 - You have .pem file but you don't have public key on your side\n\nFrom v0.4.0, the plugin supports PEM (Privacy Enhanced Mail) scenario where you create key-pair but you only have .pem / private key (downloaded from AWS, for example) and you don't have the public key on your side.\n\nSuppose you've already downloaded a pem file and you want to ssh to your EKS worker node (EC2) named `ip-10-173-62-96.ap-northeast-1.compute.internal` using the pem, execute the plugin with options like this:\n\n- usernaem: `ec2-user`\n- identity: `~/.ssh/mykey.pem`\n\n```sh\n$ kubectl ssh-jump -u ec2-user -i ~/.ssh/mykey.pem ip-10-173-62-96.ap-northeast-1.compute.internal\n```\n#### CASE 2: Access remote serivces via SSH local port forwarding\n\nSSH local port forwarding allows to forward the traffic form local machine to SSH jump then SSH jump will forward the traffic to remote services (host:port)s.\n##### 2-1 - Configuring SSH local port forwarding with --args or -a option\n\nSuppose you have private & public SSH key on your side and you want to access a remote server (IP: `10.100.10.8`) using `3389`/TCP port which is not accessible directly but accessible via SSH jump, execute the plugin with options like this, at first:\n\n- identity:`~/.ssh/id_rsa_k8s`\n- pubkey:`~/.ssh/id_rsa_k8s.pub`)\n\n The command below allows to forward the traffic form local machine (`localhost:13200`) to SSH jump then SSH jump will forward the traffic to the remote server (`10.100.10.8:3389`). \n```sh\n$ kubectl ssh-jump sshjump \\\n  -i ~/.ssh/id_rsa_k8s -p ~/.ssh/id_rsa_k8s.pub \\\n  -a \"-L 13200:10.100.10.8:3389\"\n```\n> - `sshjump` is the hostname for SSH jump Pod\n> -  The value for `--arg` or `-a` should be in this format: \"-L local_port:remote_address:remote_port\"\n\nNow, you're ready to access to the remote server at port 13200 at local machine.\n\n## Useful Links\n\n- [Extend kubectl with plugins](https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/)\n- [Write your own kubectl subcommands](https://ahmet.im/blog/kubectl-plugins/)\n- [SSH-AGENT - SINGLE SIGN-ON USING SSH](https://www.ssh.com/ssh/agent)\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/yokawasa/kubectl-plugin-ssh-jump\n"
  },
  {
    "path": "VERSION",
    "content": "0.7.3\n"
  },
  {
    "path": "kubectl-ssh-jump",
    "content": "#!/usr/bin/env bash\n# vim: sw=2:\n#\n# A kubectl plugin to ssh into Kubernetes nodes using a SSH jump host Pod\n#\n\n[[ -n $DEBUG ]] && set -x -e\n\nPLUGIN_DIR=\"${HOME}/.kube/kubectlssh\"\nPLUGIN_SSH_OPTIONS_FILE=\"${PLUGIN_DIR}/options\"\nMAX_POD_CREATION_TIME=10   # unit: second\nSSH_AGENT_ENV_FILE=\"${PLUGIN_DIR}/sshagent-env\"\nSSH_AGENT_PID_FILE=\"${PLUGIN_DIR}/sshagent-pid\"\n\nhelp(){\n  echo \"Usage: \"\n  echo \"  kubectl ssh-jump <dest_node> [options]\"\n  echo \"\"\n  options\n}\n\noptions(){\n  cat <<\"EOF\"\nOptions:\n  <dest_node>                     Destination node name or IP address\n                                  dest_node must start from the following letters:\n                                  ASCII letters 'a' through 'z' or 'A' through 'Z',\n                                  the digits '0' through '9', or hyphen ('-').\n                                  NOTE: Setting dest_node as 'jumphost' allows to \n                                  ssh into SSH jump Pod as 'root' user \n  -u, --user <sshuser>            SSH User name\n  -i, --identity <identity_file>  Identity key file, or PEM(Privacy Enhanced Mail)\n  -p, --pubkey <pub_key_file>     Public key file\n  -P, --port <port>               SSH port for target node SSH server\n                                  Defaults to 22\n  -a, --args <args>               Args to exec in ssh session\n  -n, --namespace <ns>            Namespace for jump pod\n  --context <context>             Kubernetes context\n  --pod-template <file>           Path to custom sshjump pod definition\n  -l, --labels <key>=<val>[,...]  Find a pre-existing sshjump pod using labels\n  --skip-agent                    Skip automatically starting SSH agent and adding \n                                  SSH Identity key into the agent before SSH login\n                                  (=> You need to manage SSH agent by yourself)\n  --cleanup-agent                 Clearning up SSH agent at the end\n                                  The agent is NOT cleaned up in case that\n                                  --skip-agent option is given\n  --cleanup-jump                  Clearning up sshjump pod at the end\n                                  Defaults to skip cleaning up sshjump pod\n  -v, --verbose                   Run ssh in verbose mode (=ssh -vvv)\n  -h, --help                      Show this message\n\nExample:\n  Scenario1 - You have private & public SSH key on your side\n  $ kubectl ssh-jump -u myuser -i ~/.ssh/id_rsa -p ~/.ssh/id_rsa.pub hostname\n\n  Scenario2 - You have .pem file but you don't have public key on your side\n  $ kubectl ssh-jump -u ec2-user -i ~/.ssh/mykey.pem hostname\n\nEOF\n}\n\nread_options(){\n  if [[ -f \"${PLUGIN_SSH_OPTIONS_FILE}\" ]]; then\n    source ${PLUGIN_SSH_OPTIONS_FILE}\n  fi  \n}\n\nwrite_options(){\n  local sshuser=\"$1\"\n  local identity=\"$2\"\n  local pubkey=\"$3\"\n  local port=\"$4\"\n\n  cat << EOF > ${PLUGIN_SSH_OPTIONS_FILE}\nsshuser=${sshuser}\nidentity=${identity}\n\npubkey=${pubkey}\nport=${port}\nEOF\n}\n\nget_node_list(){\n  echo \"List of destination node...\"\n  kubectl \"${k_args[@]}\" get no -o custom-columns=Hostname:.metadata.name,Internal-IP:'{.status.addresses[?(@.type==\"InternalIP\")].address}'\n  echo \"\"\n}\n\nget_openssh_verion_number() {\n  ssh -V 2>&1 | awk -F'[_,]' '{print $2+0}'\n}\n\ncleanup_sshjump_pod(){\n  echo \"Clearning up SSH Jump host (Pod)...\"\n  kubectl \"${k_args[@]}\" delete pod sshjump\n}\n\ncheck_and_start_agent(){\n  local identity=\"$1\"\n\n  is_alive=\"no\"\n  if [ -f ${SSH_AGENT_PID_FILE} ]; then\n    SSH_AGENT_PID=$(cat ${SSH_AGENT_PID_FILE})\n    source ${SSH_AGENT_ENV_FILE}\n    if [ ${SSH_AGENT_PID} -gt 0 ] && ps -p ${SSH_AGENT_PID} > /dev/null\n    then\n      echo \"ssh-agent is already running\"\n      is_alive=\"yes\"\n    fi\n  fi\n  if [ \"${is_alive}\" = \"no\" ]; then\n    ssh-agent > ${SSH_AGENT_ENV_FILE}\n    agent_pid=$(cat ${SSH_AGENT_ENV_FILE} | grep 'echo Agent pid' |sed 's/echo Agent pid //; s/;//')\n    echo \"Started ssh-agent: pid=${agent_pid}\"\n    echo ${agent_pid} > ${SSH_AGENT_PID_FILE}\n    source ${SSH_AGENT_ENV_FILE}\n    ssh-add ${identity}\n  fi\n}\n\ncleanup_agent(){\n  echo \"Killing ssh-agent...\"\n  ssh-agent -k\n  if [ -f ${SSH_AGENT_PID_FILE} ]; then\n    rm ${SSH_AGENT_PID_FILE}\n  fi \n  if [ -f ${SSH_AGENT_ENV_FILE} ]; then\n    rm ${SSH_AGENT_ENV_FILE}\n  fi \n}\n\ncreate_jump_pod(){\n  local pod_template\n  if [[ -n \"${jump_pod_template:-}\" && -e \"${jump_pod_template}\" ]]; then\n    pod_template=$(<\"${jump_pod_template}\")\n  fi\n  if [[ -z \"${pod_template}\" ]]; then\n    pod_template=$(cat <<EOF\napiVersion: v1\nkind: Pod\nmetadata:\n  name: sshjump\n  labels:\n    env: test\nspec:\n  containers:\n  - name: sshjump\n    image: corbinu/ssh-server\n    ports:\n    - containerPort: 22\n  nodeSelector:\n    kubernetes.io/os: linux\n    kubernetes.io/arch: amd64\nEOF\n)\n  fi\n  echo \"Creating SSH jump host (Pod)...\"\n  echo \"${pod_template}\" | kubectl \"${k_args[@]}\" apply -f -\n}\n\nrun_ssh_node(){\n  local destnode=\"$1\"\n  local sshuser=\"$2\"\n  local identity=\"$3\"\n  local pubkey=\"$4\"\n  local port=\"$5\"\n  local sshargs=\"$6\"\n  local pod_labels=\"$7\"\n\n  local pod_name\n  if [[ -n \"${pod_labels}\" ]]; then\n    pods=($(kubectl \"${k_args[@]}\" get pods -l \"${pod_labels}\" -o custom-columns=:metadata.name --no-headers 2>/dev/null))\n    if [[ \"${#pods[@]}\" -eq 0 ]]; then\n      echo \"Error: failed to find pods with labels ${pod_labels}\" >&2\n      exit 1\n    fi\n    pod_name=\"${pods[0]}\"\n    echo \"Using SSH jump pod ${pod_name}...\"\n  else\n    pod_name=sshjump\n    # Install an SSH Server if not yet installed\n    if ! kubectl \"${k_args[@]}\" get pod \"${pod_name}\" &>/dev/null; then\n      create_jump_pod\n      # Wait until sshjump gets ready\n      c=1\n      while [[ ${c} -le ${MAX_POD_CREATION_TIME} ]];\n      do\n        pod_status=$(kubectl \"${k_args[@]}\" get pod \"${pod_name}\" -o jsonpath='{.status.phase}')\n        if [[ \"${pod_status}\" == \"Running\" ]]; then\n          break\n        fi\n        (( c++ ))\n        sleep 1\n      done\n    fi\n  fi\n\n  local identity_sshjump=${identity}\n  local pubkey_sshjump=${pubkey}\n  if [ ! -f \"${pubkey_sshjump}\" ]; then\n    # Generate temp private/public key to ssh to the sshjump if the pubkey isn't given\n    identity_sshjump=${PLUGIN_DIR}/id_rsa_sshjump\n    pubkey_sshjump=${PLUGIN_DIR}/id_rsa_sshjump.pub\n    if [ ! -f \"${pubkey_sshjump}\" ]; then\n      echo \"Generating nopass SSH pri/pub key to ssh to the sshjump ...\"\n      ssh-keygen -t rsa -f ${identity_sshjump} -N '' > /dev/null\n    fi\n  fi\n\n  # Setup portforward\n  kubectl \"${k_args[@]}\" port-forward \"${pod_name}\" 2222:22 2>/dev/null &\n  pid_port_forward=$!\n\n  # Wait a bit for the port forwarding to get ready for connection handling for 2222\n  sleep 2\n\n  # Inject public SSH key to sshjump\n  cat ${pubkey_sshjump} | \\\n    kubectl \"${k_args[@]}\" exec -i \"${pod_name}\" -- /bin/bash -c \"cat > /root/.ssh/authorized_keys\"\n\n  # Add default ssh option\n  sshargs=\"${sshargs} -o StrictHostKeyChecking=no\"\n \n  # Add RSA workaround options if the local OpenSSH version >= 8.5\n  sshversion=$(get_openssh_verion_number)\n  if [ $(echo \"${sshversion} >= 8.5\" | bc) -eq 1 ]; then\n    sshargs=\"${sshargs} -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa\"\n  fi\n\n  if [ \"${destnode}\" = \"sshjump\" ]; then\n    ssh ${sshuser}@127.0.0.1 -p 2222 -i ${identity_sshjump} ${sshargs}\n  else\n    # Using the SSH Server as a jumphost (via port-forward proxy), ssh into the desired Node\n    ssh -i ${identity} -p ${port} ${sshuser}@${destnode} \\\n      -o \"ProxyCommand ssh root@127.0.0.1 -p 2222 -i ${identity_sshjump} ${sshargs} \\\"nc %h %p\\\"\" ${sshargs}\n  fi\n  # Stop port-forward\n  kill -3 ${pid_port_forward} 2>/dev/null\n}\n\nplugin_main() {\n  skip_agent=no\n  cleanup_jump=no\n  cleanup_agent=no\n  pod_labels=\n  sshargs=\"\"\n  k_args=()\n  while [ $# -gt 0 ] ; do\n    nSkip=1\n    case $1 in\n      \"-h\" | \"--help\")\n        help\n        exit 0\n\t      ;;\n      \"-v\" | \"--verbose\" )\n        sshargs=\"${sshargs} -vvv\"\n        ;;\n     \"--cleanup-jump\")\n        cleanup_jump=yes\n        ;;\n      \"--cleanup-agent\")\n        cleanup_agent=yes\n        ;;\n      \"--skip-agent\")\n        skip_agent=yes\n        ;;\n      \"-u\" | \"--user\" )\n        c_sshuser=$2\n        nSkip=2\n        ;;\n      \"-i\" | \"--identity\" )\n        c_identity=$2\n        nSkip=2\n        ;;\n      \"-p\" | \"--pubkey\" )\n        c_pubkey=$2\n        nSkip=2\n        ;;\n      \"-P\" | \"--port\")\n        c_port=$2\n        nSkip=2\n        ;;\n      \"-a\" | \"--args\" )\n        sshargs=\"${sshargs} $2\"\n        nSkip=2\n        ;;\n      \"-n\" | \"--namespace\" | \"--context\")\n         k_args+=(\"$1\" \"$2\")\n         nSkip=2\n         ;;\n      \"--pod-template\")\n         jump_pod_template=\"$2\"\n         nSkip=2\n         ;;\n      \"-l\" | \"--labels\")\n        pod_labels=\"$2\"\n        nSkip=2\n        ;;\n      [0-9a-zA-Z-]*)\n        destnode=$1\n        ;;\n      *)\n        help >&2\n        exit 1\n        ;;\n    esac\n    shift $nSkip\n  done\n\n  if [[ \"$(type kubectl &>/dev/null; echo $?)\" -eq 1 ]]; then\n    echo \"Error: missing kubectl command\" >&2\n    echo \"Please install kubectl (https://kubernetes.io/docs/tasks/tools/install-kubectl/)\" >&2\n    exit 1\n  fi\n\n  if [ ! -n \"${destnode}\" ]; then\n    help >&2\n    echo \"\"\n    get_node_list\n    exit 1\n  fi\n  if [ \"${destnode}\" = \"sshjump\" ]; then\n    echo \"Setting destination name as 'jumphost' allows to ssh into SSH jump Pod as 'root' user\"\n    c_sshuser=root\n  fi\n\n  if [ ! -d ${PLUGIN_DIR} ]; then\n    mkdir -p ${PLUGIN_DIR}\n  fi\n  read_options\n\n  if [ ! -n \"${c_sshuser}\" ]; then\n    if [ ! -n \"${sshuser}\" ]; then\n      c_sshuser=\"${USER}\"  # default: Current executing user\n    fi\n    echo \"using: sshuser=${sshuser}\"\n    c_sshuser=\"${sshuser}\"\n  fi\n  if [ ! -f \"${c_identity}\" ]; then\n    if [ ! -f \"${identity}\" ]; then\n      echo \"Error: identity file is required\" >&2\n      help >&2\n      exit 1\n    fi\n    echo \"using: identity=${identity}\"\n    c_identity=\"${identity}\"\n  fi\n  if [ ! -f \"${c_pubkey}\" ]; then\n    # From v0.4.0 pubkey file is optional to support PEM scenario\n    # where you don't have public key on your side\n    #if [ ! -n \"${pubkey}\" ]; then\n    #  help >&2\n    #  exit 1\n    #fi\n    if [ -f \"${pubkey}\" ]; then\n      echo \"using: pubkey=${pubkey}\"\n      c_pubkey=\"${pubkey}\"\n    fi\n  fi\n  if [ ! -n \"${c_port}\" ]; then\n    if [ ! -n \"${port}\" ]; then\n      port=\"22\"    # default: 22\n    fi\n    echo \"using: port=${port}\"\n    c_port=\"${port}\"\n  fi\n\n  if [ \"${sshargs}\" != \"\" ]; then\n    echo \"using: args=${sshargs}\"\n  fi\n\n  if [ \"${jump_pod_template}\" != \"\" ]; then\n     echo \"using: pod-template=${jump_pod_template}\"\n  fi\n\n  # Caching current ssh options\n  write_options \"${c_sshuser}\" \"${c_identity}\" \"${c_pubkey}\" \"${c_port}\"\n\n  if [ \"${skip_agent}\" = \"no\" ]; then\n    check_and_start_agent ${c_identity}\n  fi\n  # SSH Logging into desitnation node via Jump host\n  run_ssh_node \"${destnode}\" \"${c_sshuser}\" \"${c_identity}\" \"${c_pubkey}\" \"${c_port}\" \"${sshargs}\" \"${pod_labels}\"\n\n  # Cleaning up resources if needed\n  if [[ \"${cleanup_jump}\" == \"yes\" && -z \"${pod_labels}\" ]]; then\n    cleanup_sshjump_pod\n  fi\n  if [[ \"${skip_agent}\" = \"no\" && \"${cleanup_agent}\" = \"yes\" ]]; then\n    cleanup_agent\n  fi\n}\n\nplugin_main \"$@\"\n"
  },
  {
    "path": "ssh-jump.yaml",
    "content": "apiVersion: krew.googlecontainertools.github.com/v1alpha2\nkind: Plugin\nmetadata:\n  name: ssh-jump\nspec:\n  version: \"v0.6.0\"\n  homepage: https://github.com/yokawasa/kubectl-plugin-ssh-jump\n  platforms:\n  - selector:\n      matchExpressions:\n      - {key: os, operator: In, values: [darwin, linux]}\n    uri: https://github.com/yokawasa/kubectl-plugin-ssh-jump/archive/0.6.0.zip\n    sha256: \"a24149bb1b1ccba91ae87c86d21625adf9e110b9e81a0ab58ec84343e0f99ede\"\n    files:\n    - from: \"./*/kubectl-ssh-jump\"\n      to: .\n    - from: \"./*/LICENSE\"\n      to: .\n    bin: \"./kubectl-ssh-jump\"\n  shortDescription: Access nodes or services using SSH jump Pod\n  caveats: |\n    This plugin needs the following programs:\n    * ssh(1)\n    * ssh-agent(1)\n\n    Please follow the documentation: https://github.com/yokawasa/kubectl-plugin-ssh-jump\n  description: |\n    A kubectl plugin to access Kubernetes nodes or remote services using a SSH jump Pod.\n    A jump Pod is an intermediary Pod or an SSH gateway to Kubernetes node machines or\n    remote services, through which a connection can be made.\n"
  }
]