encrypt controll channel using ssh
[bak-git.git] / bak-git-server.pl
1 #!/usr/bin/perl
2
3 =head1 bak-git
4
5 Simple tracking of remote files in central git repository
6 with only shell, netcat, rsync and ssh on client
7
8 Start server, install on remote-host or upgrade with:
9
10   ./bak-git-server.pl /path/to/backup 192.168.42.42
11         [--install remote-host]
12         [--upgrade]
13
14 C<rsync> traffic is always transfered over ssh, but C<diff> or C<ch> can
15 still leak sensitive information if C<bak> shell client connects directly
16 to server host.
17
18 Add following line to C<~/.ssh/config> under C<Host> for which you want encrypted
19 controll channel (or to pass through server ssh hops using C<ProxyCommand>)
20
21   RemoteForward 9001 192.168.42.42:9001
22
23 bak command overview:
24
25   bak add /path
26   bak commit [/path [message]]
27   bak diff [host:][/path]
28   bak status [/path]
29   bak log [/path]
30
31   bak ch[anges]
32   bak revert [host:]/path
33
34   bak cat [host:]/path
35
36   bak - push all changed files to server
37
38 See L<http://blog.rot13.org/bak-git> for more information
39
40 =cut
41
42 use warnings;
43 use strict;
44 use autodie;
45 use IO::Socket::INET;
46 use File::Path;
47 use Getopt::Long;
48
49 my $upgrade = 0;
50 my $install;
51
52 GetOptions(
53         'upgrade!'  => \$upgrade,
54         'install=s' => \$install,
55 ) || die "$!\n";
56
57 my ( $dir, $server_ip ) = @ARGV;
58 die "usage: $0 /backup/directory 127.0.0.1\n" unless $dir;
59 $server_ip ||= '127.0.0.1';
60
61 # parse ssh config
62 my $ssh_tunnel;
63 open(my $ssh_fd, '<', "$ENV{HOME}/.ssh/config");
64 my $host;
65 while(<$ssh_fd>) {
66         chomp;
67         next unless length($_) > 0;
68         next if m/^\s*#/;
69
70         if ( /^Host\s+(.+)/i ) {
71                 $host = $1;
72         } elsif ( /^\s+(\S+)\s+(.+)/ ) {
73                 $ssh_tunnel->{$host}++ if lc($1) eq 'remoteforward' && $2 =~ m/9001/;
74         } else {
75                 die "can't parse $_";
76         }
77 }
78
79 sub shell_client {
80         my ( $hostname ) = @_;
81         my $path = '/tmp/bak';
82         my $server = $server_ip;
83         $server = '127.0.0.1' if $ssh_tunnel->{$hostname};
84 warn "# ssh_client $hostname $server";
85         open(my $fh, '>', $path);
86         print $fh "#!/bin/sh\n";
87         print $fh "echo \$USER/\$SUDO_USER $hostname `pwd` \$* | nc $server 9001\n";
88         close($fh);
89         chmod 0755, $path;
90         return $path;
91 }
92
93 chdir $dir;
94 system 'git init' unless -e '.git';
95
96 if ( $upgrade || $install ) {
97
98         my @hosts = grep { -d $_ } glob '*';
99         @hosts = ( $install ) if $install;
100
101         foreach my $hostname ( @hosts ) {
102                 warn "install on $hostname\n";
103                 system 'ssh-copy-id', "root\@$hostname" if ! -d $hostname;
104                 my $path = shell_client( $hostname );
105                 system "scp $path root\@$hostname:/usr/local/bin/";
106                 system "ssh root\@$hostname apt-get install -y rsync";
107         }
108 } else {
109         warn "# start ssh tunnels...";
110         foreach my $host ( keys %$ssh_tunnel ) {
111                 warn "## $host\n";
112                 open( $ssh_tunnel->{$host}, '-|', "ssh -N root\@$host &" ) or die $!;
113         }
114 }
115
116 my $server = IO::Socket::INET->new(
117         Proto     => 'tcp',
118         LocalAddr => $server_ip,
119         LocalPort => 9001,
120         Listen    => SOMAXCONN,
121         Reuse     => 1
122 ) || die $!;
123
124
125 warn "dir: $dir listen: $server_ip:9001\n";
126
127 sub rsync {
128         warn "# rsync ",join(' ', @_), "\n";
129         system 'rsync', @_;
130 }
131
132 sub pull_changes {
133         my $hostname = shift;
134         system "find $hostname -type f | sed 's,$hostname,,' > /tmp/$hostname.list";
135         if ( @_ ) {
136                 open(my $files, '>>', "/tmp/$hostname.list");
137                 print $files "$_\n" foreach @_;
138                 close($files);
139         }
140         rsync split / /, "-avv --files-from /tmp/$hostname.list root\@$hostname:/ $hostname/";
141 }
142
143 while (my $client = $server->accept()) {
144         my $line = <$client>;
145         chomp($line);
146         warn "<<< $line\n";
147         my ($user,$hostname,$pwd,$command,$rel_path,$message) = split(/\s+/,$line,6);
148         $hostname =~ s/\..+$//;
149
150         my $on_host = '';
151         if ( $rel_path =~ s/^([^:]+):(.+)$/$2/ ) {
152                 if ( -e $1 ) {
153                         $on_host = $1;
154                 } else {
155                         print $client "host $1 doesn't exist in backup\n";
156                         next;
157                 }
158         }
159         my $path = $rel_path =~ m{^/} ? $rel_path : "$pwd/$rel_path";
160
161         warn "$hostname [$command] $on_host:$path | $message\n";
162
163         my $args_message = $message;
164
165         $message ||= "$path [$command]";
166         $message = "$hostname: $message";
167
168         my $dir = $path;
169         $dir =~ s{/[^/]+$}{};
170
171         my $backup_path = -e "$hostname/$path" ? "$hostname/$path" : $hostname;
172
173         sub git {
174                 my $args = join(' ',@_);
175                 warn "# git $args\n";
176                 my $out = `git $args`;
177                 warn "$out\n# [", length($out), " bytes]\n" if defined $out;
178                 return $out;
179         }
180
181         if ( ! $command ) {
182                 pull_changes $hostname;
183         } elsif ( $command eq 'add' ) {
184                 mkpath "$hostname/$dir" unless -e "$hostname/$dir";
185                 while ( $path ) {
186                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
187                         print $client git 'add', "$hostname/$path";
188
189                         $args_message =~ s/^(.+)\b// || last;
190                         $path = $1;
191                         warn "? $path";
192                 }
193         } elsif ( $command eq 'commit' ) {
194                 pull_changes $hostname;
195                 $message =~ s/'/\\'/g;
196                 $user =~ s/\/$//;
197                 print $client git( "commit -m '$message' --author '$user <$hostname>' $backup_path" );
198         } elsif ( $command =~ m{(diff|status|log|ch)} ) {
199                 $command .= ' --stat' if $command eq 'log';
200                 $command = 'log --patch-with-stat' if $command =~ m/^ch/;
201                 pull_changes( $hostname ) if $command eq 'diff';
202                 if ( $on_host ) {
203                         mkpath $_ foreach grep { ! -e $_ } ( "$hostname/$dir", "$on_host/$dir" );
204                         rsync( '-avv', "root\@$hostname:$path", "$hostname/$path" );
205                         rsync( '-avv', "root\@$on_host:$path", "$on_host/$path" );
206                         open(my $diff, '-|', "diff -Nuw $hostname$path $on_host$path");
207                         while(<$diff>) {
208                                 print $client $_;
209                         }
210                 } else {
211                         # commands without path will show host-wide status/changes
212                         my $backup_path = $path ? "$hostname/$path" : "$hostname/";
213                         # hostname must end with / to prevent error from git:
214                         # ambiguous argument 'arh-hw': both revision and filename
215                         # to support branches named as hosts
216                         print $client git($command, $backup_path);
217                 }
218         } elsif ( $command eq 'revert' ) {
219                 if ( $on_host ) {
220                         rsync( '-avv', "$on_host/$path", "root\@$hostname:$path" );
221                 } else {
222                         print $client git "checkout -- $hostname/$path";
223                         rsync( '-avv', "$hostname/$path", "root\@$hostname:$path" );
224                 }
225         } elsif ( $command eq 'cat' ) {
226                 my $file_path = ( $on_host ? $on_host : $hostname ) . "/$path";
227                 open(my $file, '<', $file_path) || warn "ERROR $file_path: $!";
228                 while(<$file>) {
229                         print $client $_;
230                 }
231                 close($file);
232         } elsif ( $command eq 'ls' ) {
233                 print $client `ls $backup_path`;
234         } else {
235                 print $client "Unknown command: $command\n";
236         }
237
238 }
239