Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Captcha.cs « RESTMethods « WebServer « Server « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ac4bec06a4cc4e9a44524f3b6b9f5bdfda27c58f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//  Copyright (C) 2016, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Linq;
using System.Collections.Generic;

namespace Duplicati.Server.WebServer.RESTMethods
{
    public class Captcha : IRESTMethodGET, IRESTMethodPOST
    {
        private class CaptchaEntry
        {
            public readonly string Answer;
            public readonly string Target;
            public int Attempts;
            public readonly DateTime Expires;

            public CaptchaEntry(string answer, string target)
            {
                Answer = answer;
                Target = target;
                Attempts = 4;
                Expires = DateTime.Now.AddMinutes(2);
            }
        }

        private static object m_lock = new object();
        private static Dictionary<string, CaptchaEntry> m_captchas = new Dictionary<string, CaptchaEntry>();

        public static bool SolvedCaptcha(string token, string target, string answer)
        {
            lock(m_lock)
            {
                CaptchaEntry tp;
                m_captchas.TryGetValue(token ?? string.Empty, out tp);
                if (tp == null)
                    return false;
                
                if (tp.Attempts > 0)
                    tp.Attempts--;
                
                return tp.Attempts >= 0 && string.Equals(tp.Answer, answer, StringComparison.OrdinalIgnoreCase) && tp.Target == target && tp.Expires >= DateTime.Now;
            }
        }

        public void GET(string key, RequestInfo info)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                info.ReportClientError("Missing token value", System.Net.HttpStatusCode.Unauthorized);
                return;
            }
            else
            {
                string answer = null;
                lock (m_lock)
                {
                    CaptchaEntry tp;
                    m_captchas.TryGetValue(key, out tp);
                    if (tp != null && tp.Expires > DateTime.Now)
                        answer = tp.Answer;
                }

                if (string.IsNullOrWhiteSpace(answer))
                {
                    info.ReportClientError("No such entry", System.Net.HttpStatusCode.NotFound);
                    return;
                }

                using (var bmp = CaptchaUtil.CreateCaptcha(answer))
                using (var ms = new System.IO.MemoryStream())
                {
                    info.Response.ContentType = "image/jpeg";
                    info.Response.ContentLength = ms.Length;
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    ms.Position = 0;

                    info.Response.ContentType = "image/jpeg";
                    info.Response.ContentLength = ms.Length;
                    info.Response.SendHeaders();
                    ms.CopyTo(info.Response.Body);
                    info.Response.Send();
                }
            }        
        }

        public void POST(string key, RequestInfo info)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                var target = info.Request.Param["target"].Value;
                if (string.IsNullOrWhiteSpace(target))
                {
                    info.ReportClientError("Missing target parameter", System.Net.HttpStatusCode.BadRequest);
                    return;
                }

                var answer = CaptchaUtil.CreateRandomAnswer(minlength: 6, maxlength: 6);
                var nonce = Guid.NewGuid().ToString();

                string token;
                using (var ms = new System.IO.MemoryStream())
                {
                    var bytes = System.Text.Encoding.UTF8.GetBytes(answer + nonce);
                    ms.Write(bytes, 0, bytes.Length);
                    ms.Position = 0;
                    token = Library.Utility.Utility.Base64PlainToBase64Url(Library.Utility.Utility.CalculateHash(ms));
                }

                lock (m_lock)
                {
                    var expired = m_captchas.Where(x => x.Value.Expires < DateTime.Now).Select(x => x.Key).ToArray();
                    foreach (var x in expired)
                        m_captchas.Remove(x);

                    if (m_captchas.Count > 3)
                    {
                        info.ReportClientError("Too many captchas, wait 2 minutes and try again", System.Net.HttpStatusCode.ServiceUnavailable);
                        return;
                    }

                    m_captchas[token] = new CaptchaEntry(answer, target);
                }

                info.OutputOK(new
                {
                    token = token
                });
            }
            else
            {
                var answer = info.Request.Param["answer"].Value;
                var target = info.Request.Param["target"].Value;
                if (string.IsNullOrWhiteSpace(answer))
                {
                    info.ReportClientError("Missing answer parameter", System.Net.HttpStatusCode.BadRequest);
                    return;
                }
                if (string.IsNullOrWhiteSpace(target))
                {
                    info.ReportClientError("Missing target parameter", System.Net.HttpStatusCode.BadRequest);
                    return;
                }

                if (SolvedCaptcha(key, target, answer))
                    info.OutputOK();
                else
                    info.ReportClientError("Incorrect", System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}