GVKun编程网logo

杂记(php session)(侍卫官杂记)

1

本文将分享杂记的详细内容,并且还将对phpsession进行详尽解释,此外,我们还将为大家带来关于ASP.NETSessionandFormsAuthenticationandSessionFixat

本文将分享杂记的详细内容,并且还将对php session进行详尽解释,此外,我们还将为大家带来关于ASP.NET Session and Forms Authentication and Session Fixation、ch.ethz.ssh2.Session 和 com.jcraft.jsch.Session、ci 框架的 session 类,怎么使用 ci 的 session 类、Cloud Foundry Session Affinity(Sticky Session)的实现的相关知识,希望对你有所帮助。

本文目录一览:

杂记(php session)(侍卫官杂记)

杂记(php session)(侍卫官杂记)

如果php.ini  文件 

session.auto_start  = 0

而导致程序无法运行时,可以尝试在程序设置

$config[''sess_save_path''] = ''/tmp'';

ASP.NET Session and Forms Authentication and Session Fixation

ASP.NET Session and Forms Authentication and Session Fixation

https://peterwong.net/blog/asp-net-session-and-forms-authentication/

The title can be misleading, because in concept, one is not related to the other.  However, a lot of web applications mix them up, causing bugs that are hard to troubleshoot, and, at worst, causing security vulnerabilities.

A little bit of background on each one.  ASP.NET sessions are used to keep track and keep information related to a “user” session.  When a web server is initially accessed by a browser, the server generates a unique session ID, and sends that session ID to the browser as the value of a cookie (the name of the cookie is ASP.NET_SessionId).  Along with that session ID, a dictionary of objects on the server, often referred to as session state, is allocated corresponding to that session ID.  This dictionary can be used to keep track of information unique to that session.  For example, it could be used to keep track of items placed in a shopping cart metaphor.

Note that this “session” can exist even if the user has not authenticated.  And this is often useful.  In a retail web site (like Amazon), you can put items in your shopping cart, and only need to authenticate or sign on when you are ready to checkout — and even then, you can actually make a purchase without needing to authenticate, provided, of course, that a valid credit card is used.

Because this “session” is disjoint from authentication, it is better referred to as a “browser” session instead of as a “user” session.  In a kiosk environment, if a user walks away from the kiosk while there are items in a shopping cart, the next user to use the kiosk will still see the same shopping cart.  The web server doesn’t know any better that a different user is using the kiosk, because the same session ID is being sent back in the session cookie during interaction with the web server.

That dictionary of objects on the server, the session state, also poses certain complications that most developers are aware of.  In a web farm, some form of sticky load balancer has to be used so that session state can be kept in memory.  Or a centralized store for the session state is used to make the state consistent across the servers in the web farm.  In either case, service performance can be affected.  I have a very strong opinion against using session state.  I avoid it, if at all possible.

What about Forms Authentication?  Forms Authentication is the most common authentication mechanism for ASP.NET web sites.  When a user is authenticated, most commonly using a user ID and password, a Forms Authentication cookie is generated and is sent to the browser (the name of the cookie, by default, is .ASPXAUTH).  The cookie contains the encrypted form of an authentication ticket that contains, among other things, the user ID that uniquely identifies the user.  The same cookie is sent to the web server on each HTTP request, so the web server has an idea of the user identity to correlate to a particular HTTP request.

Everything I mentioned above is common knowledge for web developers.  Trouble and confusion only comes about when an expectation is made that an ASP.NET session can be associated with ASP.NET authentication.  To be clear, it can be done, but precautionary measures have to be taken.

The problem is related to session hijacking, but better known as session fixation.  Assuming that you’ve done your diligence of using SSL/TLS and HttpOnly cookies, there isn’t a big risk of having the session ID stolen/hijacked by sniffing the network.  And most applications also perform some session cleanup when the user logs out.  Some applications even ensure that a new session ID is created when the user logs in, thinking that this is enough to correlate a session state with a user identity.

Remember that the session cookie and the forms authentication cookie are two different cookies.  If the two are not synchronized, the web server could potentially allow or disallow some operations incorrectly.

