首页 文章

为每个请求创建一个自定义apache模块钩子?

提问于
浏览
1

对于一个项目,我需要在apache级别进行HMAC身份验证 . 所以我扩展了mod_example,解释了here到此为止:

module AP_MODULE_DECLARE_DATA   hmac_module =
        {
                STANDARD20_MODULE_STUFF,
                NULL,            // Per-directory configuration handler
                NULL,            // Merge handler for per-directory configurations
                NULL,            // Per-server configuration handler
                NULL,            // Merge handler for per-server configurations
                NULL,            // Any directives we may have for httpd
                register_hooks   // Our hook registering function
        };


/* register_hooks: Adds a hook to the httpd process */
static void register_hooks(apr_pool_t *pool)
{

    /* Hook the request handler */
    ap_hook_handler(hmac_handler, NULL, NULL,APR_HOOK_REALLY_FIRST);
}

static int hmac_handler(request_rec *r)
{
    // ...
    // some variable definition
    // ...

    // Check that the "hmac-handler" handler is being called.
    if (!r->handler || strcmp(r->handler, "hmac-handler")) return (DECLINED);

    ap_args_to_table(r, &GET);
    ap_parse_form_data(r, NULL, &POST, -1, 8192);

    timestamp = apr_table_get(r->headers_in, "X-EPOCH");
    claimedHash = apr_table_get(r->headers_in, "X-HMAC");
    if (!timestamp){
        ap_log_rerror(APLOG_MARK,APLOG_ERR,HTTP_FORBIDDEN,r,"Timestamp does not exits in request");
        return HTTP_FORBIDDEN;
    }
    if(!claimedHash){
        ap_log_rerror(APLOG_MARK,APLOG_ERR,HTTP_FORBIDDEN,r,"There is no claimed hash in the request!");
        return HTTP_FORBIDDEN;
    }

    //...
    // calculate timestamp's sha1 hash
    //...

    if(strcmp(claimedHash,encoded)){
        ap_log_rerror(APLOG_MARK,APLOG_ERR,HTTP_FORBIDDEN,r,"Claimed hash and digested values does not match,Claimed:%s , Target:%s",claimedHash,encoded);
        return HTTP_FORBIDDEN;
    }

    // Let Apache know that we responded to this request.
    return OK;
}

现在,我需要在进一步处理之前将此模块挂钩到apache中,以便检查此请求是否经过身份验证 .

我知道 ap_hook_handler 函数中的 APR_HOOK_REALLY_FIRST 参数使apache在任何其他处理程序之前执行此处理程序 .

但我需要知道如何在特定目录中发生的任何请求之前执行此处理程序 .

1 回答

  • 1

    我终于把它弄清楚了 . 我应该在早期阶段注册我的模块:access_checker,而不是在处理程序阶段注册钩子 .

    如果有兴趣,最终代码可在github获取 .

相关问题