pastebin - collaborative debugging tool
rovema.kpaste.net RSS


sshnfs - ssh with nfs forwarding
Posted by Anonymous on Fri 28th Jul 2023 13:42
raw | new post
view followups (newest first): sshnfs - ssh with nfs forwarding by Anonymous
modification of post by Anonymous (view diff)

  1. #!/bin/ksh93
  2.  
  3. #
  4. # sshnfs - remote login client with NFSv4 forwarding
  5. #
  6.  
  7. #
  8. # Example usage:
  9. # $ ksh sshnfs.ksh -o NFSURL=ssh+nfs://localhost/export/home/rmainz root@10.49.28.10 #
  10. # $ ksh sshnfs.ksh -o NFSURL=nfs://localhost/export/home/rmainz root@10.49.20.207 #
  11. # $ ksh sshnfs.ksh -o NFSURL=nfs://derfwpc5131/export/home/rmainz root@10.49.28.10 #
  12. # $ ksh sshnfs.ksh -o NFSURL=ssh+nfs://derfwpc5131/export/home/rmainz -o SSHNFSJumphost=rmainz@derfwpc5131,roland.mainz@derfwnb8353 -J rmainz@derfwpc5131,roland.mainz@derfwnb8353 root@10.49.20.207
  13. # $ ksh sshnfs.ksh -o NFSURL=ssh+nfs://derfwpc5131/export/home/rmainz target@fe80::d6f5:27ff:fe2b:8588%enp2s0
  14. # $ ksh sshnfs.ksh -o NFSURL=ssh+nfs://root@derfwpc5131/export/home/rmainz root@10.49.28.56
  15. # $ ksh sshnfs.ksh -o NFSServerSSHLoginName=root -o NFSURL=ssh+nfs://derfwpc5131/export/home/rmainz root@10.49.28.56
  16. # $ SSHNFS_OPTIONS='-o NFSServerSSHLoginName=root -o NFSURL=ssh+nfs://derfwpc5131/export/home/rmainz' sshnfs.ksh root@10.49.28.56
  17. #
  18.  
  19. #
  20. # Written by Roland Mainz <roland.mainz@nrubsig.org>
  21. #
  22.  
  23. #    
  24. # simple netstat -n parser
  25. #    
  26. function netstat_list_connections
  27. {
  28.         set -o nounset
  29.         nameref data=$1
  30.        
  31.         compound out=( typeset stdout stderr ; integer res )
  32.        
  33.         out.stderr="${ { out.stdout="${ LC_ALL='POSIX' PATH='/usr/bin:/bin' netstat -a -n ; (( out.res=$? )) ; }" ; } 2>&1 ; }"
  34.         if (( out.res != 0 )) || [[ ${out.stderr} != '' ]] ; then
  35.                 return 1
  36.         fi
  37.  
  38.         typeset -a data.connections
  39.         typeset l
  40.         typeset leftover
  41.         integer dci=0 # data.connections array index
  42.  
  43.         while read l ; do
  44.                 leftover="${l/~(Elrx)
  45.                 (?: # non-capturing group
  46.                         #
  47.                         # regex group for tcp,udp
  48.                         #
  49.                         (tcp|tcp6|udp|udp6|raw|raw6|sctp|sctp6) # Proto
  50.                         [[:space:]]+
  51.                         ([[:digit:]]+)                  # Recv-Q
  52.                         [[:space:]]+
  53.                         ([[:digit:]]+)                  # Send-Q
  54.                         [[:space:]]+
  55.                         ([^[:space:]]+)                 # Local Address
  56.                         [[:space:]]+
  57.                         ([^[:space:]]+)                 # Foreign Address
  58.                         (?:
  59.                                 |
  60.                                 [[:space:]]+
  61.                                 ([^[:space:]]*?)        # State (Optional)
  62.                         )
  63.                 |
  64.                         #
  65.                         # regex for unix
  66.                         #
  67.                         (unix)                          # Proto
  68.                         [[:space:]]+
  69.                         ([[:digit:]]+)                  # RefCnt
  70.                         [[:space:]]+
  71.                         (\[.+?\])                       # Flags
  72.                         [[:space:]]+
  73.                         ([^[:space:]]+)                 # Type
  74.                         [[:space:]]+
  75.                         ([^[:space:]]*?)                # State (optional)
  76.                         [[:space:]]+
  77.                         ([[:digit:]]+)                  # I-Node
  78.                         (?:
  79.                                 |
  80.                                 [[:space:]]+
  81.                                 ([^[:space:]]+)         # Path (optional)
  82.                         )
  83.                 )
  84.                         /X}"
  85.        
  86.                 # If the regex above did not match then .sh.match
  87.                 # remains untouched, so we might see data from the
  88.                 # previous round.
  89.                 # So we check the "leftover" var whether it just
  90.                 # contains the dummy value of "X" to indicate a
  91.                 # successful regex match
  92.                 if [[ "$leftover" == 'X' ]] ; then
  93.                         #print -v .sh.match
  94.                        
  95.                         if [[ "${.sh.match[1]-}" != '' ]] ; then
  96.                                 nameref dcn=data.connections[$dci]
  97.  
  98.                                 typeset dcn.proto="${.sh.match[1]}"
  99.                                 typeset dcn.recv_q="${.sh.match[2]}"
  100.                                 typeset dcn.send_q="${.sh.match[3]}"
  101.                                 typeset dcn.local_address="${.sh.match[4]}"
  102.                                 typeset dcn.foreign_address="${.sh.match[5]}"
  103.                                 typeset dcn.state="${.sh.match[6]}"
  104.                                 ((dci++))
  105.                         elif [[ "${.sh.match[7]-}" != '' ]] ; then
  106.                                 nameref dcn=data.connections[$dci]
  107.  
  108.                                 typeset dcn.proto="${.sh.match[7]}"
  109.                                 typeset dcn.refcnt="${.sh.match[8]}"
  110.                                 typeset dcn.flags="${.sh.match[9]}"
  111.                                 typeset dcn.type="${.sh.match[10]}"
  112.                                 [[ "${.sh.match[11]}" != '' ]] && typeset dcn.state="${.sh.match[11]}"
  113.                                 typeset dcn.inode="${.sh.match[12]}"
  114.                                 [[ "${.sh.match[13]}" != '' ]] && typeset dcn.path="${.sh.match[13]}"
  115.                                 ((dci++))
  116.                         fi
  117.                 else
  118.                         true
  119.                         #printf $"leftover=%q\n" "${leftover}"
  120.                 fi
  121.         done <<<"${out.stdout}"
  122.        
  123.         return 0
  124. }
  125.  
  126. function netstat_list_active_local_tcp_connections
  127. {
  128.         set -o nounset
  129.         nameref ar=$1
  130.         compound c
  131.         integer port
  132.         integer i
  133.  
  134.         netstat_list_connections c || return 1
  135.         #print -v c
  136.        
  137.         [[ -v ar ]] || integer -a ar
  138.  
  139.         for i in "${!c.connections[@]}" ; do
  140.                 nameref n=c.connections[$i]
  141.                
  142.                 # look for only for TCP connections which match
  143.                 # 127.0.*.* or IPv6 ::1 for localhost
  144.                 # 0.0.0.0 or IPv6 :: for all addresses (e.g. servers)
  145.                 if [[ "${n.proto}" == ~(El)tcp && \
  146.                         "${n.local_address}" == ~(Elr)((127\.0\..+|::1)|(::|0\.0\.0\.0|)):[[:digit:]]+ ]] ; then
  147.  
  148.                         port="${n.local_address##*:}"
  149.                         #printf $"port = %d\n" port
  150.  
  151.                         (( ar[port]=1 ))
  152.                 fi
  153.         done
  154.  
  155.         return 0
  156. }
  157.  
  158. function netstat_find_next_free_local_tcp_port
  159. {
  160.         set -o nounset
  161.         compound c=( integer -a ar )
  162.         nameref ret_free_port=$1
  163.         integer start_port
  164.         integer end_port
  165.         integer i
  166.  
  167.         netstat_list_active_local_tcp_connections c.ar || return 1
  168.  
  169.         #print -v c
  170.  
  171.         (( start_port=$2 ))
  172.         if (( $# > 2 )) ; then
  173.                 (( end_port=$3 ))
  174.         else
  175.                 (( end_port=65535 ))
  176.         fi
  177.  
  178.         for ((i=start_port ; i < end_port ; i++ )) ; do
  179.                 if [[ ! -v c.ar[i] ]] ; then
  180.                         (( ret_free_port=i ))
  181.                         return 0
  182.                 fi
  183.         done
  184.        
  185.         return 1
  186. }
  187.  
  188. #
  189. # parse_rfc1738_url - parse RFC 1838 URLs
  190. #
  191. # Output variables are named after RFC 1838 Section 5 ("BNF for
  192. # specific URL schemes")
  193. #
  194. function parse_rfc1738_url
  195. {
  196.         set -o nounset
  197.  
  198.         typeset url="$2"
  199.         typeset leftover
  200.         nameref data="$1" # output compound variable
  201.        
  202.         # ~(E) is POSIX extended regular expression matching (instead
  203.         # of shell pattern), "x" means "multiline", "l" means "left
  204.         # anchor", "r" means "right anchor"
  205.         leftover="${url/~(Elrx)
  206.                 (.+?)                           # scheme
  207.                 :\/\/                           # '://'
  208.                 (                               # login
  209.                         (?:
  210.                                 (.+?)           # user (optional)
  211.                                 (?::(.+))?      # password (optional)
  212.                                 @
  213.                         )?
  214.                         (                       # hostport
  215.                                 (.+?)           # host
  216.                                 (?::([[:digit:]]+))? # port (optional)
  217.                         )
  218.                 )
  219.                 (?:\/(.*?))?/X}"                # path (optional)
  220.  
  221.         # All parsed data should be captured via eregex in .sh.match - if
  222.         # there is anything left (except the 'X') then the input string did
  223.         # not properly match the eregex
  224.         [[ "$leftover" == 'X' ]] ||
  225.                 { print -u2 -f $"%s: Parser error, leftover=%q\n" \
  226.                         "$0" "$leftover" ; return 1 ; }
  227.  
  228.         data.url="${.sh.match[0]}"
  229.         data.scheme="${.sh.match[1]}"
  230.         data.login="${.sh.match[2]}"
  231.         # FIXME: This should use [[ ! -v .sh.match[3] ]], but ksh93u has bugs
  232.         [[ "${.sh.match[3]-}" != '' ]] && data.user="${.sh.match[3]}"
  233.         [[ "${.sh.match[4]-}" != '' ]] && data.password="${.sh.match[4]}"
  234.         data.hostport="${.sh.match[5]}"
  235.         data.host="${.sh.match[6]}"
  236.         [[ "${.sh.match[7]-}" != '' ]] && integer data.port="${.sh.match[7]}"
  237.         [[ "${.sh.match[8]-}" != '' ]] && data.uripath="${.sh.match[8]}"
  238.  
  239.         return 0
  240. }
  241.  
  242.  
  243. function parse_sshnfs_url
  244. {
  245.         typeset url="$2"
  246.         nameref data="$1"
  247.        
  248.         parse_rfc1738_url data "$url" || return 1
  249.        
  250.         [[ "${data.scheme}" == ~(Elr)(ssh\+nfs|nfs) ]] || \
  251.                 { print -u2 -f $"%s: Not a nfs:// or ssh+nfs:// url\n" "$0" ; return 1 ; }
  252.         [[ "${data.host}" != '' ]] || { print -u2 -f $"%s: NFS hostname missing\n" "$0" ; return 1 ; }
  253.         [[ "${data.uripath}" != '' ]] || { print -u2 -f $"%s: NFS path missing\n" "$0" ; return 1 ; }
  254.        
  255.         return 0
  256. }
  257.  
  258.  
  259. function main
  260. {
  261.         set -o nounset
  262.         typeset mydebug=false # fixme: should be "bool" for ksh93v
  263.         integer i
  264.         integer retval
  265.         compound c
  266.  
  267.         #
  268.         # Expand SSHNFS_OPTIONS before arguments given to sshnfs.ksh
  269.         # By default we use IFS=$' \t\n' for argument splitting
  270.         #
  271.         typeset -a c.args=( ${SSHNFS_OPTIONS-} "$@" )
  272.  
  273.         for ((i=0 ; i < ${#c.args[@]} ; i++)) ; do
  274.                 if [[ "${c.args[i]}" == '-o' ]] ; then
  275.                         case "${c.args[i+1]-}" in
  276.                                 ~(Eli)NFSServerSSHLoginName=)
  277.                                         # User name for SSH login to NFS server
  278.                                         typeset c.nfsserver_ssh_login_name="${c.args[i+1]/~(Eli)NFSServerSSHLoginName=}"
  279.  
  280.                                         unset c.args[$i] c.args[$((i+1))]
  281.                                         ((i++))
  282.                                         ;;
  283.  
  284.                                 ~(Eli)NFSURL=)
  285.                                         unset c.nfs_server
  286.                                         compound c.nfs_server
  287.                                         typeset c.url="${c.args[i+1]/~(Eli)NFSURL=}"
  288.                                         parse_sshnfs_url c.nfs_server "${c.url}" || return 1
  289.  
  290.                                         unset c.args[$i] c.args[$((i+1))]
  291.                                         ((i++))
  292.                                         ;;
  293.  
  294.                                 ~(Eli)SSHNFSJumphost=)
  295.                                         [[ ! -v c.ssh_jumphost_args ]] && typeset -a c.ssh_jumphost_args
  296.                                         c.ssh_jumphost_args+=( "-J" "${c.args[i+1]/~(Eli)SSHNFSJumphost=}" )
  297.  
  298.                                         unset c.args[$i] c.args[$((i+1))]
  299.                                         ((i++))
  300.                                         ;;
  301.                         esac
  302.                 fi
  303.         done
  304.  
  305.         if [[ -v c.nfs_server ]] ; then
  306.                 if [[ ! -v c.nfs_server.port ]] ; then
  307.                         # use # default NFSv4 TCP port number (see
  308.                         # $ getent services nfs #)
  309.                         integer c.nfs_server.port=2049
  310.                 fi
  311.  
  312.                 case "${c.nfs_server.scheme}" in
  313.                         'ssh+nfs')
  314.                                 #
  315.                                 # Find free local forwarding port...
  316.                                 #
  317.  
  318.                                 # port on THIS machine
  319.                                 integer c.local_forward_port
  320.  
  321.                                 # TCP port on destination machine where we forward the
  322.                                 # NFS port from the server
  323.                                 integer c.destination_nfs_port=33049
  324.  
  325.                                 (( i=34049 ))
  326.                                 netstat_find_next_free_local_tcp_port c.local_forward_port $i
  327.  
  328.                                 #
  329.                                 # ... and adjust c.destination_nfs_port by the same offset
  330.                                 # we do that so that multiple sshnfs.ksh logins to the same
  331.                                 # machine do try to use the same ports on that machine
  332.                                 #
  333.                                 (( c.destination_nfs_port += c.local_forward_port-i ))
  334.                                 ${mydebug} && printf $"debug: c.local_forward_port=%d, c.destination_nfs_port=%d\n" \
  335.                                         c.local_forward_port \
  336.                                         c.destination_nfs_port
  337.  
  338.                                 c.ssh_control_socket_name="/tmp/sshnfs_ssh-control-socket_logname${LOGNAME}_ppid${PPID}_pid$$"
  339.  
  340.                                 #
  341.                                 # Find SSH login user name for NFS server
  342.                                 #
  343.                                 if [[ -v c.nfs_server.user ]] ; then
  344.                                         typeset c.nfsserver_ssh_login_name="${c.nfs_server.user}"
  345.                                 fi
  346.                                 if [[ ! -v c.nfsserver_ssh_login_name ]] ; then
  347.                                         # default user name if neither URL nor
  348.                                         # "-o NFSServerSSHLoginName=..." were given
  349.                                         typeset c.nfsserver_ssh_login_name="$LOGNAME"
  350.                                 fi
  351.  
  352.                                 #
  353.                                 # Forward NFS port from server to local machine
  354.                                 #
  355.                                 # Notes:
  356.                                 # - We use $ ssh -M ... # here as a way to terminate the port
  357.                                 # forwarding process later using "-O exit" without the need
  358.                                 # for a pid
  359.                                 #
  360.                                 print -u2 -f $"# Please enter the login data for NFS server (%s):\n" \
  361.                                         "${c.nfsserver_ssh_login_name}@${c.nfs_server.host}"
  362.  
  363.                                 #
  364.                                 # Notes:
  365.                                 # - fixme: c.nfs_server.port is fixed
  366.                                 # for ssh+nfs://-URLs, so for now we
  367.                                 # have to hardcode TCP/2049 for now
  368.                                 # - We use aes128-cbc,aes128-ctr ciphers for better
  369.                                 # throughput (see https://bash-prompt.net/guides/bash-ssh-ciphers/
  370.                                 # for a benchmark) and lower latency, as NFS is
  371.                                 # a bit latency-sensitive
  372.                                 # - We turn compression off, as it incrases latency
  373.                                 #
  374.                                 ssh \
  375.                                         -L "${c.local_forward_port}:localhost:2049" \
  376.                                         -M -S "${c.ssh_control_socket_name}" \
  377.                                         -N \
  378.                                         -f -o 'ExitOnForwardFailure=yes' \
  379.                                         -o 'Compression=no' \
  380.                                         -o 'Ciphers=aes128-cbc,aes128-ctr' \
  381.                                         "${c.ssh_jumphost_args[@]}" \
  382.                                         "${c.nfsserver_ssh_login_name}@${c.nfs_server.host}"
  383.                                 if (( $? != 0 )) ; then
  384.                                         print -u2 -f $"%s: NFS forwarding ssh failed with error code %d\n" "$0" $?
  385.                                         return 1
  386.                                 fi
  387.  
  388.                                 # debug
  389.                                 ${mydebug} && \
  390.                                         ssh \
  391.                                                 -S "${c.ssh_control_socket_name}" \
  392.                                                 -O 'check' \
  393.                                                 "${c.nfsserver_ssh_login_name}@${c.nfs_server.host}"
  394.  
  395.                                 print -u2 -f $"# Use this to mount the directory:\n"
  396.                                 print -u2 -f $"# $ mkdir /mnt_nfs\n"
  397.                                 print -u2 -f $"# $ mount -vvv -t nfs -o vers=4.2,port=%d localhost:/%s /mnt_nfs\n" \
  398.                                         c.destination_nfs_port \
  399.                                         "${c.nfs_server.uripath}"
  400.  
  401.                                 #
  402.                                 # add NFS forwarding options to main ssh argument list
  403.                                 #
  404.                                 # Notes:
  405.                                 # - We use aes128-cbc,aes128-ctr ciphers for better
  406.                                 # throughput (see https://bash-prompt.net/guides/bash-ssh-ciphers/
  407.                                 # for a benchmark) and lower latency, as NFS is
  408.                                 # a bit latency-sensitive
  409.                                 # - We turn compression off, as it incrases latency
  410.                                 #
  411.                                 c.args=(
  412.                                         '-R' "${c.destination_nfs_port}:localhost:${c.local_forward_port}"
  413.                                         '-o' 'ExitOnForwardFailure=yes'
  414.                                         '-o' 'Compression=no'
  415.                                         '-o' 'Ciphers=aes128-cbc,aes128-ctr'
  416.                                         "${c.args[@]}"
  417.                                 )
  418.                                 ;;
  419.                         'nfs')
  420.                                 #
  421.                                 # Validate configuration
  422.                                 #
  423.                                 if [[ -v c.ssh_jumphost_args ]] ; then
  424.                                         print -u2 -f $"%s: Error: SSHNFSJumphost cannot be used for nfs://-URLs\n" "$0"
  425.                                         return 2
  426.                                 fi
  427.                                 if [[ -v c.nfs_server.user ]] ; then
  428.                                         print -u2 -f $"%s: Error: 'user' in URLs is not used in nfs://-URLs\n" "$0"
  429.                                         return 2
  430.                                 fi
  431.                                 if [[ -v c.nfs_server.password ]] ; then
  432.                                         print -u2 -f $"%s: Error: 'password' in URLs is not used in nfs://-URLs\n" "$0"
  433.                                         return 2
  434.                                 fi
  435.  
  436.                                 #
  437.                                 # Guess a TCP port number which might be
  438.                                 # free on the destination machine
  439.                                 #
  440.                                 integer myuid=$(id -u)
  441.                                 integer mypid=$$ # used to circumvent ksh93 -n warning
  442.  
  443.                                 # TCP port on destination machine where we forward the
  444.                                 # NFS port from the server
  445.                                 integer c.destination_nfs_port=33049
  446.  
  447.                                 # try to adjust c.destination_nfs_port so that multiple sshnfs.ksh
  448.                                 # sessions do intefere with each other
  449.                                 # (16381 is a prime number)
  450.                                 (( c.destination_nfs_port += (mypid+myuid+PPID) % 16381 ))
  451.  
  452.                                 print -u2 -f $"# Use this to mount the directory:\n"
  453.                                 print -u2 -f $"# $ mkdir /mnt_nfs\n"
  454.                                 print -u2 -f $"# $ mount -vvv -t nfs -o vers=4.2,port=%d localhost:/%s /mnt_nfs\n" \
  455.                                         c.destination_nfs_port \
  456.                                         "${c.nfs_server.uripath}"
  457.  
  458.                                 #
  459.                                 # add NFS forwarding options to main ssh argument list
  460.                                 #
  461.                                 # Notes:
  462.                                 # - We use aes128-cbc,aes128-ctr ciphers for better
  463.                                 # throughput (see https://bash-prompt.net/guides/bash-ssh-ciphers/
  464.                                 # for a benchmark) and lower latency, as NFS is
  465.                                 # a bit latency-sensitive
  466.                                 # - We turn compression off, as it incrases latency
  467.                                 #
  468.                                 c.args=(
  469.                                         '-R' "${c.destination_nfs_port}:${c.nfs_server.host}:${c.nfs_server.port}"
  470.                                         '-o' 'ExitOnForwardFailure=yes'
  471.                                         '-o' 'Compression=no'
  472.                                         '-o' 'Ciphers=aes128-cbc,aes128-ctr'
  473.                                         "${c.args[@]}"
  474.                                 )
  475.                                 ;;
  476.                         *)
  477.                                 print -u2 -f $"%s: Unknown URL scheme %q\n" "$0" "${c.nfs_server.scheme}"
  478.                                 return 2
  479.                                 ;;
  480.                 esac
  481.         fi
  482.  
  483.         # debug: print application data (compound c)
  484.         ${mydebug} && print -v c
  485.  
  486.         print -u2 -f $"# ssh login data for destination machine:\n"
  487.         ssh "${c.args[@]}" ; (( retval=$? ))
  488.  
  489.         if [[ -v c.ssh_control_socket_name ]] ; then
  490.                 ssh \
  491.                         -S "${c.ssh_control_socket_name}" \
  492.                         -O 'exit' \
  493.                         "${c.nfsserver_ssh_login_name}@${c.nfs_server.host}"
  494.         fi
  495.  
  496.         wait
  497.  
  498.         return $retval
  499. }
  500.  
  501. #
  502. # main
  503. #
  504. main "$@"
  505. exit $?
  506.  
  507. # EOF.

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}




All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at