Here’s a hypothetical (albeit unrealistic) scenario.  A banking application puts a savings account balance into session state once the user logs in.  Perhaps it is computationally expensive to obtain the account balance, so to improve performance, it is kept at session state.  The application ensures that a new session ID is created after the user logs in and clears the session state when the user logs out.  This prevents the occurrence of one user reusing the session state of another user.  Does it really prevent it?  No.

As an end-user having control of my browser, I am privy to the traffic/data that the browser receives.  With the appropriate tools like Fiddler2 or Firebug, I can see the session and forms authentication cookies.  I may not be able to tamper them (i.e., the forms authentication cookie is encrypted and hashed to prevent tampering), but I could still capture them and store them for a subsequent replay attack.

In the hypothetical banking application above, I initially log in and get SessionIDCookie1 and FormsAuthCookie1.  Let’s say the account balance stored in session state corresponding to SessionIDCookie1 is $100. 

I don’t log out, but open up another window/tab and somehow prevent (through Fiddler2 maybe) the cookies from being sent through the second window.  I log in to that second window. 

The web server, noting that the request from the second window has no cookies, starts off another session state, and also returns SessionIDCookie2 and FormsAuthCookie2

Browsers usually overwrite cookies with the same names, so my SessionCookieID2 and FormsAuthCookie2 are my new session ID and forms authentication cookies. 

But remember that I captured SessionIDCookie1 and FormsAuthCookie1 to use in a future attack.

In that second window, I transfer $80 away from my account, thereby updating the session state corresponding to SessionIDCookie2 to be $20.  I cannot make another $80 transfer in the second window because I do not have sufficient funds.

Note that SessionIDCookie1 has not been cleaned up and there is a session state on the server corresponding to SessionIDCookie1 which still thinks that the account balance is $100.  I now perform my replay attack, sending to the web server SessionIDCookie1 and FormsAuthCookie1.  For that given session state, I can make another $80 transfer away from my account.

You might say that the application could easily keep track of the forms authentication cookie issued for a particular user, so that when FormsAuthCookie2 is issued, FormsAuthCookie1 becomes invalid and will be rejected by the server.  But what if I use SessionIDCookie1 and FormsAuthCookie2 on the second window?  It’s the same result — I can make another $80 transfer away from my account.

Oh, you might say that the application should invalidate SessionIDCookie1 when SessionIDCookie2 is issued.  Sure, but how?  Unlike the forms authentication cookies, where the user identity is the same within both cookies, there is nothing common between SessionIDCookie1 and SessionIDCookie2.  And since there is nothing relating SessionIDCookies with FormsAuthCookies, there’s no mechanism to search for and invalidate SessionIDCookie1.

The only workaround for this is custom code that ties a SessionIDCookie with the FormsAuthCookie that was issued for the same logical session.  One of the following options should provide a solution.

  • Key your session states by an authenticated user ID instead of by a session ID.  No need for the session cookie.  This will not work for applications that need to keep track of session without authentication (e.g., online shopping).
  • Store the session ID as part of the payload for the forms authentication cookie.  Verify that the session ID in the session cookie is the same as that stored in the forms authentication cookie.  Keep track of the forms authentication issued for each user so that only a single forms authentication cookie (the most recently issued) is valid for the same user.

Maybe an overarching solution is to avoid storing user-specific information in the session state.  Remember that it is a “browser” session state, and has nothing to do with an authenticated user.  If you keep that in mind and only store “browser”-related information into session state, then you could avoid the problems altogether.

ASP.NET session fixation is not a very publicized problem, but is potentially a big risk, specially if improper assumptions are made with regard to session and authentication.  ASP.NET session fixation is also described long back in http://software-security.sans.org/blog/2009/06/14/session-attacks-and-aspnet-part-1/, and been reported through Microsoft Connect http://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=143361, but to my knowledge, has not been addressed within the ASP.NET framework itself.

ch.ethz.ssh2.Session 和 com.jcraft.jsch.Session

ch.ethz.ssh2.Session 和 com.jcraft.jsch.Session

