public static void WriteAddonInfo(this IAuthHandler authHandler, IPacketReader inPacket, IPacketWriter outPacket, int size) { int count = 0x100; // arbitrary number if (Authenticator.ClientBuild >= 9464) { count = inPacket.ReadInt32(); // addon count } int i = 0; while (inPacket.Position < size && i < count) { string addonName = inPacket.ReadString(); bool enabled = inPacket.ReadBool(); uint filecrc = inPacket.ReadUInt32(); uint urlcrc = inPacket.ReadUInt32(); bool requireskey = filecrc != 0x1C776D01u && filecrc != 0x4C1C776Du; // offical crcs outPacket.WriteUInt8(2); // blizzard outPacket.WriteBool(true); // enabled outPacket.WriteBool(requireskey); if (requireskey) { outPacket.Write(AddonPublicKey); } outPacket.WriteUInt32(0); // use addon url file outPacket.WriteUInt8(0); // addon url filename, cstring i++; } outPacket.WriteUInt32(0); // banned addon count }
public EventManagerMiddleware( RequestDelegate next, IOptions <EventManagerConfiguration> config ) { _next = next; _config = config.Value; EventManagerConstants.EventReceptionPath = !string.IsNullOrEmpty(_config.EventReceptionPath) ? _config.EventReceptionPath : EventManagerConstants.EventReceptionPath; EventManagerConstants.ReplyEventPrefix = !string.IsNullOrEmpty(_config.ReplyEventPrefix) ? _config.ReplyEventPrefix : EventManagerConstants.ReplyEventPrefix; EventDispatcher = EventDispatcher.Instance; foreach (SubscriptionConfiguration subscriptionConf in _config.Subscriptions) { foreach (EventSubscriberConfiguration eventSubscriberConf in subscriptionConf.Subscribers) { ExternalServiceConfiguration externalService = _config.ExternalServices.Find(x => x.Name == eventSubscriberConf.Name); if (externalService == null) { continue; } IAuthHandler auth = AuthFactory.Create(externalService.Auth); if (!auth.Valid(externalService.Config, eventSubscriberConf)) { throw new ArgumentException($"EventManagerMiddleware ERROR: externalService is not Valid for the externalService.Auth.Type `{externalService.Auth.Type}` and name `{externalService.Name}`, so it wont be registered with EventDispatcher.Register"); } else { List <Func <Event, HttpResponseMessage> > callbacks = new List <Func <Event, HttpResponseMessage> >(); Subscriber subscriber = new Subscriber(eventSubscriberConf.Name) { Config = new SubscriberConfig { MaxTries = externalService.Config.MaxRetries, RequestRate = externalService.Config.RequestRate } }; eventSubscriberConf.Endpoint = AuthFactory.Endpoint(eventSubscriberConf, externalService); Subscription subscription = new Subscription() { Subscriber = subscriber, EventName = subscriptionConf.EventName, Method = new HttpMethod(eventSubscriberConf.Method), EndPoint = eventSubscriberConf.Endpoint, CallBacks = callbacks, IsExternal = true, Auth = auth, Synchronous = eventSubscriberConf.Synchronous }; EventDispatcher.Register(subscription); } } } }
public SecurityScanWorker(ILogger <SecurityScanWorker> logger, ServiceConfig config, IWorkQueue <ScanRequest> queue, ISecurityScanner scanner, IClientFactory clientFactory, RegistryAuthenticationDecoder authDecoder, IAuthHandler authHandler) : base(logger, config, queue, clientFactory) { this.scanner = scanner; this.authDecoder = authDecoder; this.authHandler = authHandler; }
private T GetCached <T>(string scope, string key, bool isVolatile, IAuthHandler authHandler, Func <T> func) where T : class { var cache = Settings.CacheFactory?.Get <T>(); T result; if (authHandler.Authorize(scope)) { if (cache != null && cache.TryGet(key, out result)) { #if DEBUG Console.WriteLine($"Cache hit {key}"); #endif return(result); } else { #if DEBUG Console.WriteLine($"Cache miss {key}"); #endif result = func(); cache?.Set(key, result, isVolatile ? Settings.VolatileTtl : Settings.StaticTtl); return(result); } } else { throw new AuthenticationException("The request could not be authorized."); } }
public RemoteDockerClient(ServiceConfig config, IAuthHandler auth, IDockerDistribution dockerDistribution, ILocalDockerClient localClient, ICacheFactory cacheFactory) : base(config, auth) { this.dockerDistribution = dockerDistribution; this.localClient = localClient; this.cacheFactory = cacheFactory; }
/// <summary> /// Run the server. The method will not return until Stop() is called. /// </summary> public void Run() { if (authHandler == null) { authHandler = new DefaultAuthHandler(); } if (fsHandler == null) { fsHandler = new DefaultFileSystemHandler(); } if (socket == null) { socket = new TcpListener(endpoint); } socket.Start(); // listen for new connections try { while (true) { Socket peer = socket.AcceptSocket(); IPEndPoint peerPort = (IPEndPoint)peer.RemoteEndPoint; Session session = new Session(peer, bufferSize, authHandler.Clone(peerPort), fsHandler.Clone(peerPort), logHandler.Clone(peerPort)); session.Start(); sessions.Add(session); // purge old sessions for (int i = sessions.Count - 1; i >= 0; --i) { if (!sessions[i].IsOpen) { sessions.RemoveAt(i); --i; } } } } catch (SocketException) { // ignore, Stop() will probably cause this exception } finally { // close all running connections foreach (Session s in sessions) { s.Stop(); } } }
Func <HttpRequestMessage, Task <string> > ClientTokenCallback(IAuthHandler auth) => (message) => { // the Refit interface must set this header for each request, so we know what kind of token to get here. var scope = message.Headers.First(h => h.Key.Equals("X-Docker-Scope")).Value.First(); var token = auth.TokensRequired && auth.AuthorizeAsync(scope).Result ? auth.GetAuthorizationAsync(scope).Result?.Parameter : null; return(Task.FromResult(token)); };
public IndexWorker(ILogger <IndexWorker> logger, ServiceConfig config, IWorkQueue <IndexRequest> queue, IClientFactory clientFactory, IIndexStore indexStore, RegistryAuthenticationDecoder authDecoder, IAuthHandler authHandler, ICacheFactory cacheFactory) : base(logger, config, queue, clientFactory) { this.indexStore = indexStore; this.authDecoder = authDecoder; this.authHandler = authHandler; this.cacheFactory = cacheFactory; }
public SearchController(IDatabase database, ILogger <SearchController> logger, IAuthHandler authHandler, ICaptcha captcha) { _database = database; _logger = logger; _authHandler = authHandler; _captcha = captcha; }
public RepositoryController(ILoggerFactory logFactory, IAuthHandler auth, IClientFactory clientFactory, IIndexStore indexStore, IWorkQueue <IndexRequest> indexQueue, ISecurityScanner secScanner = null) : base(logFactory, auth) { this.clientFactory = clientFactory; this.logger = logFactory.CreateLogger <RepositoryController>(); this.indexStore = indexStore; this.indexQueue = indexQueue; this.secScanner = secScanner; }
public static RequestHandler GetInstance(IAuthHandler authHandler = null) { if (instance == null) { instance = new RequestHandler(authHandler); } return(instance); }
public PostController(IDatabase database, IAuthHandler authHandler, IActivityLogger activityLogger, ILogger <PostController> logger, ICaptcha captcha) { _database = database; _authHandler = authHandler; _activityLogger = activityLogger; _logger = logger; _captcha = captcha; }
public AuthController(IEMailHandler _emailHandler, IConfiguration _config, IAuthHandler _authHandler, IHostingEnvironment _hostingEnvironment, IUserProfileHandler _userProfileHandler) { authHandler = _authHandler; hostingEnviroment = _hostingEnvironment; emailHandler = _emailHandler; userProfileHandler = _userProfileHandler; config = _config; URLprotocol = config["URLprotocol"]; }
private RequestHandler(IAuthHandler authHandler) { if (authHandler == null) { this.authHandler = new AuthHandler(AuthHandler.DefaultTokenTimeout); } else { this.authHandler = authHandler; } }
public AccountController(IMemoryCache memoryCache, IAuthHandler authHandler, IWebHostEnvironment webHostEnvironment, IActivityLogger activityLogger, ILogger <AccountController> logger, ICaptcha captcha) { _memoryCache = memoryCache; _authHandler = authHandler; _webHostEnvironment = webHostEnvironment; _activityLogger = activityLogger; _logger = logger; _captcha = captcha; }
public static byte[] GetAddonInfo(this IAuthHandler authhandler, IPacketReader packet) { byte[] data = packet.ReadToEnd(); using (var msIn = new MemoryStream(data, 2, data.Length - 2)) // skip zlib header using (var dfltStream = new DeflateStream(msIn, CompressionMode.Decompress)) using (var msOut = new MemoryStream()) { dfltStream.CopyTo(msOut); return(msOut.ToArray()); } }
public WhaleratorControllerBase(ILoggerFactory logFactory, IAuthHandler auth) { LogFactory = logFactory; lazyAuthHandler = new Lazy <IAuthHandler>(() => { var credentials = User.ToRegistryCredentials(); credentials.Registry = RegistryCredentials.DockerHubAliases.Contains(credentials.Registry) ? RegistryCredentials.DockerHub : credentials.Registry.ToLowerInvariant(); auth.LoginAsync(credentials).Wait(); return(auth); }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication); }
public AuthorizationController( IAuthRepository repository, ICustomizeService serv, IOptions <AuthServiceModel> options, IAuthHandler authHandler ) { repo = repository; service = serv; _options = options; _authHandler = authHandler; }
public IDockerClient GetClient(IAuthHandler auth) { var host = auth.GetRegistryHost(config.IgnoreInternalAlias); if (string.IsNullOrEmpty(config.RegistryRoot)) { /* this is convoluted. The local client needs to call back to the remote client to fetch layers or other blobs as needed, but the remote client needs to call down * to the local client to actually load data, interperet manifests, etc. So, a circular dependency exists. Still waiting on an epiphany to make it cleaner. */ var httpClient = new HttpClient(new AuthenticatedParameterizedHttpClientHandler(ClientTokenCallback(auth))) { BaseAddress = new Uri(RegistryCredentials.HostToEndpoint(host)) }; var service = RestService.For <IDockerDistribution>(httpClient); var localClient = new LocalDockerClient(config, indexer, extractor, auth, loggerFactory.CreateLogger <LocalDockerClient>()) { RegistryRoot = config.RegistryCache, Host = host }; var remoteClient = new RemoteDockerClient(config, auth, service, localClient, cacheFactory) { Host = host }; localClient.RecurseClient = remoteClient; var cachedClient = new CachedDockerClient(config, remoteClient, cacheFactory, auth) { Host = host, CacheLocalData = config.LocalCache }; return(cachedClient); } else if (config.LocalCache) { var localClient = new LocalDockerClient(config, indexer, extractor, auth, loggerFactory.CreateLogger <LocalDockerClient>()) { RegistryRoot = config.RegistryRoot }; var cachedClient = new CachedDockerClient(config, localClient, cacheFactory, auth) { Host = host, CacheLocalData = config.LocalCache }; return(cachedClient); } else { return(new LocalDockerClient(config, indexer, extractor, auth, loggerFactory.CreateLogger <LocalDockerClient>()) { RegistryRoot = config.RegistryRoot }); } }
public AdminController( IAuthHandler authHandler, IAdminRepository repository, IAdminService serv, IOptions <AuthServiceModel> options, IMapper map ) { _authHandler = authHandler; repo = repository; service = serv; _options = options; mapper = map; }
/// <summary> /// Creates a new session, which can afterwards be started with Start(). /// </summary> public Session(Socket socket, int bufferSize, IAuthHandler authHandler, IFileSystemHandler fileSystemHandler, ILogHandler logHandler) { this.controlSocket = socket; this.dataBufferSize = bufferSize; this.authHandler = authHandler; this.fsHandler = fileSystemHandler; this.logHandler = logHandler; this.cmdRcvBuffer = new byte[CMD_BUFFER_SIZE]; this.cmdRcvBytes = 0; this.dataBuffer = new byte[dataBufferSize + 1]; // +1 for partial EOL this.randomTextIndex = new Random(); this.thread = new Thread(new ThreadStart(this.Work)); }
public async void OnAuthorization(AuthorizationFilterContext context) { Microsoft.AspNetCore.Http.IHeaderDictionary headers = context.HttpContext.Request.Headers; Microsoft.AspNetCore.Http.HttpRequest request = context.HttpContext.Request; string tokenStr = headers["Authorization"].ToString().Replace("Bearer ", ""); IAuthHandler authHandler = _builder.Create <IAuthHandler>(); AuthenticateResult authResult = await context.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); IToken token = _builder.Create <IToken>(); token.Value = tokenStr; if (authResult.Succeeded && authResult.Principal.Identity.IsAuthenticated && authHandler.Check(token)) { } else { context.Result = new ForbidResult(); } }
public async Task <T> ExecAsync(string scope, string key, TimeSpan ttl, IAuthHandler authHandler, Func <Task <T> > func) { T result; if (await authHandler.AuthorizeAsync(scope)) { if (await ExistsAsync(key)) { return(await GetAsync(key)); } else { result = await func(); await SetAsync(key, result, ttl); return(result); } } else { throw new AuthenticationException("The request could not be authorized."); } }
public Task <T> ExecAsync(string scope, string key, IAuthHandler authHandler, Func <Task <T> > func) => ExecAsync(scope, key, Ttl, authHandler, func);
public TopicController(IDatabase database, ILogger <TopicController> logger, IAuthHandler authHandler) { _database = database; _logger = logger; _authHandler = authHandler; }
public RepositoriesController(ILoggerFactory logFactory, ServiceConfig config, IAuthHandler auth, IClientFactory regFactory) : base(logFactory, auth) { this.config = config; this.clientFactory = regFactory; }
public ApiAuthController(IAuthHandler auth) => Auth = auth;
/// <summary> /// Run the server. The method will not return until Stop() is called. /// </summary> public void Run() { if (authHandler == null) authHandler = new DefaultAuthHandler(); if (fsHandler == null) fsHandler = new DefaultFileSystemHandler(); if (socket == null) socket = new TcpListener(endpoint); socket.Start(); // listen for new connections try { while (true) { Socket peer = socket.AcceptSocket(); IPEndPoint peerPort = (IPEndPoint) peer.RemoteEndPoint; Session session = new Session(peer, bufferSize, authHandler.Clone(peerPort), fsHandler.Clone(peerPort), logHandler.Clone(peerPort)); session.Start(); sessions.Add(session); // purge old sessions for (int i = sessions.Count - 1; i >= 0; --i) { if (!sessions[i].IsOpen) { sessions.RemoveAt(i); --i; } } } } catch (SocketException) { // ignore, Stop() will probably cause this exception } finally { // close all running connections foreach (Session s in sessions) { s.Stop(); } } }
public AdminService(IAdminRepository repository, IAuthHandler authHandler, IOptions <AuthServiceModel> options) { repo = repository; _authHandler = authHandler; _options = options; }
public AuthController(IAuthHandler authHandler) { this.authHandler = authHandler; }
public DistributionClient(IAuthHandler tokenSource) { _TokenSource = tokenSource; }