pastebin - collaborative debugging tool
rovema.kpaste.net RSS


sshnfs - ssh with nfs forwarding
Posted by Anonymous on Wed 19th Jul 2023 14:55
raw | new post
view followups (newest first): sshnfs - ssh with nfs forwarding by Anonymous
modification of post by Anonymous (view diff)

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