通过 Jsch 连接
step 1 引入 jar 包
<!-- jcraft 包 -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>

step 2 代码
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class Main {
    public static void main(String[] args) throws Exception {
        long currentTimeMillis = System.currentTimeMillis();

        String command = "uname -a";
 
        JSch jsch = new JSch();
        Session session = jsch.getSession("xfraud", "192.168.115.64", 22);
        session.setPassword("cfca1234");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(60 * 1000);
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
 
        channel.setInputStream(null);
 
        ((ChannelExec) channel).setErrStream(System.err);
 
        InputStream in = channel.getInputStream();
 
        channel.connect();
 
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0) continue;
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
 
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println ("Jsch 方式"+(currentTimeMillis1-currentTimeMillis));
    }

}
 

通过 ganymed-ssh2 连接
step 1 引入 jar 包
<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>

</dependency>

step 2 代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

//import org.apache.commons.lang.StringUtils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class MainCommand {
    private static String DEFAULTCHART = "UTF-8";

    private static Connection login(String ip, String username, String password) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = new Connection(ip);
            connection.connect ();// 连接
            flag = connection.authenticateWithPassword (username, password);// 认证
            if (flag) {
                System.out.println ("================ 登录成功 ==================");
                return connection;
            }
        } catch (IOException e) {
            System.out.println ("========= 登录失败 =========" + e);
            connection.close();
        }
        return connection;
    }

    /**
     * 远程执行 shll 脚本或者命令
     * 
     * @param cmd
     *            即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    private static String execmd(Connection connection, String cmd) {
        String result = "";
        try{
            if (connection != null) {
                Session session = connection.openSession ();// 打开一个会话
                session.execCommand (cmd);// 执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                System.out.println(result);
                // 如果为得到标准输出为空,说明脚本执行出错了
                /*if (StringUtils.isBlank(result)) {
                    System.out.println ("得到标准输出为空,链接 conn:" + connection + ", 执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    System.out.println ("执行命令成功,链接 conn:" + connection + ", 执行的命令:" + cmd);
                }*/
                connection.close();
                session.close();
            }
        } catch (IOException e) {
            System.out.println ("执行命令失败,链接 conn:" + connection + ", 执行的命令:" + cmd + " " + e);
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 解析脚本执行返回的结果集
     * 
     * @param in
     *            输入流对象
     * @param charset
     *            编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
                System.out.println(line);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            System.out.println ("解析脚本出错:" + e.getMessage ());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println ("解析脚本出错:" + e.getMessage ());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        long currentTimeMillis = System.currentTimeMillis();
        String ip = "192.168.115.64";
        String username = "xfraud";
        String password = "cfca1234";
        String cmd = "uname -a";        
        Connection connection = login(ip, username, password);
        String execmd = execmd(connection, cmd);
        System.out.println(execmd);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println ("ganymed-ssh2 方式"+(currentTimeMillis1-currentTimeMillis));
    }
}

 

 


转载:https://blog.csdn.net/u011937566/article/details/81666347

ci 框架的 session 类,怎么使用 ci 的 session 类

ci 框架的 session 类,怎么使用 ci 的 session 类

初始化 Session

Sessions 会在每个页面载入后开始运行,所以 session 类必须首先被初始初始化。您可以在控制器中初始化,也可以在系统中自动加载(译者注:在 autoload.php 设定)

$this->load->library(''session''); 

注意:默认情况下,Session Cookie 每隔 5 分钟才会更新一次,这样会减少对处理器的负荷。如果你重复的装载页面, 你会发现” 上次活动” 的时间在五分钟,或多余五分钟的时候才会变化,也就是 cookie 上次被写入的时间。 这个时间可以通过设置 application/config/config.php 文件里的 $config [''sess_time_to_update''] 行来改变。

取得 Session 数据

$this->session->userdata(''item'');

session_id = $this->session->userdata(''session_id''); 

添加自定义的 Session 数据

$this->session->set_userdata($array);

$newdata = array(
                       ''username''  => ''johndoe'',
                       ''email''     => ''johndoe@some-site.com'',
                       ''logged_in'' => TRUE
                   );

