You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. package Apache::Authn::Redmine;
  2. =head1 Apache::Authn::Redmine
  3. Redmine - a mod_perl module to authenticate webdav subversion users
  4. against redmine database
  5. =head1 SYNOPSIS
  6. This module allow anonymous users to browse public project and
  7. registred users to browse and commit their project. Authentication is
  8. done against the redmine database or the LDAP configured in redmine.
  9. This method is far simpler than the one with pam_* and works with all
  10. database without an hassle but you need to have apache/mod_perl on the
  11. svn server.
  12. =head1 INSTALLATION
  13. For this to automagically work, you need to have a recent reposman.rb
  14. (after r860) and if you already use reposman, read the last section to
  15. migrate.
  16. Sorry ruby users but you need some perl modules, at least mod_perl2,
  17. DBI and DBD::mysql (or the DBD driver for you database as it should
  18. work on allmost all databases).
  19. On debian/ubuntu you must do :
  20. aptitude install libapache-dbi-perl libapache2-mod-perl2 libdbd-mysql-perl
  21. If your Redmine users use LDAP authentication, you will also need
  22. Authen::Simple::LDAP (and IO::Socket::SSL if LDAPS is used):
  23. aptitude install libauthen-simple-ldap-perl libio-socket-ssl-perl
  24. =head1 CONFIGURATION
  25. ## This module has to be in your perl path
  26. ## eg: /usr/lib/perl5/Apache/Authn/Redmine.pm
  27. PerlLoadModule Apache::Authn::Redmine
  28. <Location /svn>
  29. DAV svn
  30. SVNParentPath "/var/svn"
  31. AuthType Basic
  32. AuthName redmine
  33. Require valid-user
  34. PerlAccessHandler Apache::Authn::Redmine::access_handler
  35. PerlAuthenHandler Apache::Authn::Redmine::authen_handler
  36. ## for mysql
  37. RedmineDSN "DBI:mysql:database=databasename;host=my.db.server"
  38. ## for postgres
  39. # RedmineDSN "DBI:Pg:dbname=databasename;host=my.db.server"
  40. RedmineDbUser "redmine"
  41. RedmineDbPass "password"
  42. ## Optional where clause (fulltext search would be slow and
  43. ## database dependant).
  44. # RedmineDbWhereClause "and members.role_id IN (1,2)"
  45. ## Optional credentials cache size
  46. # RedmineCacheCredsMax 50
  47. </Location>
  48. To be able to browse repository inside redmine, you must add something
  49. like that :
  50. <Location /svn-private>
  51. DAV svn
  52. SVNParentPath "/var/svn"
  53. Order deny,allow
  54. Deny from all
  55. # only allow reading orders
  56. <Limit GET PROPFIND OPTIONS REPORT>
  57. Allow from redmine.server.ip
  58. </Limit>
  59. </Location>
  60. and you will have to use this reposman.rb command line to create repository :
  61. reposman.rb --redmine my.redmine.server --svn-dir /var/svn --owner www-data -u http://svn.server/svn-private/
  62. =head1 REPOSITORIES NAMING
  63. A projet repository must be named with the projet identifier. In case
  64. of multiple repositories for the same project, use the project identifier
  65. and the repository identifier separated with a dot:
  66. /var/svn/foo
  67. /var/svn/foo.otherrepo
  68. =head1 MIGRATION FROM OLDER RELEASES
  69. If you use an older reposman.rb (r860 or before), you need to change
  70. rights on repositories to allow the apache user to read and write
  71. S<them :>
  72. sudo chown -R www-data /var/svn/*
  73. sudo chmod -R u+w /var/svn/*
  74. And you need to upgrade at least reposman.rb (after r860).
  75. =head1 GIT SMART HTTP SUPPORT
  76. Git's smart HTTP protocol (available since Git 1.7.0) will not work with the
  77. above settings. Redmine.pm normally does access control depending on the HTTP
  78. method used: read-only methods are OK for everyone in public projects and
  79. members with read rights in private projects. The rest require membership with
  80. commit rights in the project.
  81. However, this scheme doesn't work for Git's smart HTTP protocol, as it will use
  82. POST even for a simple clone. Instead, read-only requests must be detected using
  83. the full URL (including the query string): anything that doesn't belong to the
  84. git-receive-pack service is read-only.
  85. To activate this mode of operation, add this line inside your <Location /git>
  86. block:
  87. RedmineGitSmartHttp yes
  88. Here's a sample Apache configuration which integrates git-http-backend with
  89. a MySQL database and this new option:
  90. SetEnv GIT_PROJECT_ROOT /var/www/git/
  91. SetEnv GIT_HTTP_EXPORT_ALL
  92. ScriptAlias /git/ /usr/libexec/git-core/git-http-backend/
  93. <Location /git>
  94. Order allow,deny
  95. Allow from all
  96. AuthType Basic
  97. AuthName Git
  98. Require valid-user
  99. PerlAccessHandler Apache::Authn::Redmine::access_handler
  100. PerlAuthenHandler Apache::Authn::Redmine::authen_handler
  101. # for mysql
  102. RedmineDSN "DBI:mysql:database=redmine;host=127.0.0.1"
  103. RedmineDbUser "redmine"
  104. RedmineDbPass "xxx"
  105. RedmineGitSmartHttp yes
  106. </Location>
  107. Make sure that all the names of the repositories under /var/www/git/ have a
  108. matching identifier for some project: /var/www/git/myproject and
  109. /var/www/git/myproject.git will work. You can put both bare and non-bare
  110. repositories in /var/www/git, though bare repositories are strongly
  111. recommended. You should create them with the rights of the user running Redmine,
  112. like this:
  113. cd /var/www/git
  114. sudo -u user-running-redmine mkdir myproject
  115. cd myproject
  116. sudo -u user-running-redmine git init --bare
  117. Once you have activated this option, you have three options when cloning a
  118. repository:
  119. - Cloning using "http://user@host/git/repo(.git)" works, but will ask for the password
  120. all the time.
  121. - Cloning with "http://user:pass@host/git/repo(.git)" does not have this problem, but
  122. this could reveal accidentally your password to the console in some versions
  123. of Git, and you would have to ensure that .git/config is not readable except
  124. by the owner for each of your projects.
  125. - Use "http://host/git/repo(.git)", and store your credentials in the ~/.netrc
  126. file. This is the recommended solution, as you only have one file to protect
  127. and passwords will not be leaked accidentally to the console.
  128. IMPORTANT NOTE: It is *very important* that the file cannot be read by other
  129. users, as it will contain your password in cleartext. To create the file, you
  130. can use the following commands, replacing yourhost, youruser and yourpassword
  131. with the right values:
  132. touch ~/.netrc
  133. chmod 600 ~/.netrc
  134. echo -e "machine yourhost\nlogin youruser\npassword yourpassword" > ~/.netrc
  135. =cut
  136. use strict;
  137. use warnings FATAL => 'all', NONFATAL => 'redefine';
  138. use DBI;
  139. use Digest::SHA;
  140. # optional module for LDAP authentication
  141. my $CanUseLDAPAuth = eval("use Authen::Simple::LDAP; 1");
  142. use Apache2::Module;
  143. use Apache2::Access;
  144. use Apache2::ServerRec qw();
  145. use Apache2::RequestRec qw();
  146. use Apache2::RequestUtil qw();
  147. use Apache2::Const qw(:common :override :cmd_how);
  148. use APR::Pool ();
  149. use APR::Table ();
  150. # use Apache2::Directive qw();
  151. my @directives = (
  152. {
  153. name => 'RedmineDSN',
  154. req_override => OR_AUTHCFG,
  155. args_how => TAKE1,
  156. errmsg => 'Dsn in format used by Perl DBI. eg: "DBI:Pg:dbname=databasename;host=my.db.server"',
  157. },
  158. {
  159. name => 'RedmineDbUser',
  160. req_override => OR_AUTHCFG,
  161. args_how => TAKE1,
  162. },
  163. {
  164. name => 'RedmineDbPass',
  165. req_override => OR_AUTHCFG,
  166. args_how => TAKE1,
  167. },
  168. {
  169. name => 'RedmineDbWhereClause',
  170. req_override => OR_AUTHCFG,
  171. args_how => TAKE1,
  172. },
  173. {
  174. name => 'RedmineCacheCredsMax',
  175. req_override => OR_AUTHCFG,
  176. args_how => TAKE1,
  177. errmsg => 'RedmineCacheCredsMax must be decimal number',
  178. },
  179. {
  180. name => 'RedmineGitSmartHttp',
  181. req_override => OR_AUTHCFG,
  182. args_how => TAKE1,
  183. },
  184. );
  185. sub RedmineDSN {
  186. my ($self, $parms, $arg) = @_;
  187. $self->{RedmineDSN} = $arg;
  188. my $query = "SELECT
  189. users.hashed_password, users.salt, users.auth_source_id, roles.permissions, projects.status
  190. FROM projects, users, roles
  191. WHERE
  192. users.login=?
  193. AND projects.identifier=?
  194. AND users.status=1
  195. AND (
  196. roles.id IN (SELECT member_roles.role_id FROM members, member_roles WHERE members.user_id = users.id AND members.project_id = projects.id AND members.id = member_roles.member_id)
  197. OR
  198. (cast(projects.is_public as CHAR) IN ('t', '1')
  199. AND (roles.builtin=1
  200. OR roles.id IN (SELECT member_roles.role_id FROM members, member_roles, users g
  201. WHERE members.user_id = g.id AND members.project_id = projects.id AND members.id = member_roles.member_id
  202. AND g.type = 'GroupNonMember'))
  203. )
  204. )
  205. AND roles.permissions IS NOT NULL";
  206. $self->{RedmineQuery} = trim($query);
  207. }
  208. sub RedmineDbUser { set_val('RedmineDbUser', @_); }
  209. sub RedmineDbPass { set_val('RedmineDbPass', @_); }
  210. sub RedmineDbWhereClause {
  211. my ($self, $parms, $arg) = @_;
  212. $self->{RedmineQuery} = trim($self->{RedmineQuery}.($arg ? $arg : "")." ");
  213. }
  214. sub RedmineCacheCredsMax {
  215. my ($self, $parms, $arg) = @_;
  216. if ($arg) {
  217. $self->{RedmineCachePool} = APR::Pool->new;
  218. $self->{RedmineCacheCreds} = APR::Table::make($self->{RedmineCachePool}, $arg);
  219. $self->{RedmineCacheCredsCount} = 0;
  220. $self->{RedmineCacheCredsMax} = $arg;
  221. }
  222. }
  223. sub RedmineGitSmartHttp {
  224. my ($self, $parms, $arg) = @_;
  225. $arg = lc $arg;
  226. if ($arg eq "yes" || $arg eq "true") {
  227. $self->{RedmineGitSmartHttp} = 1;
  228. } else {
  229. $self->{RedmineGitSmartHttp} = 0;
  230. }
  231. }
  232. sub trim {
  233. my $string = shift;
  234. $string =~ s/\s{2,}/ /g;
  235. return $string;
  236. }
  237. sub set_val {
  238. my ($key, $self, $parms, $arg) = @_;
  239. $self->{$key} = $arg;
  240. }
  241. Apache2::Module::add(__PACKAGE__, \@directives);
  242. my %read_only_methods = map { $_ => 1 } qw/GET HEAD PROPFIND REPORT OPTIONS/;
  243. sub request_is_read_only {
  244. my ($r) = @_;
  245. my $cfg = Apache2::Module::get_config(__PACKAGE__, $r->server, $r->per_dir_config);
  246. # Do we use Git's smart HTTP protocol, or not?
  247. if (defined $cfg->{RedmineGitSmartHttp} and $cfg->{RedmineGitSmartHttp}) {
  248. my $uri = $r->unparsed_uri;
  249. my $location = $r->location;
  250. my $is_read_only = $uri !~ m{^$location/*[^/]+/+(info/refs\?service=)?git\-receive\-pack$}o;
  251. return $is_read_only;
  252. } else {
  253. # Standard behaviour: check the HTTP method
  254. my $method = $r->method;
  255. return defined $read_only_methods{$method};
  256. }
  257. }
  258. sub access_handler {
  259. my $r = shift;
  260. unless ($r->some_auth_required) {
  261. $r->log_reason("No authentication has been configured");
  262. return FORBIDDEN;
  263. }
  264. return OK unless request_is_read_only($r);
  265. my $project_id = get_project_identifier($r);
  266. $r->set_handlers(PerlAuthenHandler => [\&OK])
  267. if is_public_project($project_id, $r) && anonymous_allowed_to_browse_repository($project_id, $r);
  268. return OK
  269. }
  270. sub authen_handler {
  271. my $r = shift;
  272. my ($res, $redmine_pass) = $r->get_basic_auth_pw();
  273. return $res unless $res == OK;
  274. if (is_member($r->user, $redmine_pass, $r)) {
  275. return OK;
  276. } else {
  277. $r->note_auth_failure();
  278. return DECLINED;
  279. }
  280. }
  281. # check if authentication is forced
  282. sub is_authentication_forced {
  283. my $r = shift;
  284. my $dbh = connect_database($r);
  285. my $sth = $dbh->prepare(
  286. "SELECT value FROM settings where settings.name = 'login_required';"
  287. );
  288. $sth->execute();
  289. my $ret = 0;
  290. if (my @row = $sth->fetchrow_array) {
  291. if ($row[0] eq "1" || $row[0] eq "t") {
  292. $ret = 1;
  293. }
  294. }
  295. $sth->finish();
  296. undef $sth;
  297. $dbh->disconnect();
  298. undef $dbh;
  299. $ret;
  300. }
  301. sub is_public_project {
  302. my $project_id = shift;
  303. my $r = shift;
  304. if (is_authentication_forced($r)) {
  305. return 0;
  306. }
  307. my $dbh = connect_database($r);
  308. my $sth = $dbh->prepare(
  309. "SELECT is_public FROM projects WHERE projects.identifier = ? AND projects.status <> 9;"
  310. );
  311. $sth->execute($project_id);
  312. my $ret = 0;
  313. if (my @row = $sth->fetchrow_array) {
  314. if ($row[0] eq "1" || $row[0] eq "t") {
  315. $ret = 1;
  316. }
  317. }
  318. $sth->finish();
  319. undef $sth;
  320. $dbh->disconnect();
  321. undef $dbh;
  322. $ret;
  323. }
  324. sub anonymous_allowed_to_browse_repository {
  325. my $project_id = shift;
  326. my $r = shift;
  327. my $dbh = connect_database($r);
  328. my $sth = $dbh->prepare(
  329. "SELECT permissions FROM roles WHERE permissions like '%browse_repository%'
  330. AND (roles.builtin = 2
  331. OR roles.id IN (SELECT member_roles.role_id FROM projects, members, member_roles, users
  332. WHERE members.user_id = users.id AND members.project_id = projects.id AND members.id = member_roles.member_id
  333. AND projects.identifier = ? AND users.type = 'GroupAnonymous'));"
  334. );
  335. $sth->execute($project_id);
  336. my $ret = 0;
  337. if (my @row = $sth->fetchrow_array) {
  338. if ($row[0] =~ /:browse_repository/) {
  339. $ret = 1;
  340. }
  341. }
  342. $sth->finish();
  343. undef $sth;
  344. $dbh->disconnect();
  345. undef $dbh;
  346. $ret;
  347. }
  348. # perhaps we should use repository right (other read right) to check public access.
  349. # it could be faster BUT it doesn't work for the moment.
  350. # sub is_public_project_by_file {
  351. # my $project_id = shift;
  352. # my $r = shift;
  353. # my $tree = Apache2::Directive::conftree();
  354. # my $node = $tree->lookup('Location', $r->location);
  355. # my $hash = $node->as_hash;
  356. # my $svnparentpath = $hash->{SVNParentPath};
  357. # my $repos_path = $svnparentpath . "/" . $project_id;
  358. # return 1 if (stat($repos_path))[2] & 00007;
  359. # }
  360. sub is_member {
  361. my $redmine_user = shift;
  362. my $redmine_pass = shift;
  363. my $r = shift;
  364. my $project_id = get_project_identifier($r);
  365. my $pass_digest = Digest::SHA::sha1_hex($redmine_pass);
  366. my $access_mode = request_is_read_only($r) ? "R" : "W";
  367. my $cfg = Apache2::Module::get_config(__PACKAGE__, $r->server, $r->per_dir_config);
  368. my $usrprojpass;
  369. if ($cfg->{RedmineCacheCredsMax}) {
  370. $usrprojpass = $cfg->{RedmineCacheCreds}->get($redmine_user.":".$project_id.":".$access_mode);
  371. return 1 if (defined $usrprojpass and ($usrprojpass eq $pass_digest));
  372. }
  373. my $dbh = connect_database($r);
  374. my $query = $cfg->{RedmineQuery};
  375. my $sth = $dbh->prepare($query);
  376. $sth->execute($redmine_user, $project_id);
  377. my $ret;
  378. while (my ($hashed_password, $salt, $auth_source_id, $permissions, $project_status) = $sth->fetchrow_array) {
  379. if ($project_status eq "9" || ($project_status ne "1" && $access_mode eq "W")) {
  380. last;
  381. }
  382. unless ($auth_source_id) {
  383. my $method = $r->method;
  384. my $salted_password = Digest::SHA::sha1_hex($salt.$pass_digest);
  385. if ($hashed_password eq $salted_password && (($access_mode eq "R" && $permissions =~ /:browse_repository/) || $permissions =~ /:commit_access/) ) {
  386. $ret = 1;
  387. last;
  388. }
  389. } elsif ($CanUseLDAPAuth) {
  390. my $sthldap = $dbh->prepare(
  391. "SELECT host,port,tls,account,account_password,base_dn,attr_login from auth_sources WHERE id = ?;"
  392. );
  393. $sthldap->execute($auth_source_id);
  394. while (my @rowldap = $sthldap->fetchrow_array) {
  395. my $bind_as = $rowldap[3] ? $rowldap[3] : "";
  396. my $bind_pw = $rowldap[4] ? $rowldap[4] : "";
  397. if ($bind_as =~ m/\$login/) {
  398. # replace $login with $redmine_user and use $redmine_pass
  399. $bind_as =~ s/\$login/$redmine_user/g;
  400. $bind_pw = $redmine_pass
  401. }
  402. my $ldap = Authen::Simple::LDAP->new(
  403. host => ($rowldap[2] eq "1" || $rowldap[2] eq "t") ? "ldaps://$rowldap[0]:$rowldap[1]" : $rowldap[0],
  404. port => $rowldap[1],
  405. basedn => $rowldap[5],
  406. binddn => $bind_as,
  407. bindpw => $bind_pw,
  408. filter => "(".$rowldap[6]."=%s)"
  409. );
  410. my $method = $r->method;
  411. $ret = 1 if ($ldap->authenticate($redmine_user, $redmine_pass) && (($access_mode eq "R" && $permissions =~ /:browse_repository/) || $permissions =~ /:commit_access/));
  412. }
  413. $sthldap->finish();
  414. undef $sthldap;
  415. }
  416. }
  417. $sth->finish();
  418. undef $sth;
  419. $dbh->disconnect();
  420. undef $dbh;
  421. if ($cfg->{RedmineCacheCredsMax} and $ret) {
  422. if (defined $usrprojpass) {
  423. $cfg->{RedmineCacheCreds}->set($redmine_user.":".$project_id.":".$access_mode, $pass_digest);
  424. } else {
  425. if ($cfg->{RedmineCacheCredsCount} < $cfg->{RedmineCacheCredsMax}) {
  426. $cfg->{RedmineCacheCreds}->set($redmine_user.":".$project_id.":".$access_mode, $pass_digest);
  427. $cfg->{RedmineCacheCredsCount}++;
  428. } else {
  429. $cfg->{RedmineCacheCreds}->clear();
  430. $cfg->{RedmineCacheCredsCount} = 0;
  431. }
  432. }
  433. }
  434. $ret;
  435. }
  436. sub get_project_identifier {
  437. my $r = shift;
  438. my $cfg = Apache2::Module::get_config(__PACKAGE__, $r->server, $r->per_dir_config);
  439. my $location = $r->location;
  440. $location =~ s/\.git$// if (defined $cfg->{RedmineGitSmartHttp} and $cfg->{RedmineGitSmartHttp});
  441. my ($identifier) = $r->uri =~ m{$location/*([^/.]+)};
  442. $identifier;
  443. }
  444. sub connect_database {
  445. my $r = shift;
  446. my $cfg = Apache2::Module::get_config(__PACKAGE__, $r->server, $r->per_dir_config);
  447. return DBI->connect($cfg->{RedmineDSN}, $cfg->{RedmineDbUser}, $cfg->{RedmineDbPass});
  448. }
  449. 1;