dpcnm2132 2016-07-02 11:14
浏览 157
已采纳

带有TLS的PHP用于安全LDAP

I am trying to use remote LDAP server. For the purpose of security, I am trying to use only secure connection. I am able to get some code working but I am not sure, given the PHP documentation of start TLS itself, that if the following code works only on secure channel. Can anyone help with this please?

$is_valid_user = FALSE;

try {
    $ds = ldap_connect('ldap.foo.com', 389);
    if (! ldap_set_option($ds, LDAP_OPT_REFERRALS, 0)) {
        return "";
    }

    if (! ldap_start_tls($ds)) {
        return "";
    }
} catch(Exception $e) {
    return "";
}

if (! ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
    $error = "LDAP Server protocol error.";
    return "";
}

try {
    $bnd = @ldap_bind($ds, 'uid='.$user.', ou=people, dc=ldap, dc=foo, dc=com' , $passwd);

    if ($bnd) {
        $is_valid_user = TRUE;

        $srch=ldap_search($ds, 'dc=ldap, dc=foo, dc=com', "uid=$user");
        $info=ldap_get_entries($ds, $srch);
        $userdn=$info[0]["dn"];
        $usernm=$info[0]["cn"][0];

        return $usernm;
    } else {
        return "";
    }
} catch(Exception $e) {
    return "";
}
  • 写回答

1条回答 默认 最新

  • doulu6929 2016-07-02 20:31
    关注

    Just a few general improvements below. And yes, how that's written it will not continue unless the connection is encrypted via TLS. The LDAP module doesn't throw any exceptions at the moment, so the try/catch block is not really needed. Hard to tell without seeing the rest of your code, but is there a reason you want to return an empty string instead of false or null or some sort of error message?

    $is_valid_user = false;
    
    $ds = ldap_connect('ldap.foo.com', 389);
    ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    
    if (!@ldap_start_tls($ds)) {
        return "";
    }
    
    $bindUser = 'uid='.ldap_escape($user, null, LDAP_ESCAPE_DN).',ou=people,dc=ldap,dc=foo,dc=com';
    if (@ldap_bind($ds, $bindUser , $passwd)) {
        $is_valid_user = true;
    
        $srch = ldap_search($ds, $bindUser, '(objectClass=*)', ['cn']);
        $info = ldap_get_entries($ds, $srch);
        $userdn = $info[0]["dn"];
        $usernm = $info[0]["cn"][0];
    
        return $usernm;
    } else {
        return "";
    }
    

    There are also several LDAP libraries available that make LDAP much easier with PHP. I would recommend LdapTools or adldap2.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决