$this->session->set_userdata($newdata);

$this->session->set_userdata(''some_name'', ''some_value''); 

取得所有 Session 数据

$this->session->all_userdata();
Array
(
    [session_id] => 4a5a5dca22728fb0a84364eeb405b601
    [ip_address] => 127.0.0.1
    [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
    [last_activity] => 1303142623
)

删除 Session 数据

$this->session->unset_userdata(''some_name''); 

$array_items = array(''username'' => '''', ''email'' => '''');

$this->session->unset_userdata($array_items); 

 

 

 

Cloud Foundry Session Affinity(Sticky Session)的实现

Cloud Foundry Session Affinity(Sticky Session)的实现

会话保持(Session Affinity),有时又称粘滞会话(Sticky Sessions), 是负载均衡领域设计需要着力解决的重要问题之一,也是一个相对比较复杂的问题。

会话保持是指在负载均衡器上的一种机制,在完成负载均衡任务的同时,还负责一系列相关连的访问请求会分配到一台服务器上。

当用户向服务器发起请求,服务器创建一个session,并把session id以cookie的形式写回给客户。

看一个例子:当我访问SAP UI5应用时,

在http请求的头部观察到客户端要求服务器返回以cookie的形式返回session id的请求字段:

在服务器响应的头部字段果然返回了session id:

这些cookie信息能够在Chrome开发者工具的Application标签页里的Cookies区域查看:

如此一来,只要客户的浏览器不关,再去访问服务器时,访问请求会自动附上session id去,服务器端检测到这个session id后,就会使用内存中维持的与这个id对应的session为客户端服务。

再回到我们讨论的会话保持这个话题。什么时候需要会话保持?举个大家每天都会遇到的例子,大家在淘宝或者京东上购物时,从完成用户身份认证到浏览店铺,选择心仪商品加入购物车,一直到最后下单完成支付,需要经过很多次和服务器的交互过程才能完成整个交易。由于这几次交互过程从顺序上和逻辑上是密切相关的,服务器在进行这些交互过程的某一个交互步骤时需要一个上下文(Context),即上一次交互过程的输出,因此要求这些相关的交互过程都由一台服务器完成。

在这种情况下,假设负载均衡器仍然把这些相关交互session分散到不同的服务器实例上,就会带来很糟糕的用户体验,比如客户在浏览器上每点击一次,都会弹出登录页面。或者即使用户输入了正确的验证码,却仍然提示验证码错误。由于服务器处理实例不一样,也有可能造成客户放入购物车的物品丢失。

这就是会话保持机制引入的原因:确保把来自同一客户的一个完整会话的请求转发至后台同一台服务器进行处理。

那么Cloud Foundry的Session Affinity是怎么实现的呢?

官方文档有介绍:

https://docs.cloudfoundry.org/concepts/http-routing.html#sessions

(1) To support sticky sessions, configure your app to return a JSESSIONID cookie in responses. The app generates a JSESSIONID as a long hash in the following format:

您的应用在响应结果里需要加上一个JSESSIONID字段,长度如下:

1A530637289A03B07199A44E8D531427

(2) If an app returns a JSESSIONID cookie to a client request, the CF routing tier generates a unique VCAP_ID for the app instance based on its GUID in the following format:

CF routing tier基于app生成的JSESSIONID生成一个VCAP_ID: 323f211e-fea3-4161-9bd1-615392327913

(3) 接下来客户每次发起请求,必须同时提供JSESSIONID和VCAP_ID。JSESSION_ID交给应用,用于实现session粘连。而VCAP_ID用于标识服务的应用实例,如果应用挂了,gorouter会把请求路由到另一个应用实例上。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

今天关于杂记php session的讲解已经结束,谢谢您的阅读,如果想了解更多关于ASP.NET Session and Forms Authentication and Session Fixation、ch.ethz.ssh2.Session 和 com.jcraft.jsch.Session、ci 框架的 session 类,怎么使用 ci 的 session 类、Cloud Foundry Session Affinity(Sticky Session)的实现的相关知识,请在本站搜索。

本文标签: